WordPress

Briefly unavailable for scheduled maintenance.
Check back in a some hours.
403WebShell
403Webshell
Server IP : 38.242.244.58  /  Your IP : 216.73.217.62
Web Server : Apache/2.4.41 (Ubuntu)
System : Linux vmi1486879.contaboserver.net 5.4.0-166-generic #183-Ubuntu SMP Mon Oct 2 11:28:33 UTC 2023 x86_64
User : root ( 0)
PHP Version : 7.4.3-4ubuntu2.19
Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : OFF
Directory :  /var/www/html/sura/src/Controller/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/html/sura/src/Controller/StockController.php
<?php

namespace App\Controller;

use App\Entity\Model;
use App\Entity\Release;
use App\Entity\ReportedStock;
use App\Entity\Stock;
use App\Entity\StockCategory;
use App\Entity\StockRecentViews;
use App\Entity\StockRelease;
use App\Entity\StocksCats;
use App\Entity\User;
use App\Event\VideoUploadedEvent;
use App\EventSubscriber\VideoUploadedSubscriber;
use App\Form\ReportedStockType;
use App\Form\StockType;
use App\Message\VideoUploadedNotification;
use App\Repository\CartItemRepository;
use App\Repository\CountryRepository;
use App\Repository\InvoiceItemsRepository;
use App\Repository\ModelReleaseRepository;
use App\Repository\ModelRepository;
use App\Repository\PayoutDetailsRepository;
use App\Repository\ReleaseRepository;
use App\Repository\RightManagedPricingRepository;
use App\Repository\RightReadyPricingRepository;
use App\Repository\StockCategoryRepository;
use App\Repository\StockExclusivePricingRepository;
use App\Repository\StockRecentViewsRepository;
use App\Repository\StockReleaseRepository;
use App\Repository\StockRepository;
use App\Repository\StocksCatsRepository;
use App\Repository\StockTypeRepository;
use App\Repository\UserRepository;
use App\SearchRepository\StockSearchRepository;
use App\Service\Helper;
use App\Service\ImageHelper;
use App\Service\SMS;
use App\Service\VideoHelper;
use App\Util\Mailer;
use Doctrine\ORM\EntityManager;
use FOS\ElasticaBundle\Manager\RepositoryManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use function Clue\StreamFilter\remove;

/**
 * @Route("/stock")
 */
class StockController extends AbstractController
{
    /**
     * @Route("/", name="stock_index", methods={"GET"})
     */
    public function index(StockRepository $stockRepository): Response
    {
        return $this->render('stock/index.html.twig', [
            'stocks' => $stockRepository->findAll(),
        ]);
    }

    /**
     * @Route("/new", name="stock_new", methods={"GET","POST"})
     * @param Request $request
     * @param StockCategoryRepository $stockCategoryRepository
     * @param ImageHelper $imageHelper
     * @param ReleaseRepository $releaseRepository
     * @param StockTypeRepository $stockTypeRepository
     * @return Response
     * @throws \Exception
     */
    public function new(Request $request,
                        StockRepository $stockRepository,
                        StockCategoryRepository $stockCategoryRepository,
                        ImageHelper $imageHelper,
                        StocksCatsRepository $stocksCatsRepository,
                        StockReleaseRepository $stockReleaseRepository,
                        ReleaseRepository $releaseRepository,
                        StockTypeRepository $stockTypeRepository): Response
    {
        $stock_directory=$this->getParameter('stock_directory');
        $userDir = $this->getParameter('uploads_directory').$this->getUser()->getFtpUser()->getUserId();

        $fileSystem = new Filesystem();
        $finder = new Finder();

        $em = $this->getDoctrine()->getManager();
        if(!empty($request->request))

        {
            $selected_images = $request->request->get('selected_images');
            $selected_videos = $request->request->get('selected_videos');
            $selected = explode("," , $selected_images);

            $message = null;

            $categories = explode("," , $request->request->get('category'));

            if(!empty($categories[0])){
                $category1 = $categories[0];
            }else{
                $category1 = 1;
            }
            $sameShootCode = $request->request->get("same_shoot_code");
            $noOfPeople = $request->request->get("no_of_people");

            if(!empty($categories[1])){

                $category2 = 1;
            }


            foreach($selected as $key=>$value)
            {
                if($value=="" || $value== null){
                    unset($selected[$key]);
                    continue;
                }
                //$file=$this->getParameter('ftp_directory').DIRECTORY_SEPARATOR.$value;
                $selected_file = $value;
                $file = $userDir.DIRECTORY_SEPARATOR.$selected_file;


                if($fileSystem->exists($file)) {
                    $fileObj= new File($file);
                    $ext=$fileObj->guessExtension();
                    $preview_name = uniqid('preview_').'.'.$ext;
                    $new_gif_file = null;

                    $name= uniqid('img_').'.'.$ext;

                    $new_file=$stock_directory.DIRECTORY_SEPARATOR.$name;
                    //move to stock
                    //TODO create thumbnail and add and watermark


                    $stock = new Stock();
                    $type = null;

                    //image
                    $fileSystem->copy($file,$new_file);
                    $fileSystem->remove($file);

                    $stock->setPriceLarge($request->request->get('price'));
                    $stock->setPriceSmall(number_format($request->request->get('price')/3,2));

                    $type = $stockTypeRepository->findOneBy(['title'=>'photo']);

                    $stock->setFilePath($new_file);
                    $stock->setFileName($name);
                    $stock->setCreateAt(new \DateTime());
                    $stock->setCategory($stockCategoryRepository->find($category1));
                    $stock->setCategory2($stockCategoryRepository->find($category1));
                    $stock->setContributor($this->getUser());
                    //$stock->setType($stockTypeRepository->find($request->request->get('image_type')));
                    $stock->setType($type);
                    $stock->setTitle($request->request->get('title'));
                    $stock->setSameShootCode($request->request->get('same_shoot_code'));
                    $stock->setDescription($request->request->get('title'));
                    $stock->setImageType($request->request->get('image_type'));
                    $stock->setImageSubType($request->request->get('image_sub_type'));
                    $stock->setApproveBy(null);
                    $stock->setPrice(number_format($request->request->get('price')/2,2));
                    $stock->setPeopleNo($noOfPeople);
                    $stock->setShootCode($sameShootCode);
                    $stock->setFileSize(15);
                    $stock->setStatus(0);
                    $stock->setNofityModel(true);
                    $stock->setHibernateStart(null);
                    $stock->setHibernateEnd(null);
                    $stock->setKeywords($request->request->get("keywords"));
                    $stock->setApproveAt(null);
                    $start = $stockRepository->findOneBy(['Published'=>Stock::PUBLISHED_STOCK]);
                    $stock->setSuraID( $start && $start->getSuraID() ? ((int)$start->getSuraID() + rand(12345,999999) + $start->getId()+1) : rand(12345,999999));

                    //sizes and prev
                    $imageInfo = $imageHelper->fetchImageInfo($new_file);
                    $height = $imageInfo['height'];
                    $width = $imageInfo['width'];
                    $stock->setFileHeight($height);
                    $stock->setFileWidth($width);
                    $stock->setOrientation($height >= $width ? "Portrait": "Landscape");


                    $thumb_name= uniqid('thumb_').'.'.$ext;
                    $preview_name= uniqid('preview_').'.'.$ext;
                    $small_name= uniqid('sm_').'.'.$ext;
                    $large_name= uniqid('lg_').'.'.$ext;

                    $smPath = $stock_directory.DIRECTORY_SEPARATOR.$small_name;
                    $lgPath = $stock_directory.DIRECTORY_SEPARATOR.$large_name;

                    $stock->setThumbName($thumb_name);
                    $stock->setPreviewName($preview_name);
                    $em->persist($stock);

                    //set categories
                    foreach ($categories as $category){
                        $stockCat = new StocksCats();
                        $stockCat->setCategoryStockCat($stockCategoryRepository->find($category));
                        $stockCat->setStock($stock);
                        $em->persist($stockCat);
                    }

                    $releases = $request->request->get('releases');

                    if( $releases === "null"){

                    }else{
                        $releases=explode(',',$request->request->get('releases'));
                        $releasePercentage = $request->request->get('release_percentage');
                        foreach ($releases as $release){
                            $releaseEntity=$releaseRepository->find($release);
                            if($releaseEntity){
                                $stockRelease= new StockRelease();
                                $stockRelease->setTheRelease($releaseEntity);
                                $stockRelease->setTheStock($stock);
                                $stockRelease->setPercentage($releasePercentage);
                                $em->persist($stockRelease);
                            }

                        }
                    }

                    $em->flush();

                    //remove imgThumb
                    $thumbFile = $userDir.DIRECTORY_SEPARATOR.Stock::IMAGE_THUMBS_DIR.DIRECTORY_SEPARATOR.$selected_file;
                    if (file_exists($thumbFile)){
                        $fileSystem->remove($thumbFile);
                    }

                    //recreate files
                    try {
//                        dd($new_file);
                        $imageHelper->generate($new_file,$stock);
                    }catch (\Exception $exception){
                       // dd($exception->getMessage());
                        //remove cause of error
                        $stockCats = $stocksCatsRepository->findBy(['stock'=>$stock]);
                        $stockReleases = $stockReleaseRepository->findBy(['TheStock'=>$stock]);
                        foreach ($stockCats as $stockCat){
                            $em->remove($stockCat);
                        }
                        foreach ($stockReleases as $stockRelease){
                            $em->remove($stockRelease);
                        }
                        $largeFile = $stock->getLargeImagePath();
                        $mediumFile = $stock->getFilePath();
                        $smallFile = $stock->getSmallImagePath();
                        $prevFile = $this->getParameter('stock_directory').DIRECTORY_SEPARATOR.$stock->getPreviewName();
                        $thumbFile = $this->getParameter('stock_directory').DIRECTORY_SEPARATOR.$stock->getThumbName();

                        $this->removeFile($largeFile);
                        $this->removeFile($mediumFile);
                        $this->removeFile($smallFile);
                        $this->removeFile($prevFile);
                        $this->removeFile($thumbFile);

                        $em->remove($stock);
                        $em->flush();

                        $message="One of your files has been removed. Please check your file and try again";
                    }
//                    $imageHelper->reGenerateImage($stock,$this->getParameter('stock_directory'));
                    /*$em->persist($stock);
                    $em->flush();*/

                }

            }
            return new JsonResponse(['success'=>1, 'message'=>$message]);

        }

    }

    /**
     * @Route("/images", name="stock_images", methods={"GET","POST"})
     * @param Request $request
     * @param StockRepository $stockRepository
     * @param StockCategoryRepository $categoryRepository
     * @param ReleaseRepository $releaseRepository
     * @param StockTypeRepository $stockTypeRepository
     * @return Response
     */
    public function images(Request $request,
                           StockRepository $stockRepository,
                           StockCategoryRepository $categoryRepository,
                           ReleaseRepository $releaseRepository,
                           StockTypeRepository $stockTypeRepository): Response
    {
        $categories = $categoryRepository->findAll();

        $finder = new Finder();
        $storage_dir=$this->getParameter('uploads_directory');

        $entityManager = $this->getDoctrine()->getManager();
        $currentUser=$this->getUser();
        $ftpPath = $storage_dir.$currentUser->getFtpUser()->getUserId();
        $imageThumbsPath = $ftpPath.DIRECTORY_SEPARATOR.Stock::IMAGE_THUMBS_DIR;
//dump($imageThumbsPath); die;

        if (!is_dir($imageThumbsPath)){
            mkdir($imageThumbsPath,0777,true);
        }
        $files = $finder->files()->in($imageThumbsPath);
        $filesToSubmit = [];
        $imageExtensions = ["jpg", "JPG", "jpeg", "png", "PNG"];
        /**
         * @var File $file
         */
        foreach ($files as $file){
            if (in_array($file->getExtension(),$imageExtensions) ){
                array_push($filesToSubmit, $file);
            }
        }
        $imageType = $stockTypeRepository->findOneBy(['title'=>'photo']);
        $releases=$releaseRepository->findBy(['createBy'=>$currentUser]);
        $reviewedStock=$stockRepository->findBy(['contributor'=>$currentUser,'status'=>Stock::APPROVED_STOCK, 'type'=>$imageType]);
        $pendingStock=$stockRepository->findBy(['contributor'=>$currentUser,'status'=>Stock::PENDING_STOCK, 'type'=>$imageType]);
        $rejectedStock=$stockRepository->findBy(['contributor'=>$currentUser,'status'=>Stock::REJECTED_STOCK, 'type'=>$imageType]);
        //dump($pendingStock);die;
        $uploads=array();
        /** @var SplFileInfo $file */

        return $this->render('stock/images.html.twig', [
            'files' => $filesToSubmit,
            'uploads' => $uploads,
            'reviewedStock' => $reviewedStock,
            'pendingStock' => $pendingStock,
            'categories' => $categories,
            'releases' => $releases,
            'rejectedStock' => $rejectedStock

        ]);
    }


    /**
     * @Route("/images/upload", name="stock_images_upload", methods={"GET","POST"})
     * @param Request $request
     * @param StockCategoryRepository $categoryRepository
     * @param ReleaseRepository $releaseRepository
     * @return Response
     */
    public function images_upload(Request $request,StockCategoryRepository $categoryRepository,ReleaseRepository $releaseRepository): Response
    {
        $categories=$categoryRepository->findAll();

        $finder = new Finder();
        $storage_dir=$this->getParameter('ftp_directory');
        $entityManager = $this->getDoctrine()->getManager();
        $currentUser=$this->getUser();
        $ftpPath = is_dir($storage_dir . '/' . $currentUser->getUsernameCanonical())
                    ? $storage_dir . '/' . $currentUser->getUsernameCanonical()
                    : is_dir($storage_dir . '/' . $currentUser->getUsername())
                        ? $storage_dir . '/' . $currentUser->getUsername()
                        : $storage_dir . '/' . $currentUser->getUsernameCanonical();
        if (!is_dir($ftpPath)){
            mkdir($ftpPath, 0777,true);
        }
        $files = $finder->files()->in($ftpPath);
        $releases=$releaseRepository->findBy(['createBy'=>$currentUser]);
        $uploads=array();
        /** @var SplFileInfo $file */
        foreach ($files as $file){
            $upload= new Stock();
//            $upload->setFile($file);
            $upload->setContributor($currentUser);
            $upload->setFileName($file->getFilename());
            $uploads[]=$upload;
        }
        return $this->render('stock/images_upload.html.twig', [
            'files' => $files,
            'uploads' => $uploads,
            'categories' => $categories,
            'releases' => $releases,

        ]);
    }
    /**
     * @Route("/{image}/delete_file", name="stock_delete_file", methods={"GET","POST"})
     * @param Request $request
     * @return Response
     */
    public function delete_file(Request $request)
    {
        $currentUser=$this->getUser();
        $storage_dir=$this->getParameter('ftp_directory');
        $ftpPath = is_dir($storage_dir . '/' . $currentUser->getUsernameCanonical())
                    ? $storage_dir . '/' . $currentUser->getUsernameCanonical()
                    : $storage_dir . '/' . $currentUser->getUsername();
        $image=$request->get('image');
        $file_path=$ftpPath.'/'.$image;
        $file_system = new Filesystem();
        $file_system->remove([$file_path]);


        return new Response(0);

    }

    /**
     * @Route("/check-hibernated", name="stock_check_hibernated", methods={"GET","POST"})
     * @param Request $request
     * @param StockRepository $stockRepository
     * @return void
     * @throws \Exception
     */
    public function check_hibernated(Request $request, StockRepository $stockRepository)
    {
        $stock = $stockRepository->findAll();
        foreach ($stock as $item)
        {
            if($item->getHibernateEnd() >= new \DateTime())
            {
                $item->setHibernated(0);
            }
        }

    }

    /**
     * @Route("/details/{id}", name="image_details", methods={"GET","POST"})
     * @param Stock $stock
     * @param Request $request
     * @param CountryRepository $countryRepository
     * @param StockExclusivePricingRepository $stockExclusivePricingRepository
     * @param StockCategoryRepository $categoryRepository
     * @param ReleaseRepository $releaseRepository
     * @param RightManagedPricingRepository $rightManagedPricingRepository
     * @param RightReadyPricingRepository $rightReadyPricingRepository
     * @param StockRepository $stockRepository
     * @param StockRecentViewsRepository $stockRecentViewsRepository
     * @param RepositoryManagerInterface $manager
     * @param ImageHelper $imageHelper
     * @param StockTypeRepository $stockTypeRepository
     * @return Response
     * @throws \Exception
     */
    public function imageDetails(Stock $stock,
                                 Request $request,
                                 CountryRepository $countryRepository,
                                 StockExclusivePricingRepository $stockExclusivePricingRepository,
                                 StockCategoryRepository $categoryRepository,
                                 ReleaseRepository $releaseRepository,
                                 RightManagedPricingRepository $rightManagedPricingRepository,
                                 RightReadyPricingRepository $rightReadyPricingRepository,
                                 StockRepository $stockRepository,
                                 StockRecentViewsRepository $stockRecentViewsRepository,
                                 RepositoryManagerInterface $manager,
                                 ImageHelper $imageHelper,
                                 VideoHelper $videoHelper,
                                 StockTypeRepository $stockTypeRepository)
    {

        $currentUser=$this->getUser();
        $em = $this->getDoctrine()->getManager();

        //recent views
        $stockRecentView = $stockRecentViewsRepository->findOneBy(['user'=>$currentUser, 'stock'=>$stock]);

        if ($stockRecentView){
            //update time
            $stockRecentView->setViewedAt(new \DateTime());
        }else{
            //create
            $stockRecentView = new StockRecentViews();
            $stockRecentView->setStock($stock);
            $stockRecentView->setUser($currentUser);
            $stockRecentView->setViewedAt(new \DateTime());
        }
        $em->persist($stockRecentView);

        $reported_stock = new ReportedStock();
        $reported_stock->setStock($stock);
        $reported_stock->setSource($currentUser);
        $reported_stock->setReportDate(new \DateTime());
        $form = $this->createForm(ReportedStockType::class, $reported_stock);

        $categories=$categoryRepository->findAll();
//        $exclusive_pricing = $stockExclusivePricingRepository->findAll()[0];
        $exclusive_pricing = $stockExclusivePricingRepository->findOneBy(['stockType' => $stock->getType()]);
        $right_managed_pricing =$rightManagedPricingRepository->find(1);
        $right_ready_pricing =$rightReadyPricingRepository->find(1);
        $countries = $countryRepository->findAll();
        $views = (int)$stock->getViews();
        $stock->setViews($views + 1);

        $em->persist($stock);
        $em->flush();
        $releases=$releaseRepository->findBy(['createBy'=>$currentUser]);

        //same shoot stock
        $sameShootStock = null;
        $shootCode = $stock->getSameShootCode();

        if ($shootCode){
            $sameShootStock = $stockRepository->findSimilarShootStock($stock);
        }


        //$stockReleasesRepo = $em->getRepository(StockRelease::class);
        $stockReleases = $stock->getStockReleases();
        $theReleaseRepo = $em->getRepository(Release::class);

        $stocks = [];
        //$models = [];
        foreach ($stockReleases as $stockRel){

            $relFileId = $stockRel->getTheRelease()->getId();

            $rel = $theReleaseRepo->find($relFileId);

            $model = $rel->getModel();
            $theReleaseFiles = $theReleaseRepo->findBy(["model" => $model]);

            foreach ($theReleaseFiles as $relFile){
                $stockReleasesForAll = $relFile->getStockReleases();
                foreach ($stockReleasesForAll as $stockRelease){
                    $stockForModel = $stockRelease->getTheStock();
                    if (!in_array($stockForModel,$stocks)){
                        if ($stockForModel->getStatus() == Stock::PUBLISHED_STOCK && $stockForModel->getId() != $stock->getId() && $stockForModel->getType() === $stock->getType()){
                            array_push($stocks, $stockForModel);
                        }
                    }
                    //$models[$stockForModel->getId()] = $model;
                }
            }
        }

        /**@var $stockSearchRepo StockSearchRepository**/
        $stockSearchRepo = $manager->getRepository(Stock::class);
        $similarStocks = $stockSearchRepo->search_similar_stock($stock);
        //dump($similarStocks);die;
        //sizes
        $width=null;
        $height=null;
        $smallWidth=null;
        $smallHeight=null;
        $largeWidth=$stock->getFileWidth();
        $largeHeight=$stock->getFileHeight();

//        $file=new File($stock->getFilePath());

        $fileSize = null; //number_format($file->getSize() / 1048576, 1);
        $smallSize=null;
        $largeSize=null;

        $smallDPI=null;
        $mediumDPI=null;
        $largeDPI=null;

        if ($stock->getType() === $stockTypeRepository->findOneBy(['title'=>'photo'])) {
            try{
                //medium
                if (is_file($stock->getFilePath())){
                    $mediumFile=getimagesize($stock->getFilePath());
                    $width=$mediumFile[0];
                    $height=$mediumFile[1];
                    $file=new File($stock->getFilePath());
                    $fileSize = number_format($file->getSize() / 1000000, 1);
                    $xResolution = $imageHelper->fetchImageInfo($stock->getFilePath())['exifs']['XResolution'];

                    $resolutionAr = explode("/",strval($xResolution));
                    $resolution = $resolutionAr[0]/$resolutionAr[1];
                    $mediumDPI = $resolution;
                }
            }catch (\Exception $exception){
                //
            }
            try{
                //small
               $smallFile=getimagesize($stock->getSmallImagePath());
               $smallWidth=$smallFile[0];
               $smallHeight=$smallFile[1];
                $file=new File($stock->getSmallImagePath());
                $smallSize = number_format($file->getSize() / 1000000, 1);
                $xResolution = $imageHelper->fetchImageInfo($stock->getSmallImagePath())['exifs']['XResolution'];
                $resolutionAr = explode("/",strval($xResolution));
                $resolution = $resolutionAr[0]/$resolutionAr[1];
                $smallDPI = $resolution;
             }catch (\Exception $exception){
                //
            }
            try{
                //large
                $file=new File($stock->getLargeImagePath());
                $largeSize = number_format($file->getSize() / 1000000, 1);
                $xResolution = $imageHelper->fetchImageInfo($stock->getLargeImagePath())['exifs']['XResolution'];
                $resolutionAr = explode("/",strval($xResolution));
                $resolution = $resolutionAr[0]/$resolutionAr[1];
                $largeDPI = $resolution;
           }catch (\Exception $exception){
//                dd($exception->getMessage());
           }
        }else if (strtolower($stock->getType()->getTitle()) == 'video'){
            //video - fetch details
            $lgVid = $stock->getLargeImagePath();
            $smVid = $stock->getSmallImagePath();
            $mdVid = $stock->getFilePath();

            //fps && width && height && res
            $metaLarge = $videoHelper->fetchVideoMetaData($lgVid);
            $metaMediun = $videoHelper->fetchVideoMetaData($mdVid);
            $metaSmall = $videoHelper->fetchVideoMetaData($smVid);

            $medium_width = $metaMediun['width'];
            $medium_height = $metaMediun['height'];
            $medium_resolution = $metaMediun['resolution'];
            $medium_fps = $metaMediun['fps'];
            $medium_size = $metaMediun['size'];

            $large_width = $metaLarge['width'];
            $large_height = $metaLarge['height'];
            $large_resolution = $metaLarge['resolution'];
            $large_fps = $metaLarge['fps'];
            $large_size = $metaLarge['size'];

            $small_width = $metaSmall['width'];
            $small_height = $metaSmall['height'];
            $small_resolution = $metaSmall['resolution'];
            $small_fps = $metaSmall['fps'];
            $small_size = $metaSmall['size'];
        }

        $releases = $stock->getStockReleases();

        $releaseInfo = count($releases) > 0;

        /*$fileName = "suraimages_".$stock->getId()."_".ucfirst($stock->getTitle()).".".$file->getExtension();

        ob_start();
        header('Content-Disposition: Inline; filename="'.$fileName.'"');
        ob_end_flush();
        flush();*/


        return $this->render('stock/details.html.twig', [
            'image' => $stock,
            'releaseInfo' => $releaseInfo,
            'categories'=>$categories,
            'releases' =>$releases,
            'exclusivePricing' => $exclusive_pricing,
            'rightManagedPricing' => $right_managed_pricing,
            'rightReadyPricing' => $right_ready_pricing,
            'countries' => $countries,
            'form' => $form->createView(),
            'sammeShootStock' => $sameShootStock,
            "sameModelStocks" => $stocks,
            "similarStocks" => $similarStocks,
            "stockTypes" =>$stockTypeRepository->findAll(),
            "largeWidth"=>$largeWidth,
            "largeHeight"=>$largeHeight,
            "smallWidth"=>$smallWidth,
            "smallHeight"=>$smallHeight,
            "width"=>$width,
            "height"=>$height,
            'fileSize'=>$fileSize,
            'smallSize'=>$smallSize,
            'largeSize'=>$largeSize,
            'mediumSize'=>$fileSize,
            'smallDPI' => $smallDPI,
            'mediumDPI' => $mediumDPI,
            'largeDPI' => $largeDPI,
            //'models' => $models

            #video
            'video_medium_res' => $medium_resolution ?? null,
            'video_medium_width' => $medium_width ?? null,
            'video_medium_height' => $medium_height ?? null,
            'video_medium_fps' => $medium_fps ?? null,
            'video_medium_size' => $medium_size ?? null,

            'video_small_res' => $small_resolution ?? null,
            'video_small_width' => $small_width ?? null,
            'video_small_height' => $small_height ?? null,
            'video_small_fps' => $small_fps ?? null,
            'video_small_size' => $small_size ?? null,

            'video_large_res' => $large_resolution ?? null,
            'video_large_width' => $large_width ?? null,
            'video_large_height' => $large_height ?? null,
            'video_large_fps' => $large_fps ?? null,
            'video_large_size' => $large_size ?? null,
        ]);



    }

    /**
     * @Route("/{image}/delete_file", name="stock_delete_file", methods={"GET","POST"})
     * @param Request $request
     * @param StockRepository $stockRepository
     * @param CartItemRepository $cartItemRepository
     * @param InvoiceItemsRepository $invoiceItemsRepository
     * @param StockCategoryRepository $categoryRepository
     * @param StockRecentViewsRepository $stockRecentViewsRepository
     * @return Response
     */
    public function delete_images(Request $request,
                                  StockRepository $stockRepository,
                                  CartItemRepository $cartItemRepository,
                                  InvoiceItemsRepository $invoiceItemsRepository,
                                  StockCategoryRepository $categoryRepository,
                                  StockRecentViewsRepository $stockRecentViewsRepository)
    {
        $currentUser=$this->getUser();
        $imagename = $request->get("image");
        $fileType = $request->get("fileType");
        $stockType = $request->get("stockType");

        $storage_dir=$this->getParameter('uploads_directory');
        $stock_directory=$this->getParameter('stock_directory');

        $thumb_nail_file = $storage_dir.$currentUser->getFtpUser()->getUserId().DIRECTORY_SEPARATOR.Stock::IMAGE_THUMBS_DIR.DIRECTORY_SEPARATOR.$imagename;

        if (file_exists($thumb_nail_file)){
            $this->removeFile($thumb_nail_file);
        }

        if ($fileType === "to-submit"){

            $filePath =  $storage_dir.$currentUser->getFtpUser()->getUserId();
            $file = null;
            if (file_exists($filePath.DIRECTORY_SEPARATOR.$imagename)){
                $file = new File($filePath.DIRECTORY_SEPARATOR.$imagename);

                //if video get the mp4 file & remove
                if ($stockType == "video"){
                    $vid_file_name = str_replace("gif","mp4",$file->getFilename());
                    $vidFile = new File($filePath.DIRECTORY_SEPARATOR.$vid_file_name);
                    $this->removeFile($vidFile);
                }
            }

        }
        else if ($fileType === "pending" || $fileType === "approved" || $fileType === "rejected" ){
            $filePath=$this->getParameter('stock_directory');

            $stck=$stockRepository->findOneBy(['FileName'=>$imagename]);
            $file_path = $stck->getType()->getId() == 4 ? $stck->getFilePath() : $stck->getLargeImagePath();
            if (!file_exists($file_path)){
                $file_path = $stck->getFilePath();
                if (!file_exists($file_path)){
                    return new JsonResponse(0);
                }
            }
            $file = new File($file_path);
            $em = $this->getDoctrine()->getManager();
            $stock = $stck;

            if ($stock){
                //check if in invoice
                $invoiceItems = $invoiceItemsRepository->findBy(['Stock' => $stock]);
                if(count($invoiceItems) > 0){
                    return new Response(0);
                }

                //check if in cart
                $cartItems = $cartItemRepository->findBy(['Stock' => $stock]);
                foreach ($cartItems as $cartItem){
                    $cart = $cartItem->getCart();
                    $cart_item_amount = $cartItem->getAmount();
                    $cart->setTotal($cart->getTotal() - $cart_item_amount);
                    $em->persist($cart);
                    $em->remove($cartItem);
                }
                //check if is featured in StockCategory
                $categories = $categoryRepository->findBy(['featuredStock' => $stock]);
                foreach ($categories as $category){
                    $category->setFeaturedStock(null);
                    $em->persist($category);
                }
                //check categories in stockcats
                $stockCats = $stock->getStocksCats();
                foreach ($stockCats as $stockCat){
                    $em->remove($stockCat);
                }

                //check in recent views
                $recentViews = $stockRecentViewsRepository->findBy(['stock'=>$stock]);
                foreach ($recentViews as $recentView){
                    $em->remove($recentView);
                }

                $releases = $stock->getStockReleases();
                foreach ($releases as $release){
                    $em->remove($release);
                }
                //get the thumbnail $ preview & del
                $prevFileName = $stock->getPreviewName();
                $thumbFileName = $stock->getThumbName();
                $smImgPath = $stock->getSmallImagePath();
                $lgImgPath = $stock->getLargeImagePath();
                $smImg = null;
                $lgImg = null;
                $prevFile = null;
                $thumbFile = null;

                if ($smImgPath){
                    try{
                        $smImg = new File($smImgPath);
                    }catch (FileException $exception){
                        //
                    }
                }
                if ($lgImgPath){
                    try{
                        $lgImg = new File($lgImgPath);
                    }catch (FileException $exception){
                        //
                    }
                }
                if ($prevFileName){
                    try{
                        $prevFile = new File($filePath.DIRECTORY_SEPARATOR.$prevFileName);
                    }catch (FileException $exception){
                        //
                    }
                }
                if ($thumbFileName){
                    try{
                        $thumbFile = new File($filePath.DIRECTORY_SEPARATOR.$thumbFileName);
                    }catch (FileException $exception){
                        //
                    }
                }

                //FOR APPROVED VIDEOS
                if ($stock->getSearchPageVideoName() && !empty($stock->getSearchPageVideoName())){
                    if (is_file($stock_directory.DIRECTORY_SEPARATOR.$stock->getSearchPageVideoName())){
                        $this->removeFile($stock_directory.DIRECTORY_SEPARATOR.$stock->getSearchPageVideoName());
                    }
                    $stock->setSearchPageVideoName(null);
                }
                if ($stock->getSharableImage() && !empty($stock->getSharableImage())){
                    if (is_file($stock_directory.DIRECTORY_SEPARATOR.$stock->getSharableImage())){
                        $this->removeFile($stock_directory.DIRECTORY_SEPARATOR.$stock->getSharableImage());
                    }
                    $stock->setSharableImage(null);
                }

                $shareable = $filePath.DIRECTORY_SEPARATOR.$stock->getSharableImage();

                $this->removeFile($shareable);
                $this->removeFile($smImg);
                $this->removeFile($lgImg);
                $this->removeFile($prevFile);
                $this->removeFile($thumbFile);

                $em->remove($stock);
                $em->flush();
            }

        }
        else{

            //delete from history
            $stocksDir=$this->getParameter('stock_directory');
            $stock = $stockRepository->findOneBy(["FileName" => $imagename]);

            $filePath = $stock->getFilePath();
            $file=null;

            if (file_exists($filePath)){
                $file = new File($filePath);
            }

            $em = $this->getDoctrine()->getManager();

            if ($stock){
                //check if in invoice
                $invoiceItems = $invoiceItemsRepository->findBy(['Stock' => $stock]);
                $tracker = false;
                if(count($invoiceItems) > 0){

                    foreach ($invoiceItems as $item)
                    {
                        if($item->getInvoice()->getStatus() != 'paid' || $item->getInvoice()->getStatus() != 'processing' )
                        {
                            $em->remove($item);
                            $em->flush();
                        }else{
                            $tracker = true;
                        }

                    }
                    if($tracker)
                    {
                        $this->addFlash("delete_message", "The stock cannot be deleted because it is in a member's invoice. This will be useful when tracking transactions.");
                        return $this->redirectToRoute("all_image_uploads");
                    }


                }

                //check if in cart
                $cartItems = $cartItemRepository->findBy(['Stock' => $stock]);
                foreach ($cartItems as $cartItem){
                    $cart = $cartItem->getCart();
                    $cart_item_amount = $cartItem->getAmount();
                    $cart->setTotal($cart->getTotal() - $cart_item_amount);
                    $em->persist($cart);
                    $em->remove($cartItem);
                }

                //check if is featured in StockCategory
                $categories = $categoryRepository->findBy(['featuredStock' => $stock]);
                foreach ($categories as $category){
                    $category->setFeaturedStock(null);
                    $em->persist($category);
                }

                //check categories in stockcats
                $stockCats = $stock->getStocksCats();
                foreach ($stockCats as $stockCat){
                    $em->remove($stockCat);
                }

                $releases = $stock->getStockReleases();
                foreach ($releases as $release){
                    $em->remove($release);
                }

                //check recent views
                $recentViews = $stockRecentViewsRepository->findBy(['stock'=>$stock]);
                if (count($recentViews) > 0){
                    foreach ($recentViews as $recentView){
                        $em->remove($recentView);
                    }
                }

                //get the thumbnail $ preview & del
                $prevFileName = $stock->getPreviewName();
                $thumbFileName = $stock->getThumbName();
                $smImgPath = $stock->getSmallImagePath();
                $lgImgPath = $stock->getLargeImagePath();

                $smImg =  file_exists($smImgPath) ? new File($smImgPath): null;
                $lgImg = file_exists($lgImgPath) ? new File($lgImgPath): null;
                $prevFile = file_exists($prevFileName) ? new File($filePath.DIRECTORY_SEPARATOR.$prevFileName): null;
                $thumbFile = file_exists($thumbFileName) ? new File($filePath.DIRECTORY_SEPARATOR.$thumbFileName): null;

                $this->removeFile($smImg);
                $this->removeFile($lgImg);
                $this->removeFile($prevFile);
                $this->removeFile($thumbFile);


                $em->remove($stock);
                $em->flush();
                $file_system = new Filesystem();
                if ($file != null){
                    $file_system->remove([$file]);
                }
                $this->addFlash("delete_message", "The stock has been deleted successfully.");
                return $this->redirectToRoute("all_image_uploads");
            }
        }

        if ($file && file_exists($file)){
            $this->removeFile($file);
        }

//        return new Response(1);
        return $this->redirectToRoute("all_image_uploads");
    }

    public function removeFile($file){
        /**
         * @var File $file
         */
        $file_system = new Filesystem();
        if ($file != null){
            if (is_file($file)){
                $file_system->remove([$file]);
            }
        }
    }

    /**
     * @Route("/models", name="stock_models", methods={"GET","POST"})
     */
    public function models(Request $request,ModelRepository $modelRepository): Response
    {
        $finder = new Finder();
        $storage_dir=$this->getParameter('ftp_directory');
        $entityManager = $this->getDoctrine()->getManager();
        $currentUser=$this->getUser();
        $myModels=$modelRepository->findBy(['createdBy'=>$currentUser]);
        return $this->render('stock/models.html.twig', [
            'currentUser' => $currentUser,
            'myModels' => $myModels,


        ]);
    }

    /**
     * @Route("/exclusive-licenced-stock", name="exclusive-licenced-stock", methods={"GET","POST"})
     * @param Request $request
     * @param StockRepository $stockRepository
     * @param Mailer $mailer

     */
    public function exclusiveLicencedStock(Request $request,StockRepository $stockRepository, Mailer $mailer,Filesystem $filesystem): Response
    {
        $stocks = $stockRepository->findAll();

        $logs_dir =$this->getParameter('logs_directory');
        $file_system = new Filesystem();

        if (!is_dir($logs_dir)) {
            mkdir($logs_dir, 0777, true);
            $file_system->chown($logs_dir, "www-data");
            $file_system->chgrp($logs_dir, "www-data");
        }

        $log_file = $logs_dir.'/cron_logs.txt';

        if(!is_file($logs_dir.'/cron_logs.txt'))
        {
            $file_system->touch($logs_dir.'/cron_logs.txt');
            $log_file = $logs_dir.'/cron_logs.txt';
           // $filesystem->chmod($logs_dir, 0777);
        }

        //$filesystem->chmod($log_file, 0777);
        $date = new \DateTime();
        $description = "Running Cron for exclusive licenced stocks ";

        $data = sprintf("\n[%s]   -   %s", $date->format('h:i:s, Y-m-d'), $description);


       // dd(is_file($log_file));

        file_put_contents($log_file,$data, FILE_APPEND);

        foreach ($stocks as $stock)
        {
            if(!empty($stock->getExclusiveLicenceHolder()))
            {
                $today = new \DateTime();

                $exclusiveLicenceExpiryDate = $stock->getHibernateEnd();

                $diff =  $today->diff($exclusiveLicenceExpiryDate);

                $days =(int)$diff->format('%R%a');

                $url = $this->generateUrl('renew_exclusive_licence',["id"=>$stock->getId()],UrlGeneratorInterface::ABSOLUTE_URL);

                if($days === 14)
                {
                    $mailer->sendExclusiveLicenceExpiryNotification($url,$stock,$stock->getExclusiveLicenceHolder(),$days);


                }else if ($days === 7)
                {
                    $mailer->sendExclusiveLicenceExpiryNotification($url,$stock,$stock->getExclusiveLicenceHolder(),$days);

                }else if ($days === 3)
                {
                    $mailer->sendExclusiveLicenceExpiryNotification($url,$stock,$stock->getExclusiveLicenceHolder(),$days);

                }else if ($days === 0)
                {
                    $mailer->sendExclusiveLicenceExpiryNotification($url,$stock,$stock->getExclusiveLicenceHolder(),$days);

                    //un-hibernate the file
                    $stock->setHibernated(false);
                    $stock->setExclusiveLicenceHolder(null);
                    $stock->setHibernateStart(null);
                    $stock->setHibernateEnd(null);
                    $em = $this->getDoctrine()->getManager();
                    $em ->persist($stock);
                    $em->flush();

                }

                else if ($days < 0)
                {
                    $mailer->sendExclusiveLicenceExpiryNotification($url,$stock,$stock->getExclusiveLicenceHolder(),$days);

                    //un-hibernate the file
                    $stock->setHibernated(false);
                    $stock->setExclusiveLicenceHolder(null);
                    $stock->setHibernateStart(null);
                    $stock->setHibernateEnd(null);
                    $em = $this->getDoctrine()->getManager();
                    $em ->persist($stock);
                    $em->flush();

                }

            }else if ($stock->getHibernated() && $stock->getHibernateEnd() != null){

                //hibernated by admin
                $today = new \DateTime();

                $hibernation_end = $stock->getHibernateEnd();

                $diff =  $today->diff($hibernation_end);

                $days =(int)$diff->format('%R%a');
                if ($days < 0 || $days === 0)
                {
                    //un-hibernate the file
                    $stock->setHibernated(false);
                    $stock->setExclusiveLicenceHolder(null);
                    $stock->setHibernateStart(null);
                    $stock->setHibernateEnd(null);
                    $em = $this->getDoctrine()->getManager();
                    $em ->persist($stock);
                    $em->flush();

                }
            }
        }

        die;


    }

    /**
     * @Route("/list", name="stock_list", methods={"GET","POST"})
     * @param Request $request
     * @param StockRepository $stockRepository
     * @param StockCategoryRepository $categoryRepository
     * @param ReleaseRepository $releaseRepository
     * @return Response
     */
    public function list(Request $request, StockRepository $stockRepository, StockCategoryRepository $categoryRepository, ReleaseRepository $releaseRepository): Response
    {
        $categories = $categoryRepository->findAll();

        $finder = new Finder();
        $storage_dir=$this->getParameter('ftp_directory');

        $entityManager = $this->getDoctrine()->getManager();
        $currentUser=$this->getUser();
        $ftpPath = is_dir($storage_dir . '/' . $currentUser->getUsernameCanonical())
                    ? $storage_dir . '/' . $currentUser->getUsernameCanonical()
                    : $storage_dir . '/' . $currentUser->getUsername();
        $files = $finder->files()->in($ftpPath);

        $releases=$releaseRepository->findBy(['createBy'=>$currentUser]);
        $pendingStock=$stockRepository->findBy(['contributor'=>$currentUser]);
        $uploads=array();
        /** @var SplFileInfo $file */

        return $this->render('stock/list.html.twig', [
            'files' => $files,
            'uploads' => $uploads,

            'pendingStock' => $pendingStock,
            'categories' => $categories,
            'releases' => $releases,

        ]);
    }
    /**
     * @Route("/{id}", name="stock_show", methods={"GET"})
     */
    public function show(Stock $stock): Response
    {
        $deductions=0;
        $deduction= $stock->getPriceLarge() * 0.4;
        $payouts=[
            'Sura Images'=>[
                'percentage'=>0.4,
                'amount'=>$deduction
            ]
        ];
//        $deductions+=$deduction;
        $contAmount=$stock->getPriceLarge() -$deduction;

        foreach ($stock->getStockReleases() as $stockRelease){
            /** @var  $release */
            $release=$stockRelease->getTheRelease();

            $deduction= $stock->getPrice() * ($release->getPayoutPercent()/100);
            $deductions+=$deduction;
            $payouts[$release->getTitle()]=[
                'percentage'=>$release->getPayoutPercent()/100,
                'amount'=>$deduction
            ];
        }
        return $this->render('stock/show.html.twig', [
            'stock' => $stock,
            'image' => $stock,
            'deductions' => $deductions,
            'payouts' => $payouts,
            'nett' => $contAmount-$deductions,

        ]);
    }

    /**
     * @Route("/{id}/process", name="stock_process", methods={"GET"})
     */
    public function process(Stock $stock,ImageHelper $imageHelper): Response
    {
        $imageHelper->generate($stock->getFilePath(),$stock);

        return new Response(0);

    }


    /**
     * @Route("/{id}/renew-exclusive-licence/", name="renew_exclusive_licence", methods={"GET"})
     * @param Stock $stock
     * @param RepositoryManagerInterface $manager
     * @param StockExclusivePricingRepository $stockExclusivePricingRepository
     * @param StockRepository $stockRepository
     * @return Response
     */
    public function renewLicence(Stock $stock, RepositoryManagerInterface $manager, StockExclusivePricingRepository $stockExclusivePricingRepository,  StockRepository $stockRepository): Response
    {

        $exclusive_pricing = $stockExclusivePricingRepository->findOneBy(['stockType' => $stock->getType()]);
        /**@var $stockSearchRepo StockSearchRepository**/
        $stockSearchRepo = $manager->getRepository(Stock::class);
        $similarStocks = $stockSearchRepo->search_similar_stock($stock);
        $sameShootStock = null;
        $shootCode = $stock->getSameShootCode();

        $stockReleases = $stock->getStockReleases();
        $theReleaseRepo = $this->getDoctrine()->getManager()->getRepository(Release::class);

        $stocks = [];
        //$models = [];
        foreach ($stockReleases as $stockRel){

            $relFileId = $stockRel->getTheRelease()->getId();

            $rel = $theReleaseRepo->find($relFileId);

            $model = $rel->getModel();
            $theReleaseFiles = $theReleaseRepo->findBy(["model" => $model]);

            foreach ($theReleaseFiles as $relFile){
                $stockReleasesForAll = $relFile->getStockReleases();
                foreach ($stockReleasesForAll as $stockRelease){
                    $stockForModel = $stockRelease->getTheStock();
                    if (!in_array($stockForModel,$stocks)){
                        if ($stockForModel->getStatus() == Stock::PUBLISHED_STOCK && !$stockForModel->getHibernated() && $stockForModel->getId() != $stock->getId() && $stockForModel->getType() === $stock->getType()){
                            array_push($stocks, $stockForModel);
                        }
                    }
                    //$models[$stockForModel->getId()] = $model;
                }
            }
        }

        if ($shootCode){
            $sameShootStock = $stockRepository->findSimilarShootStock($stock);
        }

        return $this->render('stock/renew_exclusive_licence.html.twig', [
            'image' => $stock,
            'exclusivePricing' => $exclusive_pricing,
            'similarStocks' => $similarStocks,
            'sammeShootStock' => $sameShootStock,
            'sameModelStocks' => $stocks
        ]);



    }

    /**
     * @Route("/{id}/edit", name="stock_edit", methods={"GET","POST"})
     */
    public function edit(Request $request, Stock $stock): Response
    {
        $form = $this->createForm(StockType::class, $stock);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('stock_index', [
                'id' => $stock->getId(),
            ]);
        }

        return $this->render('stock/edit.html.twig', [
            'stock' => $stock,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/{id}", name="stock_delete", methods={"DELETE"})
     */
    public function delete(Request $request, Stock $stock): Response
    {
        if ($this->isCsrfTokenValid('delete'.$stock->getId(), $request->request->get('_token'))) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->remove($stock);
            $entityManager->flush();
        }

        return $this->redirectToRoute('stock_index');
    }

    /**
     * @Route("/stock/images", name="fetch_keywords", methods={"POST"})
     */
    public function fetchKeywords(Request $request, ImageHelper $imageHelper)
    {
        $jsonData = array();
        if ($request->isXmlHttpRequest()){
            $imageName = $request->request->get('imageName');
            $currentUser = $this->getUser();
            $storage_directory=$this->getParameter('uploads_directory');
            $file = $storage_directory.$currentUser->getFtpUser()->getUserId().DIRECTORY_SEPARATOR.$imageName;

            if (is_file($file)){
                $imageData = $imageHelper->fetchImageInfo($file);
                $iptc = $imageData['iptc'];
                $keywords = $iptc ? $iptc['Keywords'] : null;

                $jsonData['keywords'] = $keywords;
            }
        }
        return new JsonResponse($jsonData);
    }
    /**
     * @Route("/{id}/recalculate", name="recalculate_item", options={"expose"=true}, methods={"GET","POST"})
     * @param Stock $stock
     * @param CartItemRepository $cartItemRepository
     * @return Response
     */
    public function recalculateCartItem(Stock $stock,CartItemRepository $cartItemRepository)
    {
        $currentUser=$this->getUser();

        $cartItem = $cartItemRepository->findOneBy(['Stock' => $stock, "CreateBy"=>$currentUser]);
        if ($cartItem){
            $cart = $cartItem->getCart();
            $cart-> setTotal($cart->getTotal()-$cartItem->getAmount());

            $em = $this->getDoctrine()->getManager();
//            $em->remove($cartItem);
//            $em->persist($cart);
//            $em->flush();
        }
        return $this->redirectToRoute("image_details",["id"=>$stock->getId()]);
    }

    /**
     * @Route("/recalculate-offline/{id}", name="recalculate_item_offline", options={"expose"=true}, methods={"GET","POST"})
     * @param Stock $stock
     * @param CartItemRepository $cartItemRepository
     * @return Response
     */
    public function recalculateCartItemOffline(Stock $stock,CartItemRepository $cartItemRepository)
    {
        return $this->redirectToRoute("image_details",["id"=>$stock->getId()]);
    }



    /**
     * @Route("/videos/upload", name="videos_upload")
     * @param StockCategoryRepository $categoryRepository
     * @param ReleaseRepository $releaseRepository
     * @return Response
     */
    public function videos_upload(StockCategoryRepository $categoryRepository, ReleaseRepository $releaseRepository)
    {
        $categories=$categoryRepository->findAll();

        $finder = new Finder();
        $storage_dir=$this->getParameter('ftp_directory');
        $entityManager = $this->getDoctrine()->getManager();
        $currentUser=$this->getUser();
        $ftpPath = is_dir($storage_dir . '/' . $currentUser->getUsernameCanonical())
                    ? $storage_dir . '/' . $currentUser->getUsernameCanonical()
                    : $storage_dir . '/' . $currentUser->getUsername();
        $files = $finder->files()->in($ftpPath);
        $releases=$releaseRepository->findBy(['createBy'=>$currentUser]);
        $uploads=array();
        /** @var SplFileInfo $file */
        foreach ($files as $file){
            $upload= new Stock();
//            $upload->setFile($file);
            $upload->setContributor($currentUser);
            $upload->setFileName($file->getFilename());
            $uploads[]=$upload;
        }
        return $this->render('stock/videos_upload.html.twig', [
            'files' => $files,
            'uploads' => $uploads,
            'categories' => $categories,
            'releases' => $releases,

        ]);
    }

    /**
     * @Route("/videos/show", name="stock_videos")
     * @param Request $request
     * @param StockCategoryRepository $categoryRepository
     * @param ReleaseRepository $releaseRepository
     * @param StockRepository $stockRepository
     * @return Response
     */
    public function videos(Request $request,
                           StockCategoryRepository $categoryRepository,
                           ReleaseRepository $releaseRepository,
                           StockRepository $stockRepository,
                           StockTypeRepository $stockTypeRepository)
    {
        $categories = $categoryRepository->findAll();

        $finder = new Finder();
        $storage_dir=$this->getParameter('uploads_directory');

        $entityManager = $this->getDoctrine()->getManager();
        $currentUser=$this->getUser();
        $ftpPath = $storage_dir . $currentUser->getFtpUser()->getUserId();
        $files = $finder->files()->in($ftpPath);
        $filesToSubmit = [];
        $imageExtensions = ["mp4"];
        /**
         * @var File $file
         */
        foreach ($files as $file){
            if ($file->getExtension() === "gif" ){
                array_push($filesToSubmit, $file);
            }
        }
        $videoType = $stockTypeRepository->findOneBy(['title'=>'video']);
        $releases=$releaseRepository->findBy(['createBy'=>$currentUser]);
        $reviewedStock=$stockRepository->findBy(['contributor'=>$currentUser,'Published'=>1, 'type'=>$videoType]);

        $pendingStock=$stockRepository->findBy(['contributor'=>$currentUser,'Published'=>0, 'status'=>Stock::PENDING_STOCK,'type'=>$videoType]);
        $rejectedStock=$stockRepository->findBy(['contributor'=>$currentUser,'status'=>Stock::REJECTED_STOCK, 'type'=>$videoType]);
        $uploads=array();
        /** @var SplFileInfo $file */
        //dump($pendingStock);die;

        return $this->render('stock/videos.html.twig', [
            'files' => $filesToSubmit,
            'uploads' => $uploads,
            'reviewedStock' => $reviewedStock,
            'pendingStock' => $pendingStock,
            'categories' => $categories,
            'releases' => $releases,
            'rejectedStock' => $rejectedStock

        ]);
    }

    /**
     * @Route("/approve", name="approve_stock_items", methods={"GET","POST"})
     * @param Request $request
     * @param SMS $SMS
     * @param UserRepository $userRepository
     * @param StockCategoryRepository $stockCategoryRepository
     * @param ReleaseRepository $releaseRepository
     * @param StockRepository $stockRepository
     * @param StockTypeRepository $stockTypeRepository
     * @param StocksCatsRepository $stocksCatsRepository
     * @param ModelReleaseRepository $modelReleaseRepository
     * @param StockReleaseRepository $stockReleaseRepository
     * @param Mailer $mailer
     * @return Response
     * @throws \Exception
     */
    public function approveStock(Request $request,  SMS $SMS, UserRepository $userRepository,  StockCategoryRepository $stockCategoryRepository,
                                ReleaseRepository $releaseRepository,
                                StockRepository $stockRepository,
                                 StockTypeRepository $stockTypeRepository,
                                 StocksCatsRepository $stocksCatsRepository,
                                 ModelReleaseRepository $modelReleaseRepository,
                                 StockReleaseRepository $stockReleaseRepository,
                                 Mailer $mailer, PayoutDetailsRepository $payoutDetailsRepository): Response
    {

        $em = $this->getDoctrine()->getManager();
        if(!empty($request->request))

        {
            $to_approve = $request->request->get('to_approve');
            $to_approve = explode(",",$to_approve);

            $categories = null;
            $cats = $request->request->get('category');

            $sameShootCode = $request->request->get("same_shoot_code");
            $noOfPeople = $request->request->get("no_of_people");

            $category1 = null;
            if ($cats != "null"){
                $categories = explode(",",$cats);
                $category1 = $categories[0];
            }

            $models = [];
            foreach($to_approve as $id)
            {
                $stock = $stockRepository->find($id);

                if (!isset($_POST['multiple_approve'])){
                    $title = $request->request->get('title');
                    $price = $request->request->get('price');
                    $keywords = $request->request->get("keywords");
                    $noOfPeople = $request->request->get("no_of_people");
                    $video_type = $request->request->get("video_type");

                    $imageType = $request->request->get("image_type");
                    $imageSubType = $request->request->get("image_sub_type");

                    if ($video_type != "undefined" && !empty($video_type)){
                        $stock->setVideoType($video_type);
                    }
                    !empty($imageType) ? $stock->setImageType($imageType) : null;
                    !empty($imageSubType) ? $stock->setImageSubType($imageSubType) : null;
                    !empty($noOfPeople) && ($noOfPeople !== null) && ($noOfPeople !== "null") ? $stock->setPeopleNo($noOfPeople) : null;


                    $category1 != null ? $stock->setCategory($stockCategoryRepository->find($category1)) : null;
                    $category1 != null ? $stock->setCategory2($stockCategoryRepository->find($category1)) : null;

                    //set categories
                    if ($category1 != null){
                        //get and remove all stockCats
                        $stocksCats = $stocksCatsRepository->findBy(['stock'=>$stock]);
                        foreach ($stocksCats as $stocksCat){
                            $em->remove($stocksCat);
                        }

                        //create new stockCats
                        foreach ($categories as $category){
                            $stockCategory = $stockCategoryRepository->find($category);

                            $stocksCat = new StocksCats();

                            $stocksCat->setCategoryStockCat($stockCategory);
                            $stocksCat->setStock($stock);
                            $em->persist($stocksCat);

                        }
                    }

                    !empty($title) ? $stock->setTitle($title) : null;
                    !empty($price) ? $stock->setPrice(number_format($price/2,2)) : null;
                    !empty($price) ? $stock->setPriceLarge($price) : null;
                    !empty($price) ? $stock->setPriceSmall(number_format($price/3,2)) : null;
                    !empty($keywords) ? $stock->setKeywords($keywords) : null;

                    $stock->setHibernateStart(null);
                    $stock->setHibernateEnd(null);
                    $stock->setApproveAt(new \DateTime());

                }
                $stock->setLicenceType($request->request->get('licence_type'));
                $stock->setNofityModel(true);
                $stock->setApproveBy($this->getUser());
                if ($stock->getType()->getId() == 4){
                    $stock->setPublished(Stock::PUBLISHED_STOCK);
                }
                $stock->setStatus(Stock::APPROVED_STOCK);


                $releases = $request->request->get('releases');
                //Approve contributor if not approved
                /** @var User $contributor */
                $contributor = $stock->getContributor();
                if($contributor->getRegistrationComplete() != User::IDENTITY_VERIFIED ){

                    $contributor->setRegistrationComplete(true);
                    $contributor->setIdentityVerified(User::IDENTITY_VERIFIED);
                    $contributor->setApprover($this->getUser());
                    $contributor->setApprovedAt(new \DateTime());

                    $em->persist($contributor);
                }
                $em->persist($stock);
                $em->flush();


                $releases = $stock->getStockReleases()->getValues();
                if( count($releases) == 0){

                }else{

                    $rels = $stock->getStockReleases()->getValues();
                    /**@var StockRelease $rel **/
                    foreach ($rels as $rel){
                        $model = $rel->getTheRelease()->getModel();
                        $to = $model->getEmailAddress();
                        if (!in_array($model, $models, true)){
                            array_push($models,$model);
                        }
                    }

                }

            }
            //send to contributor
            $contributor = $stock->getContributor();

            if ($stock->getType()->getId() == 4){
                $url = $this->generateUrl("stock_images", array(),UrlGeneratorInterface::ABSOLUTE_URL);
            }else{
                $url = $this->generateUrl("stock_videos", array(),UrlGeneratorInterface::ABSOLUTE_URL);
            }

            try {
                $mailer->sendContributorStockApproved($contributor,$url,$contributor->getEmail());
            }catch (\Exception $exception){

            }

            $message = "Dear ".$contributor->getUsername().", Your content has been approved, thanks for using Sura Images.";
            $payoutDets = $payoutDetailsRepository->findOneBy(["user" => $contributor]);
            if(!empty($payoutDets)){
                try {
                    $SMS->send($payoutDets->getPhoneNumber(), $message);
                }catch (\Exception $exception){

                }
            }

            $url = $this->generateUrl("image_details", ['id'=>$stock->getId()], UrlGeneratorInterface::ABSOLUTE_URL);

            $contributor = $stock->getContributor();
            foreach ($models as $model)
            {
               // $model = $userRepository->findOneBy(['email'=>$mail]);
                if($model->getPhoneNumber()===null)
                {
                 $phone_number = $model->getUser()->getPhoneNumber();
                }else{
                    $phone_number = $model->getPhoneNumber();
                }
                $message = "Hi ".$model->getFirstName().", New content that you feature which was submitted by ".$contributor->getUsername()." (one of the Sura Images contributor) has been published on Sura Images. You can log in to Sura Images to view your content.";
                try {
                    $SMS->send($message, $phone_number);
                }catch (\Exception $exception){

                }
                try {
                    $mailer->sendModelStockApproved($url,$contributor,$model);
                }catch (\Exception $exception){

                }
            }
            return new JsonResponse(['success'=>1]);

        }

    }

    /**
     * @Route("/reject", name="reject_stock")
     */
    public function reject_stock(Request $request, StockRepository $stockRepository, Mailer $mailer, SMS $SMS, PayoutDetailsRepository $payoutDetailsRepository)
    {
        $toReject = $request->request->get("to_reject");
        $reason = $request->request->get("reason");
        $em = $this->getDoctrine()->getManager();
        $toReject = explode(",",$toReject);
        foreach ($toReject as $id){
            $stock = $stockRepository->find($id);

            $stock->setPublished(0);
            $stock->setStatus(Stock::REJECTED_STOCK);
            $stock->setRejectReason($reason);
            $em->persist($stock);

        }
        $em->flush();
        $contributor = $stockRepository->find($toReject[0])->getContributor();
        $url = $this->generateUrl("contributor_dashboard", array(),UrlGeneratorInterface::ABSOLUTE_URL);
        $mail = $contributor->getEmail();
        if (isset($reason) && !empty($reason)){
            //send mail
            $mailer->sendContributorStockRejected($url,$contributor,$reason, $mail);
            //send sms
            $message = "Dear ".$contributor->getUsername().", Sorry, the content that you uploaded to Sura Images has been rejected. To find out the reasons check your email.";
            $payoutDets = $payoutDetailsRepository->findOneBy(["user" => $contributor]);
            if(!empty($payoutDets)){
                $SMS->send($payoutDets->getPhoneNumber(), $message);
            }
        }

        return new JsonResponse(['status'=>1]);
    }

    //Video upload

    /**
     * @Route("/new/video", name="stock_new_video", methods={"GET","POST"})
     * @param Request $request
     * @param StockCategoryRepository $stockCategoryRepository
     * @param VideoHelper $videoHelper
     * @param ReleaseRepository $releaseRepository
     * @param StockTypeRepository $stockTypeRepository
     * @return Response
     * @throws \Exception
     */
    public function new_video(Request $request,
                              StockRepository $stockRepository,
                              StockCategoryRepository $stockCategoryRepository,
                                VideoHelper $videoHelper,
                                ReleaseRepository $releaseRepository,
                                StockTypeRepository $stockTypeRepository,
                                MessageBusInterface $bus): Response
    {
        $storage_dir=$this->getParameter('public_directory');
        $stock_directory=$this->getParameter('stock_directory');
        $ftp_directory=$this->getParameter('ftp_directory');
        $userDir = $this->getParameter('uploads_directory').$this->getUser()->getFtpUser()->getUserId();
        $fileSystem = new Filesystem();
        $finder = new Finder();

        $em = $this->getDoctrine()->getManager();
        if(!empty($request->request))

        {
            $selected_videos = $request->request->get('selected_videos');
            $selected = explode("," , $selected_videos);
            $video = true;

            $categories = explode("," , $request->request->get('category'));

            if(!empty($categories[0])){
                $category1 = $categories[0];
            }else{
                $category1 = 1;
            }
            $sameShootCode = $request->request->get("same_shoot_code");
            $noOfPeople = $request->request->get("no_of_people");

            if(!empty($categories[1])){

                $category2 = 1;
            }
            foreach($selected as $key=>$value)
            {
                if($value=="" || $value== null){
                    unset($selected[$key]);
                    continue;
                }
                //$file=$this->getParameter('ftp_directory').DIRECTORY_SEPARATOR.$value;
                $selected_file = $value;
                $file = $userDir.DIRECTORY_SEPARATOR.$selected_file;




                if($fileSystem->exists($file)) {
                    $fileObj= new File($file);
                    $ext=$fileObj->guessExtension();
                    $preview_name = uniqid('preview_').'.'.$ext;
                    $new_gif_file = null;

                    $name= uniqid('vid_').'.mp4';
                    $gif_name = str_replace("mp4",$ext,$name);
                    $video_name= str_replace($ext,"mp4",$selected_file);
                    $new_gif_file=$stock_directory.DIRECTORY_SEPARATOR.$gif_name;

                    $new_file=$stock_directory.DIRECTORY_SEPARATOR.$name;

                    $stock = new Stock();
                    $type = null;

                    //vid
                    $videoFile = new File($userDir.DIRECTORY_SEPARATOR.$video_name);
                    //Fetch information
                    $metadata = $videoHelper->fetchVideoMetaData($videoFile);

                    $fileSystem->copy($videoFile,$new_file);
                    $fileSystem->copy($file,$new_gif_file);
                    $fileSystem->remove($videoFile);
                    $fileSystem->remove($file);
                    $type = $stockTypeRepository->findOneBy(['title'=>'video']);
                    $stock->setThumbName($gif_name);

                    $stock->setLargeImagePath($new_file);
                    $stock->setFileName($name);
                    $stock->setCreateAt(new \DateTime());
                    $stock->setCategory($stockCategoryRepository->find($category1));
                    $stock->setCategory2($stockCategoryRepository->find($category1));
                    $stock->setContributor($this->getUser());
                    //$stock->setType($stockTypeRepository->find($request->request->get('image_type')));
                    $stock->setType($type);
                    $stock->setTitle($request->request->get('title'));
                    $stock->setSameShootCode($request->request->get('same_shoot_code'));
                    $stock->setDescription("Russian");
                    $stock->setApproveBy(null);
                    $stock->setPrice(number_format($request->request->get('price')/2,2));
                    $stock->setPeopleNo($noOfPeople);
                    $stock->setShootCode($sameShootCode);
                    $stock->setFileSize(15);
                    $stock->setStatus(0);
                    $stock->setNofityModel(true);
                    $stock->setHibernateStart(null);
                    $stock->setHibernateEnd(null);
                    $stock->setKeywords($request->request->get("keywords"));
                    $stock->setApproveAt(null);
                    $stock->setPriceLarge($request->request->get('price'));
                    $stock->setPriceSmall(number_format($request->request->get('price')/3,2));
                    $start = $stockRepository->findOneBy(['Published'=>Stock::PUBLISHED_STOCK]);
                    $stock->setSuraID((int)$start->getSuraID() + rand(12345,999999) + $start->getId()+1);
//                    $stock->setVideoResolution($request->request->get('resolution'));
                    $stock->setVideoType($request->request->get('video_type'));
                    $em->persist($stock);
                    $em->flush();


                    //Fetch information
                    $fps = $metadata['fps'];
                    $duration = $metadata['duration'];
                    $video_res = $metadata['resolution'];

                    switch ($video_res){
                        case '4K UHD':
                            $medium_res_suffix = "1080p";
                            $low_res_suffix = "720p";
                            break;
                        case '1080p':
                            $medium_res_suffix = "720p";
                            $low_res_suffix = "480p";
                            break;
                        case '720p':
                            $medium_res_suffix = "480p";
                            $low_res_suffix = "360p";
                            break;
                        default:
                            $medium_res_suffix = "_720p";
                            $low_res_suffix = "_480p";
                    }



                    $stockName = "suraimages_{__}-".$stock->getSuraID()."-".$stock->getSlug().".mp4";
                    $preview_name = str_replace("{__}","preview",$stockName);
                    $large_name = str_replace("{__}","$video_res",$stockName);
                    $medium_name = str_replace("{__}","$medium_res_suffix",$stockName);
                    $small_name = str_replace("{__}","$low_res_suffix",$stockName);

                    $large_path = $this->getParameter("stock_directory").DIRECTORY_SEPARATOR.$large_name;
                    $medium_path = $this->getParameter("stock_directory").DIRECTORY_SEPARATOR.$medium_name;
                    $small_path = $this->getParameter("stock_directory").DIRECTORY_SEPARATOR.$small_name;

                    if (is_file($stock->getLargeImagePath())){
                        try {
                            $large_path_gif = str_replace(".mp4",".gif",$large_path);
                            $thumb_name = str_replace(".mp4",".gif",$large_name);
                            $fileSystem->rename($stock->getLargeImagePath(), $large_path);
                            $fileSystem->rename($new_gif_file, $large_path_gif);
                            $stock->setLargeImagePath($large_path);
                            $stock->setLargeImageName($large_name);
                            $stock->setFileName($large_name);
                            $stock->setThumbName($thumb_name);
                            $stock->setFilePath($medium_path);
                            $stock->setPreviewName($preview_name);
                            $stock->setSmallImagePath($small_path);

                            $thumb_file_path = $large_path_gif;
                            if (is_file($thumb_file_path)){
                                $thumbSizes = getimagesize($thumb_file_path);
                                if ($thumbSizes != false){
                                    $thumb_width = $thumbSizes[0];
                                    $thumb_height = $thumbSizes[1];

                                    if ($thumb_width != 400){
                                        $regenerated_thumbnail = $videoHelper->regenerate_video_thumbnail($stock);
                                        if ($regenerated_thumbnail){
                                            $thumb_width = $regenerated_thumbnail['width'];
                                            $thumb_height = $regenerated_thumbnail['height'];
                                        }
                                    }

                                    $stock->setThumbHeight($thumb_height);
                                    $stock->setThumbWidth($thumb_width);
                                }
                            }

                            $stock->setVideoResolution($video_res);
                            $stock->setFileWidth($metadata['width']);
                            $stock->setFileHeight($metadata['height']);
                            $stock->setOrientation($metadata['orientation']);
                            $stock->setVideoDuration($duration);
                            $stock->setVideoFps($fps);

                            $em->persist($stock);
                        }catch (\Exception $exception){

                        }

                    }

                    //set categories
                    foreach ($categories as $category){
                        $stockCat = new StocksCats();
                        $stockCat->setCategoryStockCat($stockCategoryRepository->find($category));
                        $stockCat->setStock($stock);
                        $em->persist($stockCat);
                    }

                    $releases = $request->request->get('releases');

                    if( $releases === "null"){

                    }else{
                        $releases=explode(',',$request->request->get('releases'));
                        $releasePercentage = $request->request->get('release_percentage');
                        foreach ($releases as $release){
                            $releaseEntity=$releaseRepository->find($release);
                            if($releaseEntity){
                                $stockRelease= new StockRelease();
                                $stockRelease->setTheRelease($releaseEntity);
                                $stockRelease->setTheStock($stock);
                                $stockRelease->setPercentage($releasePercentage);
                                $em->persist($stockRelease);
                            }

                        }
                    }
                    $em->flush();
                }

            }
            return new JsonResponse(['success'=>1]);

        }

    }

    /**
     * @Route("/file/pending/details", name="pending_file_details", options={"expose"=true})
     * @param Request $request
     * @return JsonResponse
     */
    public function pending_approval_stock_details(Request $request, StockRepository $stockRepository, VideoHelper $videoHelper)
    {
        $em = $this->getDoctrine()->getManager();
        $details = [];
        $stock_directory=$this->getParameter('stock_directory');
        if ($request->isXmlHttpRequest()){
            if (isset($_POST['file_name']) && !empty($_POST['file_name'])){
                $file_name = $_POST['file_name'];

                $file_path = $stock_directory.DIRECTORY_SEPARATOR.$file_name;
//                if (is_file($file_path)){
                    //qr
                    $stock = $stockRepository->findOneBy(['FileName' => $file_name]);
//                }
            }else if (isset($_POST['stock_id'])){
                $stock=$stockRepository->find($_POST['stock_id']);
            }
            if ($stock){
                $details['id'] = $stock->getId();
                $details['sura_id'] = $stock->getSuraID() ? $stock->getSuraID() : $stock->getId();
                $details['title'] = $stock->getTitle();
                $details['keywords'] = $stock->getKeywords();
                $details['people'] = $stock->getPeopleNo();
                $details['type'] = ucfirst($stock->getType()->getTitle());
                $details['shootCode'] = $stock->getSameShootCode();

                if ($stock->getType()->getTitle() == "video"){
                    $details['videoType'] = $stock->getVideoType();
                    $res = $stock->getVideoResolution();
                    $duration = $stock->getVideoDuration();
                    $fps = $stock->getVideoFps();

                    if (!$res || !$duration || !$fps){
                        $metadata = $videoHelper->fetchVideoMetaData($stock->getFilePath());
                        if (!$res){
                            $resolution = $metadata['resolution'];
                            $stock->setVideoResolution($resolution);
                            $em->persist($stock);
                        }
                        if (!$duration){
                            $duration = $metadata['duration'];
                            $stock->setVideoDuration($duration);
                            $em->persist($stock);
                        }
                        if (!$fps){
                            $fps = $metadata['fps'];
                            $stock->setVideoFps($fps);
                            $em->persist($stock);
                        }
                        $em->flush();
                    }

                    $details['resolution'] = $stock->getVideoResolution() ?? "Not set";
                    $details['fps'] = $stock->getVideoFps() ?? "Not set";
                    $details['duration'] = $stock->getVideoDuration() ?? "Not set";
                }else{
                    $details['imageType'] = $stock->getImageType();
                    $details['imageSubType'] = ucfirst($stock->getImageSubType());
                }
                $details['licenceType'] = $stock->getLicenceType() != null ? $stock->getLicenceType() : "Not set until approval";

                $releases = $stock->getStockReleases();
//                $categories = $stock->getCategory()->getName();
                $stockCats = $stock->getStocksCats();


                $categories = [];
                $categoryIds = [];
                if($stockCats!=null) {
                    foreach ($stockCats as $stockCat) {
                        if ($stockCat->getCategoryStockCat()){
                            array_push($categories, $stockCat->getCategoryStockCat()->getName());
                            array_push($categoryIds, $stockCat->getCategoryStockCat()->getId());
                        }
                    }
                }


                $newPercentage=null;
                $stock_rel = "";
                $stock_rel_ids = [];
                if(count($releases) > 0) {
                    $newPercentage = $releases[0]->getPercentage();
                    foreach ($releases as $key => $val) {
                        $title = $val->getTheRelease()->getTitle();
                        $percentage = $val->getTheRelease()->getPayoutPercent();

                        $model = $val->getTheRelease()->getModel() != null ? $val->getTheRelease()->getModel()->getFirstName() : "";
                        $stock_rel = $stock_rel . $title . "[" . $model . "]";
                        array_push($stock_rel_ids,$val->getTheRelease()->getId());
                    }
                }
                $details['releases'] = $stock_rel;
                $details['categories'] = $categories;
                $details['categoryIds'] = $categoryIds;
                $details['stockRelIds'] = $stock_rel_ids;
                $details['price'] = $stock->getPriceLarge();
                $details['reject_reason'] = $stock->getRejectReason();
                $details['newPercentage'] = $newPercentage != null ? $newPercentage : 0;
                $details['licence'] = $stock->getLicenceType();

                $width = $stock->getFileWidth();
                $height = $stock->getFileHeight();

                $orientation = $stock->getOrientation();
                $details['orientation'] = $orientation!=null ? $orientation : ($width > $height ? "Landscape" : "Portrait");
            }
        }
        return new JsonResponse(['details' =>$details]);
    }

    /**
     * @Route("/edit", name="stock_edit")
     * @param Request $request
     * @param StockRepository $stockRepository
     * @param Helper $helper
     * @param StocksCatsRepository $stocksCatsRepository
     * @param StockCategoryRepository $stockCategoryRepository
     * @param StockReleaseRepository $stockReleaseRepository
     * @param ReleaseRepository $releaseRepository
     * @return JsonResponse
     */
    public function editStock(Request $request,
                              StockRepository $stockRepository,
                              Helper $helper,
                              StocksCatsRepository $stocksCatsRepository,
                              StockCategoryRepository $stockCategoryRepository,
                              StockReleaseRepository $stockReleaseRepository,
                              ReleaseRepository $releaseRepository)
    {
        $em = $this->getDoctrine()->getManager();
        $category = $_POST["category"];
        $releases = $_POST["releases"];


        $id = $_POST["stock_id"];
        $stock = $stockRepository->find($id);
        $stockType = $stock->getType()->getTitle();

        $title = $_POST["title"];
        $keywords = $_POST["keywords"];
        $price = $_POST["price"];
        $same_shoot_code = $_POST["same_shoot_code"];
        $no_of_people = $_POST["no_of_people"];

        //set categories
        if ($category != "null"){
            //get and remove all stockCats
            $stocksCats = $stocksCatsRepository->findBy(['stock'=>$stock]);
            foreach ($stocksCats as $stocksCat){
                $em->remove($stocksCat);
            }

            $categories = explode(",",$category);
            //create new stockCats
            foreach ($categories as $cat){
                $stockCategory = $stockCategoryRepository->find($cat);

                $stocksCat = new StocksCats();
                $stocksCat->setCategoryStockCat($stockCategory);
                $stocksCat->setStock($stock);
                $em->persist($stocksCat);
            }
        }

        if ($stockType == "photo"){
            $image_type = $_POST["image_type"];
            $image_sub_type = $_POST["image_sub_type"];
//            $orientation = $_POST["orientation"];
            if ($image_type != "null" && $image_type != "")
                $stock->setImageType($image_type);
            if ($image_sub_type != "null"  && $image_sub_type != "")
                $stock->setImageSubType($image_sub_type);
            /*if ($orientation != "null" && $orientation != "")
                $stock->setOrientation($orientation);*/
        }else if ($stockType == "video"){
            $video_type = $_POST["video_type"];
            if ($video_type != "null" && $video_type != "")
                $stock->setVideoType($video_type);
        }

        $pricing = $helper->getPricingByType($stockType);

        if ($title != "null" && $title != "")
            $stock->setTitle($title);
        if ($keywords != "null" && $keywords != "")
            $keywordsArray = explode(",",$keywords);
            if (count($keywordsArray) >= 7 && count($keywordsArray) <= 50){
//                $stock->setKeywords("");
                $stock->setKeywords($keywords);
            }
        if ($price != "null" && $price != "")
            if ((int)$price >= (int)$pricing->getMinimum() && (int)$price <= (int)$pricing->getMaximum()){
                $stock->setPriceLarge($price);
                $stock->setPrice(number_format($price/2,2));
                $stock->setPriceSmall(number_format($price/3,2));
            }
        if ($same_shoot_code != "null" && $same_shoot_code != "")
            $stock->setSameShootCode($same_shoot_code);
        if ($no_of_people != "null" && $no_of_people != "")
            $stock->setPeopleNo($no_of_people);

        //set releases
        if( $releases === "null" || $releases === ""){

        }else{
            $stockReleases = $stockReleaseRepository->findBy(['TheStock'=>$stock ]);
            foreach ($stockReleases as $stockRelease){
                $em->remove($stockRelease);
            }

            $relPercentage = $request->request->get('release_percentage');
            $releases=explode(',',$request->request->get('releases'));
            foreach ($releases as $release){
                $releaseEntity=$releaseRepository->find($release);
                $stockRelease= new StockRelease();
                $stockRelease->setTheRelease($releaseEntity);
                $stockRelease->setTheStock($stock);
                $stockRelease->setPercentage($relPercentage);
                $em->persist($stockRelease);
            }
        }


        $em->persist($stock);
        $em->flush();

        return new JsonResponse([
            "message" => 'stock has been updated successfully'
        ]);

    }

    /**
     * @Route("/edit/admin", name="stock_edit_admin")
     * @param Request $request
     * @param StockRepository $stockRepository
     * @param Helper $helper
     * @param StocksCatsRepository $stocksCatsRepository
     * @param StockCategoryRepository $stockCategoryRepository
     * @param StockReleaseRepository $stockReleaseRepository
     * @param ReleaseRepository $releaseRepository
     * @return JsonResponse
     */
    public function editStockAdmin(Request $request,
                              StockRepository $stockRepository,
                              Helper $helper,
                              StocksCatsRepository $stocksCatsRepository,
                              StockCategoryRepository $stockCategoryRepository,
                              StockReleaseRepository $stockReleaseRepository,
                              ReleaseRepository $releaseRepository)
    {
        $em = $this->getDoctrine()->getManager();
        $category = $_POST["category"];


        $id = $_POST["stock_id"];
        $stock = $stockRepository->find($id);
        $stockType = $stock->getType()->getTitle();

        $title = $_POST["title"];
        $keywords = $_POST["keywords"];
        $price = $_POST["price"];
        $same_shoot_code = $_POST["same_shoot_code"];
        $no_of_people = $_POST["no_of_people"];
        $licence_type = $_POST["licence_type"];

        //set categories
        if ($category != "null"){
            //get and remove all stockCats
            $stocksCats = $stocksCatsRepository->findBy(['stock'=>$stock]);
            foreach ($stocksCats as $stocksCat){
                $em->remove($stocksCat);
            }

            $categories = explode(",",$category);
            //create new stockCats
            foreach ($categories as $cat){
                $stockCategory = $stockCategoryRepository->find($cat);

                $stocksCat = new StocksCats();
                $stocksCat->setCategoryStockCat($stockCategory);
                $stocksCat->setStock($stock);
                $em->persist($stocksCat);
            }
        }

        if ($stockType == "photo"){
            $image_type = $_POST["image_type"];
            $image_sub_type = $_POST["image_sub_type"];
            $orientation = $_POST["orientation"];
            if ($image_type != "null")
                $stock->setImageType($image_type);
            if ($image_sub_type != "null")
                $stock->setImageSubType($image_sub_type);
            if ($orientation != "null")
                $stock->setOrientation($orientation);
        }else if ($stockType == "video"){
            if (isset($_POST['resolution'])){
                $resolution = $_POST['resolution'];
                $videoType = $_POST['video_type'];
                if ($resolution != "null" && $resolution != "")
                    $stock->setVideoResolution($resolution);
                if ($videoType != "null" && $videoType != "")
                    $stock->setVideoType($videoType);
            }
        }

        $pricing = $helper->getPricingByType($stockType);

        if ($title != "null")
            $stock->setTitle($title);
        if ($keywords != "null")
            $keywordsArray = explode(",",$keywords);
        if (count($keywordsArray) >= 7 && count($keywordsArray) <= 50){
//                $stock->setKeywords("");
            $stock->setKeywords($keywords);
        }
        if ($price != "null")
            if ((int)$price >= (int)$pricing->getMinimum() && (int)$price <= (int)$pricing->getMaximum()){
                $stock->setPriceLarge($price);
                $stock->setPrice(number_format($price/2,2));
                $stock->setPriceSmall(number_format($price/3,2));
            }
        if ($same_shoot_code != "null")
            $stock->setSameShootCode($same_shoot_code);
        if ($no_of_people != "null")
            $stock->setPeopleNo($no_of_people);

        if ($licence_type != "null" && $licence_type != ""){
            $stock->setLicenceType($licence_type);
        }


        $em->persist($stock);
        $em->flush();

        return new JsonResponse([
            "message" => 'stock has been updated successfully'
        ]);

    }
}

Youez - 2016 - github.com/yon3zu
LinuXploit