<?php

namespace OfficeBrain\Bundle\FlyerBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Translation\Translator;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Doctrine\ORM\EntityRepository;
//use OfficeBrain\Bundle\FlyerBundle\Controller\LiquenImg;
use OfficeBrain\Bundle\CoreBundle\Library\LiquenImg;
use OfficeBrain\Bundle\UserBundle\Library\Email as EmailLibrary;
use OfficeBrain\Bundle\FlyerBundle\Entity\Flyer;
use OfficeBrain\Bundle\FlyerBundle\Form\FlyerType;
use OfficeBrain\Bundle\CoreBundle\Library as CoreLibrary;
use OfficeBrain\Bundle\ProductBundle\Entity\CultureProducts;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\JsonResponse;
use OfficeBrain\Bundle\SearchBundle\Manager\SearchManager;
use OfficeBrain\Bundle\SearchBundle\Manager\ProductManager;
use OfficeBrain\Bundle\SearchBundle\Twig\Extension\Base64DecodeExtension;
use Symfony\Component\Validator\Constraints\DateTime;
use Symfony\Component\Validator\ExecutionContextInterface;
use Symfony\Component\Validator\Constraints\Length;
use OfficeBrain\Bundle\CoreBundle\CustomeHandler as FormErrorManager;

/**
 * This controller is implemented to provide Flyer functionality on Product
 *
 * @author Employee Id: 4273
 *
 */

class FlyerAdminController extends Controller
{
	private $request;
	private $session;
	private $translator;
	private $projectSetting;
	private $responseArray;
	private $manager;
	private $uploadHandler;
	private $emailService;
	private $userManager;
	private $baseUrl;
	private $flyerAttachmentPath;
	private $flyerAccessField;
	private $flyerConfigurationField;
	private $projectUserSetting;

   /**
	* @author Employee Id: 4273
	*
	* Description: To set member variables default value
	*
	* @return NULL
	*
	*/
	public function __construct() {
		$this->request = null;
		$this->projectSetting = null;
		$this->responseArray = null;
		$this->session = null;
		$this->flyerManager = null;
		$this->userManager = null;
		$this->baseUrl = null;
		$this->uploadHandler = null;
        $this->emailLibrary = null;
        $this->filePath = null;
        $this->flyerImageURL = null;
        $this->flyerImagesPath = null;
        $this->productAdminManager = null;
        $this->emailService = null;
        $this->formErrorManager = new FormErrorManager\JsonError ();
        $this->flyerAttachmentPath = null;
        $this->flyerAccessField = null;
        $this->flyerConfigurationField = null;
        $this->projectUserSetting = null;
	}

	/**
	 * @author Employee Id: 4273
	 *
	 * Description: To unset member variables
	 *
	 * @return NULL
	 *
	 */
	public function __destruct()
	 {

		unset ( $this->request );
		unset($this->flyerManager);
		unset($this->projectSetting);
		unset($this->responseArray);
		unset($this->session);
		unset($this->uploadHandler );
		unset($this->emailLibrary );
		unset($this->filePath );
		unset($this->flyerImageURL );
		unset($this->flyerImagesPath );
		unset($this->formErrorManager );
		unset($this->productAdminManager);
		unset($this->emailService);
		unset($this->userManager);
		unset($this->baseUrl);
		unset($this->flyerAttachmentPath);
		unset($this->flyerAccessField);
		unset($this->flyerConfigurationField);
		unset($this->projectUserSetting);


	}

	/**
	 * @author Employee Id: 4273
	 *
	 * Description: Create various objects required action in this class
	 *
	 * @return NULL
	 */
	public function initAction()
	 {
		$this->request = $this->getRequest();
		$this->session = $this->request->getSession();
		$this->projectSetting = $this->request->get('project_setting');
		$this->projectUserSetting = $this->request->get('project_user_setting');
		$this->flyerAccessField= $this->projectSetting['access_rule']['promo_discount']['option']['flyer'];
		$this->flyerConfigurationField=$this->projectSetting['configuration_rule']['promo_discount']['option']['flyer'];
		$this->translator = $this->get('translator');
		$this->flyerManager = $this->get('office_brain_flyer_manager');
		$this->uploadHandler = $this->get('office_brain_core.uploadhandler');
		$this->apiImagePath = $this->get('kernel')->getRootDir() . '/../web/images/uploads/';
		$this->flyerImagesPath = $this->apiImagePath.'images-used/';
		$this->filePath = $this->get('kernel')->getRootDir() . '/../web/';
		$this->baseUrl = $this->container->getParameter('base_url'); //die;
		$this->assetfilePath  =$this->container->getParameter('base_url'); //  asset_file_path <===== need to check
		$this->productAdminManager = $this->get('office_brain_product_admin_manager');
		$this->emailService = $this->get('office_brain_email_service');
		$this->userManager = $this->get('office_brain_user_manager');
		$this->flyerAttachmentPath =  $this->container->getParameter('flyer_base_url');
		$this->responseArray = array();

		$this->loginUserType = $this->projectUserSetting['user_data']->getUserType(); // ?$this->projectUserSetting['user_data']->getUserType():'0';

		// $this->flyerConfigurationField['no_of_record_per_page'] = 10; // temp ... removed after test
		// echo $this->projectSetting['instance_id']; exit;
	}

	private function prepareFormJsonError($form)
	{
		return array (
				'form_name' => $form->getName (),
				'form_status' => 'error',
				'form_errors' => $this->formErrorManager->prepareErrorArray ( $this->get ( 'validator' )->validate ( $form ) )
		);
	}

	/**
	 * @author Employee Id: 4273
	 *
	 * Product Detail data.
	 *
	 * @param string product slug
	 *
	 * @return array of csv file information is success else false if there was an error
	 *
	 * @Route("/admin/{_locale}/flyer/{product_id}/{product_slug}", name="office_brain_flyerbundle_flyeradmin_createflyer"),
	 *
	 * @Method({"GET"})
	 *
	 * @Template("OfficeBrainFlyerBundle:FlyerAdmin:createFlyer")
	 *
	 */
	public function createFlyerAction()
	{ // officebrain_flyer_bundle_index indexAction // $culture,$product_id,$product_slug

	 	$this->initAction();

	 	$convert = $this->container->getParameter('convert');
	 	$locale = $this->request->get('_locale'); // en_us
	    $cultureId = $this->flyerManager->findCultureId();
	 	$this->responseArray = $this->flyerManager->generateFlyer($this->productAdminManager, $convert, $this->flyerImagesPath, $this->apiImagePath, $this->flyerImageURL);

	 	if ($this->responseArray == "Error") {  // if error than render and show error
	 		$this->get('session')->getFlashBag()->add('error_message', $this->translator->trans('admin.error.blank_image'));
	 		return $this->redirect($this->generateUrl('office_brain_flyerbundle_flyeradmin_listflyer'));
	 	}
	 	elseif($this->responseArray == 'OB_ERROR'){
	 	    $this->get('session')->getflashbag()->add('error_message', $this->translator->trans('admin.error.ob_id_not_found'));
	 	    return $this->redirect($this->generateUrl('office_brain_flyerbundle_flyeradmin_listflyer'));
	 	}
	 	$this->responseArray['flyerAccessField'] = $this->flyerAccessField;
	 	$this->responseArray['flyerConfigurationField'] = $this->flyerConfigurationField;


        return $this->render('OfficeBrainFlyerBundle:FlyerAdmin:createFlyer.html.twig', array (
        		'data' => $this->responseArray,'culture'=>$cultureId,'locale'=>$locale
        ));


	}

    /**
	 *  @author 4273
	 *  Description: Server action
	 *
	 *  @param string initialVal: to fetch data by this value
	 *
	 *  @return array of fetched data
	 *
     *  @Route("/admin/server/php/", name="officebrain_flyer_upload_image")
     *
	 */
	public function serverAction()
	{
        //error_reporting(E_ALL | E_STRICT);
        $this->initAction();
        $this->uploadHandler->setOptions();

        header('Pragma: no-cache');
        header('Cache-Control: no-store, no-cache, must-revalidate');
        header('Content-Disposition: inline; filename="files.json"');
        header('X-Content-Type-Options: nosniff');
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: OPTIONS, HEAD, GET, POST, PUT, DELETE');
        header('Access-Control-Allow-Headers: X-File-Name, X-File-Type, X-File-Size');

        switch ($_SERVER['REQUEST_METHOD']) {
            case 'OPTIONS':
                break;
            case 'HEAD':
            case 'GET':
               $ets =  $this->uploadHandler->get();
                break;
            case 'POST':
                if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
                    $this->uploadHandler->delete();
                } else {
                    $this->uploadHandler->post();
                }
                break;
            case 'DELETE':
            	$this->uploadHandler->delete();
                break;
            default:
                    header('HTTP/1.1 405 Method Not Allowed');
        }

        exit();
	}


    /**
     * @author 4273
     *
     * Description: Save Flyer
     *
     * @return null
     *
     * @Route("/admin/{_locale}/save-flyer", name="office_brain_flyerbundle_flyeradmin_saveflyer")
     *
     */
    public function saveFlyerAction()
    {       //echo "Here "; die;
    	$this->initAction();

        $this->flyerManager->saveFlyerHtml($this->productAdminManager, $this->userManager);

        echo 'FlyerSaved';
        exit();
    }

    /**
     * @author 4273
     *
     * Description: Reset flyer html
     *
     * @param : null
     *
     * @return null
     *
     * @Route("/admin/{_locale}/reset-flyer", name="office_brain_flyerbundle_flyeradmin_resetflyer")
     *
     */
    public function resetFlyerAction() // officebrain_reset_flyer
    {
    	$this->initAction();
        $this->session->set('flyerUniqueId', '');

        $this->flyerManager->resetFlyer();
        exit();
    }

    /**
     * @author 4273
     *
     * Description: Send the created flyer as an attachment in the email
     *
     * @param null
     *
     * @return json array
     *
     * @Route("/admin/{_locale}/send-flyer-via-email", name="office_brain_flyerbundle_flyeradmin_sendflyerviaemail")
     *
     */
    public function sendFlyerViaEmailAction() // officebrain_send_flyer_via_email
    {
        $this->initAction();

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

        $renderResponse = $this->render('OfficeBrainFlyerBundle:FlyerAdmin:sendFlyer.html.twig', $statusResponse);
        $flyerUniqueId = $this->request->get('flyerUniqueId');
        $downloadFormat = $this->request->get('downloadFormat', 'pdf');
        $flyerAttachment = $this->generateFlyerImgOrPDFAction($flyerUniqueId, $downloadFormat, 'no', 1);

        $status = $this->flyerManager->sendEmailMessage($locale, $this->emailService, $flyerAttachment, $renderResponse);

        if($status){
       		$response = array("msg" => 'Email Sent', "status" => 'success');
        }else{
        	$response = array("msg" => 'Email Not Sent', "status" => 'failure');
        }

        return new Response(json_encode($response));

    }

    /**
     * @author 4273
     *
     * Description: Send the created flyer as a attachment in the email
     *
     * @param 1: int $flyerUniqueId
     * @param 2: $flyerType
     *
     * @return null
     *
     * @Route("/admin/{_locale}/download-flyer/{flyerUniqueId}/{flyerType}", name="officebrain_download_flyer")
     *
     */
    public function downloadFlyer($flyerUniqueId, $flyerType)
    {
    	$this->initAction();

        $this->filePath=$this->container->get('kernel')->getRootdir()."/../web/";
        $flyerUniqueId = $this->request->get('flyerUniqueId');
        $flyerAttachment = $this->generateFlyerImgOrPDFAction($flyerUniqueId, $flyerType);

        if($flyerType == 'html') {
            $fs = new Filesystem();
            $fs->mkdir($this->filePath . 'images/uploads/flyer-created/' . $this->session->getId(), 0755);
            $fileName = $this->filePath .'images/uploads/flyer-created/' . $this->session->getId() . '/flyer-' . time() . '.html';
            $fs->touch($fileName, time() + 10);
            $fs->dumpFile($fileName, $flyerAttachment);
            $flyerAttachment = $fileName;
        }

        if (file_exists($flyerAttachment)) {

        	header('Content-Description: File Transfer');

            if($flyerType=="image"){
            	header('Content-Type: image/jpeg');
            }else{
            	header('Content-Type: application/pdf');
            }

            header('Content-Disposition: attachment; filename='.basename($flyerAttachment));
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($flyerAttachment));
            readfile($flyerAttachment);
            exit;
        }
    }

    /**
     * @author 4273
     *
     * Description: generate flyer
     *
     * @param 1: $flyerUniqueId
     * @param 2: $flyerType
     * @param 3: $thumb
     * @param 4: $isMail=null
     *
     * @return generated flyer file path
     *
     * @Route("/admin/generate-flyer-pdf-or-img/{flyerUniqueId}", name="officebrain_generate_flyer_pdf_or_img")
     *
     */
    public function generateFlyerImgOrPDFAction($flyerUniqueId, $flyerType='image', $thumb = 'no', $isMail=null)
    {
    	$this->initAction();

    	$flyerHTML = $this->flyerManager->findUnique($flyerUniqueId);

        if($flyerHTML) {
            $flyerHTML = $flyerHTML[0]->getFlyerHtml();
        } else {
            $flyerHTML = '';
        }

        $relativePathFlag = ($flyerType == 'html') ? 1 : 2;

        $returnHTML = $this->renderView('OfficeBrainFlyerBundle:FlyerAdmin:generateFlyerImgOrPdf.html.twig', array (
            'flyerHTML' => $flyerHTML,
            'relativePathFlag' => $relativePathFlag

        ));

        $returnHTML = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $returnHTML);
        //echo $returnHTML; die;
        if($flyerType == 'html') {
            return $returnHTML;
        } else {
			$fileExt = ($flyerType == 'image') ? 'jpg' : $flyerType;
            $fileName = 'Flyer-' . time() . '.' . $fileExt;

            $fs = new Filesystem();

            $fs->mkdir($this->filePath . 'images/uploads/flyer-created/', 0755);

            $fs->mkdir($this->filePath . 'images/uploads/flyer-created/'. $this->session->getId(), 0755);
            $a = $this->get('knp_snappy.'.$flyerType )->generateFromHtml(
                $returnHTML,
            	$this->filePath . 'images/uploads/flyer-created/' . $this->session->getId() . '/' . $fileName

            );

        }

        if(isset($thumb) && $thumb=='yes'){
        	return  $this->session->getId() . '/' . $fileName;
        }

        if(isset($isMail))
        {
        	return $this->flyerAttachmentPath . $this->session->getId() . '/' . $fileName;
        }
        else {
        	return $this->filePath . 'images/uploads/flyer-created/'. $this->session->getId() . '/' . $fileName;
        }


    }

    /**
     *  @author 4273
     *
     *  Description: Show flyer
     *
     *  @param 1: int $flyerUniqueId
     *
     *  @return flyer html in twig
     *
     *  @Route("/admin/{_locale}/show-flyer/{flyerUniqueId}", name="office_brain_flyerbundle_flyeradmin_showflyer")
     *
     */
    public function showFlyerAction($flyerUniqueId)
    {
    	$this->initAction();

    	$flyerHTML = $this->flyerManager->fetchFlyer($flyerUniqueId);

        if($flyerHTML) {
            $flyerHTML = $flyerHTML[0]->getFlyerHtml();
        } else {
            $flyerHTML = '';
        }

        return $this->render('OfficeBrainFlyerBundle:FlyerAdmin:generateFlyerImgOrPdf.html.twig', array (
            'flyerHTML' => $flyerHTML,
            'relativePathFlag' => 1
        ));

    }


    /**
     *  @author 4493
     *
     *  Description: Share and show flyer
     *
     *  @return flyer html in twig
     *
     *  @Route("/admin/{_locale}/share-flyer/{flyerUniqueId}", name="office_brain_flyerbundle_flyeradmin_shareshowflyer")
     *
     */
    public function shareShowFlyerAction($flyerUniqueId)
    {  //  officebrain_share_show_flyer

    	$this->initAction();

    	$flyerHTML = $this->flyerManager->fetchFlyer($flyerUniqueId);

    	if($flyerHTML) {
    		$flyerHTML = $flyerHTML[0]->getFlyerHtml();
    	} else {
    		$flyerHTML = '';
    	}

    	return $this->render('OfficeBrainFlyerBundle:FlyerAdmin:generateFlyerImgOrPdf.html.twig', array (
    			'flyerHTML' => $flyerHTML,
    			'relativePathFlag' => 1
    	));

    }

    /**
     * @author 4571
     *
     * Description: Share and show flyer
     *
     * @param : null
     *
     * @return copied image filepath
     *
     * @Route("/admin/{_locale}/file-copy/", name="office_brain_flyerbundle_flyeradmin_copyimage")
     *
     */
    public function copyImageAction() //  officebrain_flyer_copy
    {
    	$this->initAction();

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

    	$tokens = explode('/', $uploadedImage);
		$fileName = urldecode($tokens[sizeof($tokens)-1]);
	    $fileToGo = $this->filePath.'/images/uploads/flyer-new-images/'.$fileName;
  	    $returnFile = $this->assetfilePath .'/images/uploads/flyer-new-images/'.$fileName;
    	copy($uploadedImage, $fileToGo);

    	echo $returnFile; exit;

    }


    /**
	 * @author 4273
	 *
	 * Description: crop image and resize
	 *
	 * @param null
	 *
	 * @return array of fetched data
	 *
     * @Route("/admin/{_locale}/server/php/image_crop_and_size", name="office_brain_flyerbundle_flyeradmin_imagecropandresize")
     *
	 */
	public function imageCropAndResizeAction()
	{     //  officebrain_flyer_upload_image_crop_n_resize
        $this->initAction();

        $this->uploadHandler->setOptions();
        $lii = new LiquenImg();

        $temp = $this->uploadHandler->getOption('relative_upload_dir');
        if(isset($_POST['source'])){
            $expArr = explode('/',$_POST['source']['file']);
            $arrSplice = array_splice($expArr,-1);
            $thePicture = substr( $temp . urldecode(array_pop($arrSplice)),1);
        }else{
            $expArr1 = explode('/',$_POST['file']);
            $arrSplice1 = array_splice($expArr1,-1);
            $thePicture = substr( $temp. urldecode(array_pop($arrSplice1)),1);
            $_POST['url']=$thePicture;
        }

        $thePicture = $this->filePath .$thePicture;

        if (!is_file($thePicture)) exit('ERROR: Source image file not found');

        if(!isset($_POST['source'])){
            $newFile = $lii->genImage($_POST);
            $thumb = $lii->genImage(array(
                'url' =>  $newFile,
                'outputFolder' => $this->filePath .'images/uploads/flyer-images/thumbnails/',
                'rename' => 'false',
                'oc' => '1',
                'width' => 'auto'
            ));

            echo json_encode(array('newFile'=>$newFile));
            exit();
        }


        $size=getimagesize($thePicture);
        $sizeRatio=$size[0]/$_POST['source']['width'];

        $newFile = $lii->genImage(array(
            'url'=>$thePicture,
            'width'=>$_POST['source']['endWidth'],
            'height'=>$_POST['source']['endHeight'],
            'oc' => '1',
            'cx' => floor($_POST['c']['x']*$sizeRatio),
            'cy' => floor($_POST['c']['y']*$sizeRatio),
            'cw' => floor($_POST['c']['w']*$sizeRatio),
            'ch' => floor($_POST['c']['h']*$sizeRatio)
        ));


        $thumb = $lii->genImage(array(
            'url' =>  $newFile,
            'outputFolder' => $this->filePath . 'images/uploads/flyer-images/thumbnails/',
            'rename' => 'false',
            'oc' => '1',
            'width' => $_POST['source']['endWidth'], // auto
            'height' => $_POST['source']['endHeight']
            //'crop' => false
        ));

        //echo 'test'; die;
        $uploadedImage = $newFile;
        $tokens = explode('/', $uploadedImage);
        $fileName = urldecode($tokens[sizeof($tokens)-1]);
        $fileToGo = $this->filePath.'images/uploads/flyer-new-images/'.$fileName;
        $returnFile = $this->assetfilePath .'/images/uploads/flyer-new-images/'.$fileName;
        copy($uploadedImage, $fileToGo);

        //print_r($file_to_go); die;
        echo json_encode(array('newFile'=>$returnFile));
        exit();
	}

	/**
	 * @author 4273
	 *
	 * @Route("admin/{_locale}/published-flyer/{id}/{uniqueId}", name="office_brain_flyerbundle_flyeradmin_publishedflyer")
	 *
	 * @Template()
	 *
	 * Description: crop image and resize
	 *
	 * @param null
	 *
	 * @return json response
	 *
	 */
	public function publishedFlyerAction()
	{ // officebrain_published_flyer
		$this->initAction();

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

		$flyer= $this->flyerManager->findById($param['id']);

		if(isset($flyer)){
			$flyerThumb = null;

			if($flyer->getFlyerUploadedPath() ==''){
				$flyerThumb = $this->generateFlyerImgOrPDFAction($param['uniqueId'],'image','yes');
			}

			$this->responseArray = $this->flyerManager->publishFlyer($flyerThumb, $flyer);

			if($this->responseArray['msg'] == "activated"){
				 $this->get('session')->getFlashBag()->add('success_message', $this->translator->trans('admin.flyer_management.publish.activated'));
			}else{
				 $this->get('session')->getFlashBag()->add('success_message', $this->translator->trans('admin.flyer_management.publish.deactivated'));
			}

		}

		return new JsonResponse($this->responseArray);
	}


	/**
	 * @author 4273
	 *
	 * @Route("admin/{_locale}/delete-flyer/{action}/{id}", name="office_brain_flyerbundle_flyeradmin_deleteflyer")
	 *
	 * @Template()
	 *
	 * Description: Delete Flyer
	 *
	 * @param null
	 *
	 * @return json response
	 *
	 */
	public function deleteFlyerAction()
	{ // officebrain_delete_flyer
		$this->initAction();

		$flyerMessage = $this->flyerManager->deleteRecords();

		switch ($flyerMessage) {
			case  'SUCCESS' :
				$this->responseArray['status'] = 'success';
				$this->responseArray['success_message'] = $this->get('translator')->trans('admin.msg.flyer_delete_msg');

				break;
			case  'FAIL':
				$this->responseArray['error_message'] = $this->get('translator')->trans('admin.msg.no_record');
				break;
		}

		return new JsonResponse($this->responseArray);

		echo $flyerMessage;
		die;

	}

	/**
	 * @author 4273
	 *
	 * Description: Add Flyer action
	 *
	 * @Route("/admin/{_locale}/add-new-flyer/", name="office_brain_flyerbundle_flyeradmin_flyernewadd")
	 *
	 * @Method({"GET","POST"})
	 *
	 * @return json response
	 *
	 * @throws null
	 *
	 * @Template()
	 *
	 */
	public function flyerNewAddAction()
	{
		$this->initAction();

		$id = $this->request->query->get('id',0);
		$locale = $this->request->get('_locale');
		$parentcategoryid = $this->request->get('pcid',0);

		$cul = $this->request->get('culture');

		if(isset($cul) && $cul!="")
		{
			 $locale = $cul;
		}

		@list($localeCulture,$localeCountry) = explode("_", $locale);
		$cultureId =  $this->flyerManager->getLanguageIdByCode($localeCulture);
		$countryId= $this->flyerManager->getCountryIdByCode(strtolower($localeCountry));
		$flyrRootDir = $this->get('kernel')->getRootDir();

		$supp = $this->flyerManager->getFlyerSubCategories($parentcategoryid);
		/*if(sizeof($supp) < 1)
		{
			$this->get('session')->getFlashBag()->add('error_message', $this->translator->trans('admin.no_supplier_err'));
		}*/

		if($id==0){
			$mod = 'add';
			$flyer = new Flyer();
		    $flyerObj = new FlyerType('add', $locale, $this->flyerManager, $this->projectSetting, $this->loginUserType,$parentcategoryid); // $this->container,$this->getUserRole,'add',$locale
		    $flyerThumb = '';
		    $flyerUploadedPath = '';
		    $extraFlyerUploadedPath = '';
		    $flyerUploadedPdf = '';
		    $extraFlyerUploadedPdf = '';
		}
		else{
			$mod = 'edit';
			$flyer = $this->flyerManager->findById($id);
			if(!$flyer){
				$this->get('session')->getFlashBag()->add('error_message', $this->translator->trans('admin.msg.no_record', array('%id%' => $id)));
				return $this->redirect($this->generateUrl('office_brain_flyerbundle_flyeradmin_listflyerajax')); //  // officebrainflyerbundle_listflyer
			}
	
			$titleOld =  $flyer->getTitle();
			$flyerThumb = $flyer->getFlyerThumb();
			$flyerUploadedPath = $flyer->getFlyerUploadedPath();
			$extraFlyerUploadedPath = $flyer->getExtraFlyerUploadedPath();
			$flyerUploadedPdf=$flyer->getFlyerUploadedPdf();
			$extraFlyerUploadedPdf=$flyer->getExtraFlyerUploadedPdf();
			
			$uniqueId = $flyer->getUniqueId();
			if($flyerUploadedPath ==''){ 
				// it will create the image for product flyers
				$flyerThumb = $this->generateFlyerImgOrPDFAction($uniqueId,'image','yes');
			}
	
			$flyer->setValidUntilDate($flyer->getValidUntilDate()->format('m/d/Y'));  // old
			$flyerObj = new FlyerType('edit', $locale, $this->flyerManager, $this->projectSetting, $this->loginUserType,$parentcategoryid); // $this->getUserRole
		}

		$form = $this->createForm($flyerObj, $flyer);
		$form->handleRequest($this->request);
		
	    if($this->request->getMethod() == 'POST'){
	    	if($id==0){
	    		
	    		if ($form->isValid()){
		    		$flyerscategoryId	=	$form->get('flyers_category_id')->getData();
					$img	=	$form->get('flyerUploadedPath')->getData();
		    		$case = $this->flyerManager->saveAddFlyer($flyer,$form,$flyrRootDir,$countryId,$cultureId,$flyerscategoryId);

		    		switch ($case) {
		    			/*case 'SIZE':
		    				$response['form_status'] = 'error';
		    				$response['form_image_error'] = $this->translator->trans("admin.flyer.imagevalidation.size");
		    				return new JsonResponse($response);
		    				break;
		    				break; */
		    			case 'HEIGHT':
		    				$response['form_status'] = 'error';
		    				$response['form_image_error'] = $this->translator->trans("admin.flyer.imagevalidation.width_height");
		    				return new JsonResponse($response);
		    				break;
		    			case 'EXTRA_HEIGHT':
		    				$response['form_status'] = 'error';
		    				$response['form_extra_image_error'] = $this->translator->trans("admin.flyer.imagevalidation.width_height");
		    				return new JsonResponse($response);
		    				break;
		    			case 'WIDTH':
							$response['form_status'] = 'error';
		    				$response['form_image_error'] = $this->translator->trans("admin.flyer.imagevalidation.width_height");
		    				return new JsonResponse($response);
		    				break;
		    			case 'EXTRA_WIDTH':
		    				$response['form_status'] = 'error';
		    				$response['form_extra_image_error'] = $this->translator->trans("admin.flyer.imagevalidation.width_height");
		    				return new JsonResponse($response);
		    				break;
		    			default:
		    				$this->get('session')->getFlashBag()->add('success_message', $this->translator->trans('admin.msg.flyer_save_msg'));
		    				$response['Message'] = "success";
		    				$response['locale'] = $locale;
		    				return new JsonResponse($response);
		    				break;
		    		}

				}
				else{
					return new JsonResponse ( $this->prepareFormJsonError ($form));
				}
	    	}
	    	else
	    	{
				if ($form->isValid()){
					
					$flyerscategoryId	=	$form->get('flyers_category_id')->getData();
					$flyerscategoryId1	=	$form->getData();
					$case=$this->flyerManager->saveEditFlyer($flyer, $form, $countryId, $cultureId, $flyerscategoryId,$titleOld,$flyrRootDir,$flyerUploadedPath,$flyerUploadedPdf, $extraFlyerUploadedPdf, $extraFlyerUploadedPath);
					
					switch ($case) {
						/*case 'SIZE':
						 $response['form_status'] = 'error';
						$response['form_image_error'] = $this->translator->trans("admin.flyer.imagevalidation.size");
						return new JsonResponse($response);
						break;
						break; */
						case 'HEIGHT':
							$response['form_status'] = 'error';
							$response['form_image_error'] = $this->translator->trans("admin.flyer.imagevalidation.width_height");
							return new JsonResponse($response);
							break;
						case 'EXTRA_HEIGHT':
							$response['form_status'] = 'error';
							$response['form_extra_image_error'] = $this->translator->trans("admin.flyer.imagevalidation.width_height");
							return new JsonResponse($response);
							break;
						case 'WIDTH':
							$response['form_status'] = 'error';
							$response['form_image_error'] = $this->translator->trans("admin.flyer.imagevalidation.width_height");
							return new JsonResponse($response);
							break;
						case 'EXTRA_WIDTH':
							$response['form_status'] = 'error';
							$response['form_extra_image_error'] = $this->translator->trans("admin.flyer.imagevalidation.width_height");
							return new JsonResponse($response);
							break;
						default:
							$this->get('session')->getFlashBag()->add('success_message', $this->translator->trans('admin.msg.flyer_updt_msg'));
							$response['Message'] = "success";
							$response['locale'] = $locale;
							return new JsonResponse($response);
							break;
					}
				}else{
					return new JsonResponse ( $this->prepareFormJsonError ($form) );
				}
	    	}

	    }

		return array('data'=>'yes','form'=>$form->createView(),'id'=>$id, 'mod'=>$mod, 'flyerThumb' => $flyerThumb, 'flyerUploadedPath' => $flyerUploadedPath, 'extraFlyerUploadedPath' => $extraFlyerUploadedPath, 'flyerUploadedPdf' => $flyerUploadedPdf, 'extraFlyerUploadedPdf' => $extraFlyerUploadedPdf );
	}

	/**
	 *
	 * @author Employee Id: 4571
	 *
	 * Description : List action
	 *
	 * @param  : null
	 *
	 * @return Array
	 *
	 * @throws null
	 *
	 * @Route("/admin/{_locale}/flyer/list", name="office_brain_flyerbundle_flyeradmin_listflyer")
	 *
	 * @Template("OfficeBrainFlyerBundle:FlyerAdmin:listFlyer.html.twig")
	 *
	 **/
	public function listFlyerAction()
	{
		$this->initAction();

		$page  = $this->request->get('page', '1');
		$recordsPerPage =  $this->flyerConfigurationField['no_of_record_per_page'];
		$this->parentcategories = $this->flyerManager->getParentCategories();
		$subIds=$this->parentcategories[0]['subids'];
		$arr_subids=explode(',',$subIds);
		$this->subcategories = $this->flyerManager->getSubCategories($subIds);
		$this->responseArray = $this->flyerManager->getFlyerList($page,$recordsPerPage,$arr_subids[0]);
		$this->responseArray['subcategories']=$this->subcategories;
		$this->responseArray['update_subcategory_tab_content']=1;
		$this->responseArray['parentcategories'] = $this->parentcategories;
		$this->responseArray['page'] = $page;
		$this->responseArray['records_per_page'] = $recordsPerPage;
		$this->responseArray['flyerAccessField'] = $this->flyerAccessField;
		$this->responseArray['flyerConfigurationField'] = $this->flyerConfigurationField;

		return $this->responseArray;
	}


	/**
	 *
	 * @author Employee Id: 4571
	 *
	 * Description : List Flyer Ajax action
	 *
	 * @param  : null
	 *
	 * @return Array
	 *
	 * @throws null
	 *
	 * @Route("/admin/{_locale}/sub-id/list-ajax", name="office_brain_flyerbundle_flyeradmin_listflyerajax")
	 *
	 * @Template("OfficeBrainFlyerBundle:FlyerAdmin:tabFlyerListContents.html.twig")
	 *
	 **/
	public function listFlyerAjaxAction()
	{
		$this->initAction();
		$page  = $this->request->get('page', '1');
		$subIds  = $this->request->get('subids', '0');
		
		$arrSubIds=explode(',',$subIds);
		$this->subcategories = $this->flyerManager->getSubCategories($subIds);
		$recordsPerPage =  $this->flyerConfigurationField['no_of_record_per_page'];
		$this->responseArray = $this->flyerManager->getFlyerListAjax($page,$recordsPerPage,$arrSubIds[0]);
		$this->responseArray['page'] = $page;
		$this->responseArray['subcategories']=$this->subcategories;
		$this->responseArray['update_subcategory_tab_content']=1;
		$this->responseArray['records_per_page'] = $recordsPerPage;
		$this->responseArray['flyerAccessField'] = $this->flyerAccessField;
		$this->responseArray['flyerConfigurationField'] = $this->flyerConfigurationField;
		return $this->responseArray;
	}
	
	/**
	 *
	 * @author Employee Id: 4571
	 *
	 * Description : List Flyer Ajax action
	 *
	 * @param  : null
	 *
	 * @return Array
	 *
	 * @throws null
	 *
	 * @Route("/admin/{_locale}/flyer/list-ajax", name="office_brain_flyerbundle_flyeradmin_listflyerajaxBySubid")
	 *
	 * @Template("OfficeBrainFlyerBundle:FlyerAdmin:tabFlyerListContents.html.twig")
	 *
	 **/
	public function listFlyerBySubidAjaxAction()
	{
		$this->initAction();
		$page  = $this->request->get('page', '1');
		$subIds  = $this->request->get('subids', '0');
		$recordsPerPage =  $this->flyerConfigurationField['no_of_record_per_page'];
		$this->responseArray = $this->flyerManager->getFlyerListAjax($page,$recordsPerPage,$subIds);
		$this->responseArray['page'] = $page;
		$this->responseArray['records_per_page'] = $recordsPerPage;
		$this->responseArray['flyerAccessField'] = $this->flyerAccessField;
		$this->responseArray['flyerConfigurationField'] = $this->flyerConfigurationField;
		return $this->responseArray;
	}

	/**
	 *
	 * @author Employee Id: 4571
	 *
	 * Description : Search Flyer
	 *
	 * @param  : null
	 *
	 * @return Response
	 *
	 * @throws null
	 *
	 * @Route("/admin/{_locale}/flyer/search", name="office_brain_flyerbundle_flyeradmin_searchflyerajax")
	 *
	 * @Template("OfficeBrainFlyerBundle:FlyerAdmin:tabFlyerListContents.html.twig")
	 *
	 **/
	public function searchFlyerAjaxAction()
	{
		$this->initAction();
		$page  = $this->request->get('page', '1');
		$subIds  = $this->request->get('subids', '0');
		$recordsPerPage =  $this->flyerConfigurationField['no_of_record_per_page'];
		$this->responseArray = $this->flyerManager->getFlyerListAjax($page,$recordsPerPage,$subIds);
		$this->responseArray['page'] = $page;
		$this->responseArray['records_per_page'] = $recordsPerPage;
		$this->responseArray['flyerAccessField'] = $this->flyerAccessField;
		$this->responseArray['flyerConfigurationField'] = $this->flyerConfigurationField;

		return $this->responseArray;
	}
	/**
	 *
	 * @author Employee Id: 5428
	 *
	 * Description : save position
	 *
	 * @param  : null
	 *
	 * @return Response
	 *
	 * @throws null
	 *
	 * @Route("/admin/{_locale}/flyer/save-position", name="office_brain_flyerbundle_flyeradmin_savepositionAjax")
	 *
	 *
	 *
	 **/
	public function savePositionFlyerAjaxAction()
	{
		$this->initAction();
		$savePosArray  = $this->request->request->all();
		$status = $this->flyerManager->saveFlyerPosition($savePosArray);
		if($status)
		{
			return new JsonResponse (array('status'=>'success','massage'=>$this->translator->trans('admin.msg.flyer_position_save_successfully')));
		}
		else 
		{
			return new JsonResponse (array('status'=>'Error','massage'=>$this->translator->trans('admin.msg.flyer_error_text')));
		}
	}

}