<?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\CoreBundle\Library\LiquenImg;
use OfficeBrain\Bundle\FlyerBundle\Entity\Flyer;
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;

/**
 * This controller implemented to provide Front Flyer functionality
 *
 * @author Employee Id: 4493
 *
 */

class FlyerController extends Controller
{
	protected $request;
	private $emailService;
	protected $uploadHandler;
	protected $emailLibrary;
	protected $filePath;
	protected $flyerImageURL;
	protected $flyerImagesPath;
	protected $manager;
	protected $session;
	protected $userId;
	protected $is_login;
	protected $distId;
	protected $projectSetting;
	protected $responseArray;
	protected $userManager;
	protected $productAdminManager;
	protected $flyerAttachmentPath;
	protected $flyerBasePath;
	protected $flyerAccessField;
	protected $flyerConfigurationField;

	/**
	 * @author Employee Id: 4493
	 *
	 * Description: To set member variables default value
	 *
	 * @return NULL
	 *
	 */
	public function __construct()
	{
		$this->request = null;
		$this->uploadHandler = null;
		$this->emailLibrary = null;
		$this->filePath = null;
		$this->flyerImageURL = null;
		$this->flyerImagesPath = null;
		$this->manager = null;
		$this->session = null;
		$this->is_login = null;
		$this->distId = null;
		$this->projectSetting = null;
		$this->responseArray = null;
		$this->userManager = null;
		$this->productAdminManager = null;
		$this->emailService = null;
		$this->flyerAttachmentPath = null;
		$this->flyerBasePath= null;
		$this->flyerAccessField = null;
		$this->flyerConfigurationField = null;
		$this->searchParameterArray = array();
		$this->searchKeyWordsArray = array();

	}

	/**
	 * @author Employee Id: 4493
	 *
	 * Description: To unset member variables
	 *
	 * @return NULL
	 *
	 */
	public function __destruct()
	{
		unset ($this->request );
		unset($this->uploadHandler );
		unset($this->emailLibrary );
		unset($this->filePath );
		unset($this->flyerImageURL );
		unset($this->flyerImagesPath );
		unset($this->manager);
		unset($this->session);
		unset($this->is_login);
		unset($this->distId);
		unset($this->projectSetting);
		unset($this->responseArray);
		unset($this->userManager);
		unset($this->productAdminManager);
		unset($this->emailService);
		unset($this->flyerAttachmentPath);
		unset($this->flyerBasePath);
		unset($this->flyerAccessField);
		unset($this->flyerConfigurationField);
		unset($this->searchParameterArray);
		unset($this->searchKeyWordsArray);

	}

	/**
	 * @author Employee Id: 4493
	 *
	 * Description: Create various objects required action in this class
	 *
	 * @return NULL
	 *
	 */
	public function initAction()
	 {

		$this->request = $this->getRequest();
		$this->translator = $this->get('translator');
		$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->session = $this->request->getSession();
		$this->distId = $this->session->get('distributorId', 0);
		$this->manager = $this->get('office_brain_flyer_manager');
		$this->projectSetting = $this->request->get('project_setting');
		$this->productAdminManager = $this->get('office_brain_product_admin_manager');
		$this->responseArray = array();
		$this->emailService = $this->get('office_brain_email_service');
		$this->userManager = $this->get('office_brain_user_manager');
		$this->flyerAttachmentPath =  $this->container->getParameter('flyer_attachment_url');

		$this->flyerBasePath =  $this->container->getParameter('flyer_base_path');
		if ($this->container->get('security.context')->isGranted('ROLE_ANONYMOUS') && $this->getUser() != null) {
			$this->userId = $this->getUser()->getId();
			$this->is_login = true;
		} else {
			$this->userId = 0;   //14
			$this->is_login = false;
		}

		$this->flyerAccessField= $this->projectSetting['access_rule']['promo_discount']['option']['flyer'];
		$this->flyerConfigurationField=$this->projectSetting['configuration_rule']['promo_discount']['option']['flyer'];
		$this->configurationRule = $this->projectSetting['configuration_rule']['transaction']['quote'];
		$this->page = $this->request->get('page', '1');
		$this->recordsPerPage = $this->request->get('records_per_page', $this->configurationRule['inline_view']['option']['no_of_product']);
	}


	/**
	 *
	 * @author Employee Id: 5430
	 *
	 * Description : Flyer List action for front
	 *
	 * @param  : null
	 *
	 * @return Array
	 *
	 * @throws null
	 *
	 * @Route("/{_locale}/flyer/{slug}/{display_image}/{page}", name="office_brain_flyerbundle_flyer_supplierflyer",
     * options={"expose"=true},
     * requirements={"page"="\d+"},
     * defaults={"records_per_page"=50,"page"=1,"display_image"="default"})
     *
     * @Method("GET")
     * @Template("OfficeBrainFlyerBundle:Flyer:flyer.html.twig")
	 *
	 **/
	public function supplierFlyerAction()
	{
		$this->initAction();
		$currentCategory =  $this->request->get('slug', null);
	
		if($currentCategory == 'featured-self-promotions'){
			if($this->userId==0){
				if ($this->request->isXmlHttpRequest()) {
					$this->responseArray['error_type'] = 'loginError';
					$this->responseArray['page_url'] = $this->generateUrl('office_brain_userbundle_login_login');
					return new JsonResponse($this->responseArray);
				}else{
					$this->get('session')->set('_security.main.target_path', $this->generateUrl($this->request->get('_route'),array('slug'=>$this->request->get('slug')),array('display_image'=>$this->request->get('display_image')),array('page'=>$this->request->get('page'))));
					return $this->redirect($this->generateUrl('office_brain_userbundle_login_login'));
				}
			}else{
				$param = $this->request->get('_route_params');
				$this->responseArray['records_per_page'] = $param['records_per_page'];
				$this->responseArray['page'] = $this->page;
				$this->keywords = $this->request->get('title', null);
				$this->slug = $currentCategory;
				$this->responseArray['parent_title'] = $this->manager->getFlyertitleBySlug($this->slug);
				$this->responseArray['parent_slug'] = $this->slug;
				$this->responseArray['content'] = $this->manager->getFlyerListBySlug($this->slug,$this->page,$this->recordsPerPage,$this->keywords);
				$this->responseArray['flyerAttachmentPath'] =$this->flyerAttachmentPath;
			}
		}else{  
			$param = $this->request->get('_route_params');
			$this->responseArray['records_per_page'] = $param['records_per_page'];
			$this->responseArray['page'] = $this->page;
			$this->keywords = $this->request->get('title', null);
			$this->slug = $currentCategory;
			$this->responseArray['parent_title'] = $this->manager->getFlyertitleBySlug($this->slug);
			$this->responseArray['parent_slug'] = $this->slug;
			$this->responseArray['content'] = $this->manager->getFlyerListBySlug($this->slug,$this->page,$this->recordsPerPage,$this->keywords);
			$this->responseArray['flyerAttachmentPath'] =$this->flyerAttachmentPath;
		}
		
		$this->responseArray['displayImage'] = $this->request->get('display_image');
		
		if ($this->request->isXmlHttpRequest() && !count($this->responseArray['content']->getItems())) {
			return new JsonResponse(array('status'=>'error', 'error_code'=>'END_OF_PAGINATION'));
		}
		
		return $this->responseArray;
	}
	/**
	 * @author Employee Id: 5430
	 *
	 * Description : Ajax base flyer page search
	 *
	 * @Route("/{_locale}/flyer/{slug}/{display_image}/{page}", name="office_brain_flyerbundle_flyer_flyerpagesearch",
	 * requirements={"page"="\d+"},
	 * options={"expose"=true},
	 * defaults={"records_per_page"=12,"page"=1,"display_image"="default"})
	 *
	 * @Method("POST")
	 * @Template("OfficeBrainFlyerBundle:Flyer:flyerpageListAjax.html.twig")
	 */
	public function flyerPageSearchAction()
	{
		$this->initAction();
		//$this->responseArray['records_per_page'] = $this->recordsPerPage;
		$param = $this->request->get('_route_params');
		$records_per_page = $param['records_per_page'];
		$this->responseArray['page'] = $this->page;
		$this->keywords = $this->request->get('title', null);
		$this->slug = $this->request->get('slug', null);
		$this->responseArray['content'] = $this->manager->getFlyerListBySlug($this->slug,$this->page,$records_per_page,$this->keywords);
		$this->responseArray['flyerAttachmentPath'] =$this->flyerAttachmentPath;
		return $this->responseArray;
	}
	/**
	 * @Route("/flyer/social-share",name="officebrain_flyer_bundle_socail_share")
	 * @Template("OfficeBrainFlyerBundle:Flyer:flyerContentShare.html.twig")
	 */
	public function flyerSocialShareAction()
	{
		return array();
	}


	/**
	 *
	 * @author Employee Id: 4571
	 *
	 * Description : Flyer List action for front
	 *
	 * @param  : null
	 *
	 * @return Array
	 *
	 * @throws null
	 *
	 * @Route("/{_locale}/flyer-list-ajax/{page}", name="office_brain_flyerbundle_flyer_supplierflyerajax",
	 * requirements={"records_per_page"="12|24|48|96|996", "page"="\d+"},
	 * defaults={"records_per_page"=12,"page"=1})
	 * @Template("OfficeBrainFlyerBundle:Flyer:flyerContent.html.twig")
	 *
	 **/
	public function supplierFlyerAjaxAction()
	{
		// officebrain_flyer_bundle_distributorflyer
		$this->initAction();

		$this->responseArray = $this->manager->getFrontFlyerList();
		$userInfo = $this->userManager->getAllSuppliers();

		if($userInfo!="" && sizeof($userInfo)>0){
			$tempArr = array();
			$id= '';
			foreach ($userInfo as $vals){
				$id = $vals['id'];
				$tempArr[$id] = $vals['firstName']." ".$vals['lastName'];
			}

			$this->responseArray['supplierData'] = $tempArr; //get all supplier
		}

		$this->responseArray['flyerAccessField']  = $this->flyerAccessField;
		$this->responseArray['flyerConfigurationField'] =  $this->flyerConfigurationField;
		return $this->responseArray;
	}

	/**
	 *
	 * @author Employee Id: 4571
	 *
	 * Description : Download Flyer
	 *
	 * @param  : $id
	 *
	 * @return Array
	 *
	 * @throws null
	 *
	 * @Route("/{_locale}/download-supplier-flyer/{id}", name="office_brain_flyerbundle_flyer_downloadsupplierflyer")
	 *
	 */
	public function downloadSupplierFlyerAction($id)
	{ 	// officebrain_download_supplierflyer

		$this->initAction();

		$flyer= $this->manager->findById($id);
		$this->manager->downloadFrontFlyer($flyer, $this->flyerBasePath);

		return array();
	}

	/**
	 *  @Route("/generate-supplier-flyer-pdf/{flyerUniqueId}",
	 * 	name="officebrain_generate_supplier_flyer_pdf",
	 *  options={"expose"=true})
	 */
	public function generateSupplierFlyerPDFAction($flyerUniqueId, $flyerType='image')
	{
		$this->initAction();

		//$flyerHTML = $em->getRepository('OfficeBrainFlyerBundle:Flyer')->fetchFlyerHTML($flyerUniqueId);
		$flyerHTML = $this->manager->fetchFlyer($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);

		if($flyerType == 'html') {
			return $returnHTML;
		} else {
			$fileExt = ($flyerType == 'image') ? 'jpg' : $flyerType;
			$fileName = 'Flyer-' . time() . '.' . $fileExt;

			$this->get('knp_snappy.' . $flyerType )->generateFromHtml(
					$returnHTML,
					$this->filePath . 'images/uploads/flyer-created/' .  '/' . $fileName
			);
		}

		return $this->filePath . 'images/uploads/flyer-created/' .  '/' . $fileName;

	}

	/**
	 * @author Employee Id: 4273
	 *
	 * Product Detail data.
	 *
	 * @param string product slug
	 *
	 * @return array
	 *
	 * @Route("/{_locale}/flyer/{product_id}/{product_slug}", name="office_brain_flyerbundle_flyer_createflyer"),
	 *
	 * @Method({"GET"})
	 *
	 * @Template("OfficeBrainFlyerBundle:Flyer:createFlyer.html.twig")
	 *
	 */
	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->manager->findCultureId();

		$this->responseArray = $this->manager->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;
		$this->responseArray['culture'] =  $cultureId;
		$this->responseArray['locale'] =  $locale;
		$this->responseArray['data'] =  $this->responseArray;
		return $this->responseArray;
		/* return $this->render('OfficeBrainFlyerBundle:Flyer:createFlyer.html.twig', array (
				 'data' => $this->responseArray, 'culture'=>$cultureId,'locale'=>$locale
		)); */


	}

	/**
	 * @author Employee Id: 4571
	 *
	 * @param string product slug
	 *
	 * @return array
	 *
	 * @Route("/{_locale}/email-flyer", name="office_brain_flyerbundle_flyer_emailflyer"),
	 *
	 * @Method({"GET"})
	 *
	 * @Template()
	 *
	 */
	public function emailFlyerAction()
	{
		$this->initAction();

		$uniqueId = $this->request->get('uniqueId');
		$id = $this->request->get('id'); // en_us

		return array('uniqueId' => $uniqueId,'id'=>$id);

	}


	/**
	 * @author 4273
	 *
	 * Send the created flyer as a attachment in the email
	 *
	 * @param string initialVal: to fetch data by this value
	 *
	 * @return array of fetched data
	 * @Route("/{_locale}/send-flyer-via-email", name="office_brain_flyerbundle_flyer_sendflyerviaemail")
	 *
	 */
	public function sendFlyerViaEmailAction() // officebrain_send_flyer_via_email
	{
		$this->initAction();

		$name = $this->request->get('name');
		$email = $this->request->get('email'); // from email ..
		$emailSubject = $this->request->get('subject');
		$to = $this->request->get('to', '');
		$locale = $this->request->get('_locale'); // en_us
		$message = $this->request->get('message');
		$id = $this->request->get('id');

		$this->response['name']=$name;
		$this->response['message']=$message;

		$response = $this->render('OfficeBrainFlyerBundle:Flyer:sendFlyer.html.twig', $this->response);

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

		$status = $this->manager->flyerSendMail($locale, $id, $templateParameterArray, $this->emailService, $to, $email, $emailSubject, $this->flyerAttachmentPath);

		//$this->emailService->sendMail($eventKey, $to, $templateParameterArray, $cultureId, $email, $emailSubject, $flyerAttachment, $cc, $bcc); // new
		if($status) {
		$response = array("msg" => 'Email Sent', "status" => 'success');
		}else{
		$response = array("msg" => 'Email Not Sent', "status" => 'error');
		}

		return new Response(json_encode($response));

	}

}