<?php
namespace OfficeBrain\Bundle\FlyerBundle\Manager\Extended;

use OfficeBrain\Bundle\FlyerBundle\Manager\AbstractManager\FlyerAbstract as FlyerAbstract;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Symfony\Component\Filesystem\Filesystem;
use OfficeBrain\Bundle\FlyerBundle\Entity\Flyer;


/**
 *
 * @author OfficeBrain 4571 <info@officebrain.com>
 *
 * Description : Extended class
 *
 */
class FlyerExtended extends FlyerAbstract
{
    /**
     *
     * @author Employee Id: 4571
     *
     * Description : Set variables
     *
     * @param 1:  $entityManager
     * @param 2:  $request
     * @param 3:  $translator
     * @param 4:  $knpPaginator
     * @param 5:  $country
     * @param 5:  $language
     *
     * @return null
     *
     * @throws null
     *
     **/
    public function __construct($entityManager, $request, $translator, $knpPaginator, $country, $language)
    {
        parent::__construct($entityManager, $request, $translator, $knpPaginator, $country, $language);
    }

    /**
     *
     * @author Employee Id: 4571
     *
     * Description : Unset variables
     *
     * @param : null
     *
     * @return null
     *
     * @throws null
     *
     **/
    public function __destruct()
    {
        parent::__destruct();
    }


    /**
     *
     * @author Employee Id: 4571
     * Description : fetch flyer
     *
     * @param : null
     *
     * @return null
     *
     * @throws null
     *
     **/
    public function fetchFlyer($flyerUniqueId)
    {
    	//return $this->flyerRepository->fetchFlyerHTML($flyerUniqueId);
    	return $this->flyerRepository->findByUniqueID($flyerUniqueId);

    }
    
    
    /**
     *
     * @author Employee Id: 5430
     * Description : get flyers by slug
     *
     * @param : null
     *
     * @return null
     *
     * @throws null
     *
     **/
    public function getFlyerListBySlug($slug,$page,$recordsPerPage,$keywords)
    {
        $countryId=$this->getCountryIdByCode($this->countryCode);
        return $this->flyerRepository->getFlyerBySlug($slug,$page,$recordsPerPage,$keywords,$countryId);
    }

    /**
     *
     * @author Employee Id: 5430
     * Description : get flyers parentcategory
     *
     * @param : null
     *
     * @return null
     *
     * @throws null
     *
     **/
    public function getParentCategories()
    {
    	return $this->flyerRepository->getParentCategories();
    }
    
    /**
     *
     * @author Employee Id: 5428
     * Description : get flyers subcategory
     *
     * @param : null
     *
     * @return null
     *
     * @throws null
     *
     **/
    public function getSubCategories($subids)
    {
    	return $this->flyerRepository->findsubCategories($subids);
    }
    
    /**
     *
     * @author Employee Id: 4571
     *
     * Description : copy flyer image
     *
     * @param : null
     *
     * @return image name
     *
     * @throws null
     *
     **/
    function copyFlyerImage($imageURL, $filePath, $convert, $imageName = '')
     {
    	//$session = $request->getSession();
    	if($imageName == '') {
    		$imageName = explode('/', $imageURL);
    		$imageName = $imageName[count($imageName) -1];
    	}
    	$imageName = str_replace(' ','_', $imageName);
    	$fs = new Filesystem();

    	$fs->mkdir($filePath, 0755);

    	$sourceAbsolutePath =  $imageURL;

    	$destinationAbsolutePath = $filePath;

    	$ch = curl_init($sourceAbsolutePath);
		$fp = fopen($destinationAbsolutePath.$imageName, 'wb');
		curl_setopt($ch, CURLOPT_FILE, $fp);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_exec($ch);
		curl_close($ch);
		fclose($fp);

    	$imageName =$this->convertToTransparent($sourceAbsolutePath, $destinationAbsolutePath, $convert, $imageName);

    	return $imageName;

    }

    /**
     *
     * @author Employee Id: 4571
     * Description : convert to transparent
     *
     * @param : null
     *
     * @return image name
     *
     * @throws null
     *
     **/
    function convertToTransparent($sourceAbsolutePath, $destinationAbsolutePath, $convert, $imageName = '')
    {
    	if($imageName == '') {
    		$pngImageName = $imageName = time();
    	} else {
    		$pngImageName = $imageName;
    	}
    	$pngImageName = substr($pngImageName, 0 , (strrpos($pngImageName, ".")));


    	exec($convert .' '. $destinationAbsolutePath.$imageName .' -fuzz 20% -fill transparent -draw "color 5,5 floodfill" -quality 100 ' . $destinationAbsolutePath . $pngImageName . '.png');
    			unlink($destinationAbsolutePath.$imageName);
    			return $pngImageName . '.png';
    }

    /**
     *
     * @author Employee Id: 4571
     * Description : fetch flyer
     *
     * @param : null
     *
     * @return null
     *
     * @throws null
     *
     **/
     public function convertImageToTransparent($convert, $productDetailArray, $flyerImagesPath, $apiImagePath, $flyerImageURL, $productId)
     {
        $imageName = '';

        $destinationAbsolutePath = $flyerImagesPath . $this->session->getId() . '/';

        if($imageName == '') {
        	$imageName = explode('/', $apiImagePath . $productDetailArray['product_detail']['data'][$productId]['basic_information']['default_image_url']);

            $imageName = $imageName[count($imageName) -1];
        }

        if($imageName == ''){
        	return 'IS_NOT_VALID_IMG';
        }

        $apiImagePath = $productDetailArray['product_images']; //str_replace('/data/', 'http://images.officebeacon.com/', $productDetailArray['product_detail']['image_path']);

        $modifiedImageName = $this->copyFlyerImage($apiImagePath , $destinationAbsolutePath, $convert, $imageName);

        $productDetailArray['product_detail']['image_path'] = $flyerImageURL . $this->session->getId() . '/' . $modifiedImageName;

        if(isset($productDetailArray['product_images']) && is_array($productDetailArray['product_images']) && isset($productDetailArray['product_images']['data'])){
            foreach($productDetailArray['product_images']['data'] as $key=>$productImages) {

                $imageName = explode('/', $productImages['image_path']);
                if(count($imageName)>1) {
                    $imageName = $imageName[1];
                } else {
                    $imageName = $imageName[0];
                }

                //Convert the product image
                $apiImagePath1 = str_replace('/data/', 'http://images.officebeacon.com/', $productDetailArray['product_images']['data']['0']['image_path']);
                $modifiedImageName = $this->copyFlyerImage($apiImagePath1, $destinationAbsolutePath, $convert, $imageName);
                $productDetailArray['product_images']['image_path'] = $flyerImageURL . $this->session->getId() . '/' . $modifiedImageName;

                //echo $productDetailArray['product_images'][$key]['image_path'] .'<br>';

            }
        }
        return $productDetailArray;
    }


    /**
     *
     * @author Employee Id: 4571
     *
     * Description : save flyer html
     *
     * @param : null
     *
     * @return null
     *
     * @throws null
     *
     **/
    public function findUnique($flyerUniqueId)
    {

    	return  $this->flyerRepository->findByUniqueID($flyerUniqueId);
    }

    /**
     *
     * @author Employee Id: 4571
     *
     * Description : reset flyer html
     *
     * @param : null
     *
     * @return null
     *
     * @throws null
     *
     **/
    public function resetFlyer()
    {
        $customUniqueId = $this->session->get('flyerUniqueId');

        if( ! $customUniqueId ) {
            return true;
        }

        $flyerExists = $this->flyerRepository->findOneBy(array('uniqueId' => $customUniqueId));

        $this->entityManager->remove($flyerExists);
        $this->entityManager->flush();

        return true;
    }

    /**
     *
     * @author Employee Id: 4571
     *
     * Description : Fetch flyer
     *
     * @param : null
     *
     * @return null
     *
     * @throws null
     *
     **/
    public function getFlyerList($page='',$recordPerPage='',$subid)
    {
    	$flyerArray = array();
    	$flyerResults = array();
    	$adminUser = false;
    	if ($this->countryCode)
    		$this->countryId = $this->getCountryIdByCode($this->countryCode);
    	if ($this->languageCode)
    		$this->languageId = $this->getLanguageIdByCode($this->languageCode);
    	$isAdmin = $this->flyerRepository->findAdminUser();
    	if($isAdmin!="" && sizeof($isAdmin)>0)
    		$adminUser = true;
    	$flyerArray = $this->flyerRepository->findActiveFlyerList($this->countryId, $this->languageId, '', $adminUser,$page,$recordPerPage,$subid);
    	$this->responseArray['culture'] = $this->culture;
	    $this->responseArray['languageCode'] = $this->languageCode;
	    $this->responseArray['countryCode'] = $this->countryCode;
	    $this->responseArray['recordSet']= $flyerArray;
	    return $this->responseArray;

    	}

    /**
     *
     * @author Employee Id: 4571
     *
     * Description : Fetch flyer
     *
     * @param : null
     *
     * @return null
     *
     * @throws null
     *
     **/
    public function getFrontFlyerList()
    {
    	$flyerArray = array();
    	$flyerResults = array();

    	$param = $this->request->get('_route_params');
    	$page = $param['page'];

    	$supplierId = $this->request->get('suppId');

    	if($supplierId == ""){
    		$supplierId = 0 ;
    	}
    	//echo " Supp id : ".$supplierId; die;
    	if ($this->countryCode) {
    		$this->countryId = $this->getCountryIdByCode($this->countryCode);
    	}

    	if ($this->languageCode) {
    		$this->languageId = $this->getLanguageIdByCode($this->languageCode);
    	}

    	$flyerArray = $this->flyerRepository->findFrontFlyerList($this->countryId, $this->languageId, $supplierId);

    	if (!empty($flyerArray)) {

	    	$i = 0;
	    	foreach ($flyerArray as $recordKey => $recordValue) {
	    		$flyerResults[$i]['id'] = $recordValue['id'];
	    	    $flyerResults[$i]['culture'] = $this->culture; // language Id
	    		$flyerResults[$i]['title'] = $recordValue['title'];
	    		$flyerResults[$i]['validUntilDate'] = $recordValue['validUntilDate'];
	    		$flyerResults[$i]['uniqueId'] = $recordValue['uniqueId'];
	    		$flyerResults[$i]['publishedAt'] = $recordValue['publishedAt'];
	    		$flyerResults[$i]['countryId'] = $recordValue['countryId'];
	    		$flyerResults[$i]['publishedFlag'] = $recordValue['publishedFlag'];
	    		$flyerResults[$i]['flyerUploadedPath'] = $recordValue['flyerUploadedPath'];
	    		$flyerResults[$i]['flyerThumb'] = $recordValue['flyerThumb'];

	    		$i++;
	    	}
    	}

	    $records_per_page = $param['records_per_page'];

	    if (count($flyerResults) > 0) {
	    		$this->responseArray['banner'] = $flyerResults;
	    		$paginator  =  $this->knpPaginator; //$this->container->get('knp_paginator');
	    		$this->responseArray['pagination'] = $paginator->paginate($flyerResults, $page, $records_per_page, array(), count($flyerResults));
	    }

	    $this->responseArray['page'] = $page;
	    $this->responseArray['culture'] = $this->culture;
	    $this->responseArray['languageCode'] = $this->languageCode;
	    $this->responseArray['countryCode'] = $this->countryCode;
	    $this->responseArray['recordSet']= $flyerResults;

	    return $this->responseArray;

    	}


    	/**
    	 *
    	 * @author Employee Id: 4571
    	 * Description : find culture Id
    	 *
    	 * @param : null
    	 *
    	 * @return null
    	 *
    	 * @throws null
    	 *
    	 **/
    	public function findCultureId()
    	{
    		$locale = $this->request->get('_locale'); // en_us

    		if($locale!=""){
    			@list($localeCulture, $localeCountry) = explode("_", $locale);
    		}

    		$productCulture = $localeCulture."_".$localeCountry;

    		return $this->getLanguageIdByCode($localeCulture); // new
    	}

    	/**
    	 *
    	 * @author Employee Id: 4571
    	 * Description : used to generate flyer
    	 *
    	 * @param : null
    	 *
    	 * @return null
    	 *
    	 * @throws null
    	 *
    	 **/
    	public function generateFlyer($productAdminManager, $convert, $flyerImagesPath, $apiImagePath, $flyerImageURL)
    	{

    		$productDetailArray = null;

    		$productId = $this->request->get('product_id');
    		$productSlug = $this->request->get('product_slug');
    		$productObCustomerId=$this->request->get('ob_customer_id');
    		
    		$locale = $this->request->get('_locale'); // en_us

    		if($locale!=""){
    			@list($localeCulture,$localeCountry) = explode("_", $locale);
    		}

    		$productCulture = $localeCulture."_".$localeCountry;

    		$cultureId =  $this->getLanguageIdByCode($localeCulture); // new

    		$flyerUniqueId = $this->session->get('flyerUniqueId', '');
    		$flyerProductSlug = $this->session->get('flyerProductSlug', '');
    		$flyerProductId = $this->session->get('flyerProductId', '');

    		if($flyerProductId != $productId) {
    			$this->session->set('flyerProductSlug', $productSlug);
    			$this->session->set('flyerProductId', $productId);
    			$flyerUniqueId = $this->session->set('flyerUniqueId', '');
    		}

    		/* fetch Product Detail By Slug */
    		//$productDetailArray = $this->fetchProductDetail($productId, $culture, 'id'); // old commented
    		$productDetailArray = $productAdminManager->view($productId, $productCulture); // new service
    		
    		$data = array();
    		$priceRule = $add_array = array();

    		//$productDetailArray["prod_detail_array"] = $productDetailArray;
    		$productDetailArray['product_detail'] = $productDetailArray;

    		if((array_key_exists("title",$productDetailArray['data'][$productId]['basic_information']))){
    			$title =  $productDetailArray['data'][$productId]['basic_information']['title'];
    		}else{
    			$title = '';
    		}

    		if((array_key_exists("description",$productDetailArray['data'][$productId]['basic_information']))){
    			 $description =  $productDetailArray['data'][$productId]['basic_information']['description'];
    		}else{
    			$description = '';
    		}

    		if((array_key_exists("default_image_url",$productDetailArray['data'][$productId]['basic_information']))){
    			$defaultImageUrl =  $productDetailArray['data'][$productId]['basic_information']['default_image_url'];
    		}else{
    			$defaultImageUrl =  '';
    		}


    		$productDetailArray['product_detail']['basic_information']['title']       		= $title;
    		$productDetailArray['product_detail']['basic_information']['description']       = $description;
    		$productDetailArray['product_detail']['basic_information']['default_image_url'] = $defaultImageUrl;
    		$productDetailArray['product_detail']['attributes'] 							= $productDetailArray['data'][$productId]['attributes'];

    		if($productDetailArray['data'][$productId]['price_type'] == "regular" ){

    			if((array_key_exists("decorative",$productDetailArray['data'][$productId]['pricing']))){
    				$usedKey = 'decorative';
    			}else{
    				$usedKey = 'blank';
    			}
    			$productDetailArray['product_detail']['regular_variations_charges'] = $productDetailArray['data'][$productId]['pricing'][$usedKey]; // regular_variations_charges
    		}


    		$productDetailArray['product_images'] = $defaultImageUrl;  //$this->pm->getProductImages($productId);
    		$productDetailArray['product_detail']['culture_product_id']= $productDetailArray['data'][$productId]['culture_product_id'];
    		$productDetailArray['product_detail']['product_id']= $productDetailArray['data'][$productId]['product_id'];
    		$productDetailArray['product_detail']['supplier']['supplier_id']= $productDetailArray['data'][$productId]['supplier']['supplier_id'];
    		//$productDetailArray['product_detail']['supplier']['ob_customer_id']= $productDetailArray['data'][$productId]['supplier']['ob_customer_id']; // new 24/9/15//

//     		 if(isset($productDetailArray['data'][$productId]['supplier']['ob_customer_id']))
    		    $productDetailArray['product_detail']['supplier']['ob_customer_id']= $productObCustomerId;
//     		 else return 'OB_ERROR';

    		if ($productDetailArray == null) {
    			/* if no product found Through exception */
    			$productDetailArray = '';
    			// throw new NotFoundHttpException('Product not found');
    		} else{

    			$productDetailArray['configuration'] = array();
    			$productDetailArray['configuration']['unique_identifier'] = md5(time().uniqid());

    			if( $flyerUniqueId ) {
    				$productDetailArray['flyerUniqueId'] = $flyerUniqueId;
    				//$flyerHTML = $em->getRepository('OfficeBrainFlyerBundle:Flyer')->fetchFlyerHTML($flyerUniqueId);
    				$flyerHTML = $this->fetchFlyer($flyerUniqueId);

    				if($flyerHTML) {
    					$productDetailArray['flyerHTML'] = $flyerHTML[0]->getFlyerHtml();
    				} else {
    					$productDetailArray['flyerHTML'] = '';
    				}
    			}
    			else {
    				$productDetailArray['update'] = false;
    				$productDetailArray['flyerUniqueId'] = uniqid().time().$this->session->getId();
    				$this->session->get('flyerUniqueId', $productDetailArray['flyerUniqueId']);
    				$productDetailArray['flyerHTML'] = '';
    			}

    			//$productDetailArray = $em->getRepository('OfficeBrainFlyerBundle:Flyer')->convertImageToTransparent($this->request, $convert, $productDetailArray, $this->flyerImagesPath, $this->apiImagePath, $this->flyerImageURL);
    			$productDetailArray = $this->convertImageToTransparent($convert, $productDetailArray, $flyerImagesPath, $apiImagePath, $flyerImageURL, $productId);

    			if($productDetailArray == 'IS_NOT_VALID_IMG'){
    				return 'Error';
    			}
    		}
    		return $productDetailArray;
    	}

    	/**
    	 * @author Employee Id: 4571
    	 *
    	 * Description : Flyer List
    	 *
    	 * @param null
    	 *
    	 * @return Data Array
    	 *
    	 * @throws null
    	 *
    	 **/
    	public function getFlyerListAjax($page='',$recordPerPage='',$subids)
    	{
    		$flyerArray = array();
    		$flyerResults = array();
    		$startDate = '';
    		$endDate = '';
    		$adminUser = false;
    		$searchWord=trim($this->request->get('flyer_search_query'));
    		$this->getCultureValueAjax();
    		if ($this->countryCode)
    			$this->countryId = $this->getCountryIdByCode($this->countryCode);
    		if ($this->languageCode)
    			$this->languageId = $this->getLanguageIdByCode($this->languageCode);
    		$isAdmin = $this->flyerRepository->findAdminUser();
    		if($isAdmin!="" && sizeof($isAdmin)>0)
    			$adminUser = true;
    		$flyerArray = $this->flyerRepository->findActiveFlyerList($this->countryId, $this->languageId, $searchWord, $adminUser,$page,$recordPerPage,$subids);

		    $this->responseArray['culture'] = $this->culture;
		    $this->responseArray['languageCode'] = $this->languageCode;
		    $this->responseArray['countryCode'] = $this->countryCode;
		    $this->responseArray['recordSet']= $flyerArray;
		    return $this->responseArray;
    	}

    /**
     *
     * @author Employee Id: 4571
     *
     * Description : save flyer html
     *
     * @param : $productAdminManager
     *
     * @return null
     *
     * @throws null
     *
     **/
	 public function saveFlyerHtml($productAdminManager, $userManager)
	 {
        $productId = $this->request->get('productId');
        $apiSupplierId = $this->request->get('supplierId'); // api SupplierId
        $obCustomerId = $this->request->get('obCustomerId');
        
        $mappedId = $userManager->supplierIdByObCustomerId($obCustomerId); // service used ..to fetch mapped supplier id with web client !

	
        $supplierId = !empty($mappedId)?$mappedId[0]['id']:'';

        //echo $supplierId; exit;

        //supplierIdByObCustomerId

        $flyerHTML = $this->request->get('flyerHTML');

        $flyerType = $this->request->get('flyerType');
        $customUniqueId = $this->request->get('flyerUniqueId');
        $this->session->set('flyerUniqueId', $customUniqueId);
        //$flyerExists = $this->findOneBy(array('uniqueId' => $customUniqueId)); // old one
        $flyerExists =  $this->flyerRepository->findByUniqueID($customUniqueId);   // new

        if($flyerExists) {
        $pid = $flyerExists[0]->getId();
        $flyer =  $this->flyerRepository->find($pid); // new

        } else {
            $flyer = new Flyer();
        }

        $locale = $this->request->get('_locale'); // en_us

        if($locale!=""){
        	@list($localeCulture,$localeCountry) = explode("_", $locale);
        }

        $productCulture = $localeCulture."_".$localeCountry;

        $cultureId =  $this->getLanguageIdByCode($localeCulture);

        $countryId= $this->getCountryIdByCode(strtolower($localeCountry));

        //$title = $this->getEntityManager()->getRepository('OfficeBrainProductBundle:CultureProducts')->find($productId); // old
        $productDetailArray =  $productAdminManager->view($productId, $productCulture); // new service

        $flyer->setProductId($productId);

        $flyer->setTitle($productDetailArray['data'][$productId]['basic_information']['title']); //  old used: - > $title->getTitle()
        $flyer->setFlyerType($flyerType);
        $flyer->setCreatedAt(new \DateTime(date('Y-m-d')));
        $flyer->setCreatedUid($this->projectSetting['user_id']);
        $flyer->setFlyerHtml($flyerHTML);
        $flyer->setSessionId($this->session->getId());
        $flyer->setUniqueId($customUniqueId);
        $flyer->setValidUntilDate(new \DateTime(date('Y-m-d',strtotime('+1 year'))));
        $flyer->setPublishedFlag('0');
        $flyer->setCulture($cultureId);
        $flyer->setCountryId($countryId);
        //$flyer->setUserId($userId);
        $flyer->setSupplierId($supplierId);
        $flyer->setInstanceId($this->projectSetting['instance_id']);
        $flyer->setInstanceType($this->projectSetting['instance_type']);

        $this->entityManager->persist($flyer);
        $this->entityManager->flush();

        $lastInsertedId	= $flyer->getId();

        return $lastInsertedId;
    }

    /**
     *
     * @author Employee Id: 4571
     *
     * Description : save flyer html
     *
     * @param : null
     *
     * @return null
     *
     * @throws null
     *
     **/
    public function saveAddFlyer($flyer, $form, $rootDir, $countryId, $cultureId, $flyerscategoryId)
    {
    	 
    	$img	=	$form->get('flyerUploadedPath')->getData();
    	$extraImg	=	$form->get('extraFlyerUploadedPath')->getData();
    	$pdf	=	$form->get('flyerUploadedPdf')->getData();
    	$extraPdf =	$form->get('extraFlyerUploadedPdf')->getData();
    	
		$validUntilDate	=	$form->get('validUntilDate')->getData();
		list($month, $date, $year) = explode('/',$validUntilDate);
    	$validUntilDate =  date("Y/m/d", mktime(0, 0, 0, $month, $date, $year));
		if($img)
    	{
			list($width,$height)=@getimagesize($img);
			//echo $width." >>> ".$height; //exit;
    		if($width < 600)
    		{
    			return "WIDTH";
    		}
    		else if($height < 780)
    		{
    			return "HEIGHT";
    		}
			$imagename = $this->uploadFile($img,$rootDir);
			$flyer->setFlyerUploadedPath($imagename);
		}
		/*else
		{
			
				$flyer->setFlyerUploadedPath($flyerUploadedPath);
		}*/
		
		if($extraImg)
		{
			list($width,$height)=@getimagesize($extraImg);
			//echo $width." >>> ".$height; //exit;
			if($width < 600)
			{
				return "EXTRA_WIDTH";
			}
			else if($height < 780)
			{
				return "EXTRA_HEIGHT";
			}
			$imagename = $this->uploadFile($extraImg,$rootDir);
			$flyer->setExtraFlyerUploadedPath($imagename);
		}
		/*else
		{
				
			$flyer->setExtraFlyerUploadedPath($extraFlyerUploadedPath);
		}*/

		if($pdf)
		{
			//echo 'hel';
			$pdfname = $this->uploadFile($pdf,$rootDir);
			$flyer->setFlyerUploadedPdf($pdfname);
		}
		/*else
		{
			$flyer->setFlyerUploadedPdf($flyerUploadedPdf);
		}*/
		 
		if($extraPdf)
		{
			//echo 'hel';
			$pdfname = $this->uploadFile($extraPdf,$rootDir);
			$flyer->setExtraFlyerUploadedPdf($pdfname);
		}
		/*else
		{
			$flyer->setExtraFlyerUploadedPdf($extraPdf);
		}*/
    	
    	//$pdfname = $this->uploadFile($pdf,$rootDir);
    	
		$extension = $img->getClientOriginalExtension() ;
    	if($extension != 'pdf'){$extension = 'image'; }

    	//$flyer->setFlyerUploadedPath($imagename);
    	//$flyer->setFlyerUploadedPdf($pdfname);
    	
    	$flyer->setFlyerType($extension);
    	$flyer->setSessionId($this->session->getId());

    	$flyer->setPublishedFlag('1');

    	$flyer->setUniqueId(md5(time().uniqid()));

    	$flyer->setValidUntilDate(new \DateTime($validUntilDate));

    	$flyer->setCountryId($countryId);
    	$flyer->setCulture($cultureId);
    	$flyer->setflyerscategoryId($flyerscategoryId);
    	$flyer->setsupplierId(5);

    	$flyer->setCreatedAt(new \DateTime(date('Y-m-d')));
    	$flyer->setCreatedUid($this->projectSetting['user_id']);
    	$flyer->setInstanceId($this->projectSetting['instance_id']);
    	$flyer->setInstanceType($this->projectSetting['instance_type']);
    	$this->entityManager->persist($flyer);
    	$this->entityManager->flush();

    }


    /**
     *
     * @author Employee Id: 4571
     *
     * Description : save flyer html
     *
     * @param : null
     *
     * @return null
     *
     * @throws null
     *
     **/
    public function saveEditFlyer($flyer, $form, $countryId, $cultureId, $flyerscategoryId, $titleOld,$rootDir,$flyerUploadedPath,$flyerUploadedPdf,$extraFlyerUploadedPdf, $extraflyerUploadedPath)
    {
    	$img	=	$form->get('flyerUploadedPath')->getData();
    	$extraImg	=	$form->get('extraFlyerUploadedPath')->getData();
    	$pdf =	$form->get('flyerUploadedPdf')->getData();
    	$extraPdf =	$form->get('extraFlyerUploadedPdf')->getData();
    	
    	$validUntilDate	=	$form->get('validUntilDate')->getData();

    	list($month, $date, $year) = explode('/',$validUntilDate);
    	$validUntilDate =  date("Y/m/d", mktime(0, 0, 0, $month, $date, $year));

    	if($img)
    	{
    		list($width,$height)=@getimagesize($img);
    		//echo $width." >>> ".$height; //exit;
    		if($width < 600)
    		{
    			return "WIDTH";
    		}
    		else if($height < 780)
    		{
    			return "HEIGHT";
    		}
    		$imagename = $this->uploadFile($img,$rootDir);
    		$flyer->setFlyerUploadedPath($imagename);
    	}
    	else
    	{
    		
    		$flyer->setFlyerUploadedPath($flyerUploadedPath);
    	}

    	if($extraImg)
    	{
    		list($width,$height)=@getimagesize($extraImg);
    		//echo $width." >>> ".$height; //exit;
    		if($width < 600)
    		{
    			return "EXTRA_WIDTH";
    		}
    		else if($height < 780)
    		{
    			return "EXTRA_HEIGHT";
    		}
    		$imagename = $this->uploadFile($extraImg,$rootDir);
    		$flyer->setExtraFlyerUploadedPath($imagename);
    	}
    	else
    	{
    	
    		$flyer->setExtraFlyerUploadedPath($extraflyerUploadedPath);
    	}

    	if($pdf)
    	{
    		//echo 'hel';
    		$pdfname = $this->uploadFile($pdf,$rootDir);
    		$flyer->setFlyerUploadedPdf($pdfname);
    	}
    	else
    	{
    		$flyer->setFlyerUploadedPdf($flyerUploadedPdf);
    	}
    	
    	if($extraPdf)
    	{
    		//echo 'hel';
    		$pdfname = $this->uploadFile($extraPdf,$rootDir);
    		$flyer->setExtraFlyerUploadedPdf($pdfname);
    	}
    	else
    	{
    		$flyer->setExtraFlyerUploadedPdf($extraFlyerUploadedPdf);
    	}
    
    	//die();
    	 
    	$flyer->setValidUntilDate(new \DateTime($validUntilDate));

    	$titleNew = $flyer->getTitle();
    	$find = '<div class="fl-text-container for-title-change">'.$titleOld.'</div>';
    	$replace = '<div class="fl-text-container for-title-change">'.$titleNew.'</div>';
    	$arr = $flyer->getFlyerHtml();
    	$newHtml = str_replace($find,$replace,$arr);
    	$flyer->setFlyerHtml($newHtml);
    	$flyer->setflyerscategoryId($flyerscategoryId);
    	//$flyer->setsortPosition(null);
    	$flyer->setUpdatedAt(new \DateTime(date('Y-m-d')));
    	$flyer->setUpdatedUid($this->projectSetting['user_id']);
    	$flyer->setInstanceId($this->projectSetting['instance_id']);
    	$flyer->setInstanceType($this->projectSetting['instance_type']);
		$this->entityManager->persist($flyer);
    	$this->entityManager->flush();

    }

    /**
     *
     * @author Employee Id: 4571
     *
     * Description : Upload flyer files
     *
     * @param : $ufile, $rootDir
     *
     * @return name
     *
     * @throws null
     *
     **/
    public function uploadFile($ufile, $rootDir)
    {	
    	if($ufile->getClientMimeType() == 'application/pdf'){
    		$name = 'flyer'.sha1(time().$ufile->getClientOriginalName());
    		$extension = $ufile->getClientOriginalExtension() ;
    		$directory =  $rootDir. '/../web/images/uploads/flyers/flyerpdf/';
    		if ( !file_exists($directory) ) {
    			$oldmask = umask(0);
    			mkdir ($directory, 0777, true);
    		}
    		$ufile->move($directory, $name.'.'.$extension);
    		$name = $name.'.'.$extension;
    	}else{
    		$name = 'thumb_'.sha1(time().$ufile->getClientOriginalName());
    		$extension = $ufile->getClientOriginalExtension() ;
    		$directory = $rootDir . '/../web/images/uploads/flyers/flyerthumb/';
    		if ( !file_exists($directory) ) {
    			$oldmask = umask(0);  
    			mkdir ($directory, 0777, true);
    		}
    		$ufile->move($directory, $name.'.'.$extension);
    		$name = $name.'.'.$extension;
    	}

    	return $name;
    }

    /**
     *
     * @author Employee Id: 4571
     *
     * Description : find flyer details by id
     *
     * @param : $id
     *
     * @return name
     *
     * @throws null
     *
     **/
    public function findById($id)
    {
    	return $this->flyerRepository->find($id);
    }

    /**
     *
     * @author Employee Id: 4571
     *
     * Description : delete flyer
     *
     * @param : null
     *
     * @return name
     *
     * @throws null
     *
     **/
    public function deleteRecords()
    {

    	if($this->request->get('action')=="delete")
    	{
    		
    		 $flyer = $this->flyerRepository->deleterecord($this->request->get('id'));

    		 if($flyer>0)
    		 {
    		 	return $returnMessage =  'SUCCESS';
    		 }
    		 else
    		 {
    		 	return $returnMessage = 'FAIL';

    		 }
    		 
    	}
    }


    /**
     *
     * @author Employee Id: 4571
     *
     * Description : send flyer via email
     *
     * @param 1: $locale,
     * @param 2: $id
     * @param 3: $templateParameterArray
     * @param 4: $emailService
     * @param 5: $to
     * @param 6: $email
     * @param 7: $emailSubject
     * @param 8: $flyerAttachmentPath
     *
     * @return flag true/false
     *
     * @throws null
     *
     **/
    public function flyerSendMail($locale, $id, $templateParameterArray, $emailService, $to, $email, $emailSubject, $flyerAttachmentPath)
    {
    	$eventKey = 'send_flyer_in_mail_from_admin_create_flyer';

    	$cc = '';
    	$bcc = '';

    	if($locale!=""){
    		@list($localeCulture,$localeCountry) = explode("_", $locale);
    	}

    	$productCulture = $localeCulture."_".$localeCountry;
    	$cultureId =  $this->getLanguageIdByCode($localeCulture); // new
    	$flyer= $this->findById($id);
    	$flyerThumb = $flyer->getFlyerThumb();
    	$flyerUploadedPath = $flyer->getFlyerUploadedPath();
    	$flyerUploadedPdf = $flyer->getflyerUploadedPdf();
    	if($flyerThumb != ""){
    		$flyerAttachment = $flyerAttachmentPath."flyers/flyerthumb/".$flyerUploadedPath;
    	}
    	if($flyerUploadedPath != ""){
    		$flyerAttachment = $flyerAttachmentPath."flyers/flyerpdf/".$flyerUploadedPdf;
    	}

    	return $emailService->sendMail($eventKey, $to, $templateParameterArray, $cultureId, $email, $emailSubject, $flyerAttachment, $cc, $bcc);
    }


    /**
     *
     * @author Employee Id: 4571
     *
     * Description : prepare email message
     *
     * @param : null
     *
     * @return flag true/false
     *
     * @throws null
     *
     **/
    public function prepareEmailMessage()
    {
    	$this->response = '';

    	$name = $this->request->get('name');
    	$message = $this->request->get('message');
        $this->response['name']=$name;
        $this->response['message']=$message;

        return $this->response;


    }

    /**
     *
     * @author Employee Id: 4571
     *
     * Description : send flyer via email
     *
     * @param 1: $locale
     * @param 2: $emailService
     * @param 3: $flyerAttachment
     * @param 4: $renderResponse
     *
     * @return flag true/false
     *
     * @throws null
     *
     **/
    public function sendEmailMessage($locale, $emailService, $flyerAttachment, $renderResponse)
    {

    	$to = $this->request->get('to', '');
    	$cc = $this->request->get('cc', '');
    	$message = $this->request->get('message');
    	$bcc ='';

    	$name = $this->request->get('name');
    	$email = $this->request->get('email'); // from email ..
    	$emailSubject = $this->request->get('subject');

    	if($locale!=""){
    		@list($localeCulture,$localeCountry) = explode("_", $locale);
    	}

    	$productCulture = $localeCulture."_".$localeCountry;
    	$cultureId =  $this->getLanguageIdByCode($localeCulture); // new

        $eventKey = 'send_flyer_in_mail_from_admin_create_flyer';

        $templateParameterArray = array(
        		'message' => $message,
        		'send_flyer_in_email_to_customer_fromadmin_template' => $renderResponse->getContent()
        );

        return $emailService->sendMail($eventKey, $to, $templateParameterArray, $cultureId, $email, $emailSubject, $flyerAttachment, $cc, $bcc); // new

    }

    /**
     *
     * @author Employee Id: 4571
     *
     * Description : Download Flyer from list
     *
     * @param 1: $flyer
     * @param 2: $flyerBasePath
     *
     * @return flag true/false
     *
     * @throws null
     *
     **/
    public function downloadFrontFlyer($flyer, $flyerBasePath)
    {
    	$flyerThumb = $flyer->getFlyerThumb();
    	$flyerType = $flyer->getFlyerType();
    	$flyerUploadedPath = $flyer->getFlyerUploadedPath();

    	if($flyerThumb != ""){
    		$flyerAttachment = $flyerBasePath."flyer-created/".$flyerThumb;
    		$fT = $flyerThumb;
    	}
    	if($flyerUploadedPath != ""){
    		$flyerAttachment = $flyerBasePath."flyer-own-images/".$flyerUploadedPath;
    		$fT = $flyerUploadedPath;
    	}

    	if (file_exists($flyerAttachment)) {
    		if($flyerType=="image"){
    			header('Content-Type: image/jpeg');
    		}else{
    			header('Content-Type: application/pdf');
    		}
    		header('Content-Disposition: attachment; filename='.($fT));
    		header('Expires: 0');
    		header('Cache-Control: must-revalidate');
    		header('Pragma: public');
    		header('Content-Length: ' . filesize($flyerAttachment));
    		readfile($flyerAttachment);
    		exit;
    	}else{

    	}
    }

    /**
     *
     * @author Employee Id: 4571
     *
     * Description : Publish Flyer
     *
     * @param: null
     *
     * @return flag true/false
     *
     * @throws null
     *
     **/
    public function publishFlyer($flyerThumb, $flyer)
    {
    	$status = $this->request->get('value');
    	$var_jason = array();

    	if($status == 0){
    		$flyer->setFlyerThumb(null);
    		$flyer->setPublishedAt(null);
    		$flyer->setPublishedFlag(0);
    		$var_jason['msg'] = "deactivated";
    	}else if($status == 1){
    		$flyer->setPublishedFlag(1);
    		$flyer->setPublishedAt(new \DateTime());
    		$flyer->setFlyerThumb($flyerThumb);
    		$var_jason['msg'] = "activated";
    	}

    	$flyer->setPublishedFlag($status);

    	$this->entityManager->persist($flyer);
    	$this->entityManager->flush();
    	//$var_jason['success'] = 'yes';

    	return $var_jason;
    }
    /**
     *
     * @author Employee Id: 5430
     *
     * Description : Publish Flyer
     *
     * @param: null
     *
     * @return flag true/false
     *
     * @throws null
     *
     **/
    public function getFlyerSubCategories($parentcategoryid)
    {
    	return $this->flyerRepository->getFlyerSubCategories($parentcategoryid);
    }
    public function saveFlyerPosition($posArray)
    {
    	$flag=true;
    	$query='';
    	foreach($posArray as $id=>$posValue)
    	{
    		if(IS_NUMERIC($posValue))
    		{
    			//$query=$query.$this->flyerRepository->getFlyerPositionUpdateQuery($id,$posValue);
    			$this->flyerRepository->updateFlyerPositionById($id,$posValue);
    		}
    		else
    		{
    			$flag=false;
    			break;
    		}
    		
    	}
    	if($flag)
    	{
    		//$this->flyerRepository->updateFlyerPosition($query);
    		return true;
    	}
    	else
    	{
    		return false;
    	}
    	
    }
    public function getFlyertitleBySlug($slug)
    {
    	$countryId=$this->getCountryIdByCode($this->countryCode);
    	return $this->flyerRepository->getFlyertitleBySlug($slug,$countryId);
    }
    
    public function importFlyer($categoryId,$rootDir,$limit){
    	
    	$flyerSheet = $rootDir.'/images/uploads/flyers/';
    	
    	$flyerArray = array();
    	
    	$file = fopen($flyerSheet."gold_star_flyer.csv","r");
    	while(! feof($file))
    	{ 
    	  $flyerArray[] = fgetcsv($file);
    	}
    	
    	fclose($file);
    	array_shift($flyerArray);
    	$this->importFlyerInformationToDb($categoryId,$flyerArray,$flyerSheet,$limit);
    	die;
    	
    }
    
    public function importFlyerInformationToDb($categoryId,$flyerArray,$flyerSheet,$limit){
    	//echo '<pre>'; print_r($flyerArray); die;
    	 foreach ($flyerArray as $key=>$val){
    	  if(!empty($val) and $key < $limit){	 
    		echo $key.'---'; 
    		$flyer = new Flyer();
    		
    		$flyerImgPath = $flyerSheet.'flyerthumb/';
    	    $flyerPdfPath = $flyerSheet.'flyerpdf/';
    	    	
    	    $imageName = 'thumb_'.sha1(time().$val[2]).'.jpg';
    	    $pdfName = 'flyer'.sha1(time().$val[3]).'.pdf';
    	    $imageCNName = 'thumb_'.sha1(time().$val[4]).'.jpg';
    	    $pdfCNName = 'flyer'.sha1(time().$val[5]).'.pdf';
    	    	
    	    $sourceImgPath = $flyerSheet.'flyer_img_pdf/'.$val[2];
    	    $sourcePdfPath = $flyerSheet.'flyer_img_pdf/'.$val[3];
    	    $sourceImgCnPath = $flyerSheet.'flyer_img_pdf/'.$val[4];
    	    $sourcePdfCnPath = $flyerSheet.'flyer_img_pdf/'.$val[5];
    	    	
    	    $destinationImgPath = $flyerImgPath.$imageName;
    	    $destinationPdfPath = $flyerPdfPath.$pdfName;
    	    $destinationImgCnPath = $flyerImgPath.$imageCNName;
    	    $destinationPdfCnPath = $flyerPdfPath.$pdfCNName;
    		
    	    copy($sourceImgPath,$destinationImgPath);
    	    copy($sourcePdfPath,$destinationPdfPath);
    	    copy($sourceImgCnPath,$destinationImgCnPath);
    	    copy($sourcePdfCnPath,$destinationPdfCnPath);
    	    
    	    $flyer->setFlyerUploadedPath($imageName);
    	    $flyer->setFlyerUploadedPdf($pdfName);
    	    $flyer->setExtraFlyerUploadedPath($imageCNName);
    	    $flyer->setExtraFlyerUploadedPdf($pdfCNName);
    	    
    	    $extension = 'image';
    	    $flyer->setTitle($val[1]);
    	    $flyer->setFlyerType($extension);
        	$flyer->setSessionId(md5(time().uniqid()));

        	$flyer->setPublishedFlag('1');

        	$flyer->setUniqueId(md5(time().uniqid()));

        	$flyer->setValidUntilDate(new \DateTime(date('Y-m-d')));

        	$flyer->setCountryId(233);
        	$flyer->setCulture(1);
        	$flyer->setflyerscategoryId($categoryId);
        	$flyer->setsupplierId(5);

        	$flyer->setCreatedAt(new \DateTime(date('Y-m-d')));
        	$flyer->setCreatedUid($this->projectSetting['user_id']);
        	$flyer->setInstanceId($this->projectSetting['instance_id']);
        	$flyer->setInstanceType($this->projectSetting['instance_type']);
        	$this->entityManager->persist($flyer);
        	$this->entityManager->flush();
    	  }	
    
    	 }
    }
    
}
