<?php

namespace OfficeBrain\Bundle\CouponBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Response;

/**
 * @author OfficeBrain 4835 <info@officebrain.com>
 * Description: CURD for Coupon Management
 * generate csv of coupons
 * import coupons in database
 * make copy of coupon for another country
 *
 * @Route("/admin/{_locale}/coupon")
 */
class CouponAdminController extends Controller
{
    private $request;
    private $translator;
    private $session;
    private $couponManager;
    private $prodctCategory;
    private $language;
    private $country;
    private $localization;
    private $catList;
    private $projectSetting;
    private $discountType;
    private $responseArray;
    private $isAjaxRequest;

    public function __construct()
    {
        $this->request = null;
        $this->translator = null;
        $this->session = null;
        $this->couponManager = null;
        $this->prodctCategory = null;
        $this->language = null;
        $this->country = null;
        $this->localization = null;
        $this->catList = null;
        $this->projectSetting = null;
        $this->discountType = null;
        $this->responseArray = array();
        $this->isAjaxRequest = null;
    
    }

    public function __destruct()
    {
        unset($this->request);
        unset($this->translator);
        unset($this->session);
        unset($this->couponManager);
        unset($this->prodctCategory);
        unset($this->language);
        unset($this->country);
        unset($this->localization);
        unset($this->catList);
        unset($this->projectSetting);
        unset($this->discountType);
        unset($this->responseArray);
        unset($this->isAjaxRequest);
    }

    public function initAction()
    {
        $this->request = $this->getRequest();
        $this->translator = $this->get('translator');
        $this->session = $this->get('session');
        $this->couponManager = $this->container->get('office_brain_couponManager');
        $this->prodctCategory = $this->container->get('officebrain_category_api_manager');
        $this->language = $this->container->getParameter('language');
        $this->country = $this->container->getParameter('country');
        $this->localization = $this->container->getParameter('localization_to_fetch');
        $this->catList = $this->prodctCategory->getList(array($this->localization[0]));
        $this->projectSetting = $this->request->get('project_setting');
        $this->discountType = $this->container->getParameter('discount_type');
        $this->responseArray = array();
        $this->isAjaxRequest = $this->request->isXmlHttpRequest();
    }

    /**
     * @author Employee Id: 4835
     * Description :render form for add.
     *
     * @param null
     *
     * @Route("/add", name="office_brain_couponbundle_couponadmin_add")
     *
     * @Method("GET")
     *
     * @return data
     *
     * @throws Exception : Null
     *
     * @Template("OfficeBrainCouponBundle:Admin:add.html.twig")
     * */
    public function addAction()
    {
        $this->initAction();
        $form = $this->couponManager->getForm();

        $this->responseArray['form'] = $form->createView();
        $this->responseArray['id'] = 0;
        $this->responseArray['mode'] = 'add';
        $this->responseArray['selcatlist'] = '';
        $this->responseArray['catList'] = $this->catList[$this->localization[0]];
        $this->responseArray['errorData'] = array();
        
        unset($form); 
        
        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4835
     * Description: preocess form for add.
     *
     * @param null
     *
     * @Route("/add",name="office_brain_couponbundle_couponadmin_processadd")
     *
     * @Method("POST")
     *
     * @return data
     *
     * @throws Exception : Null
     *
     * @Template("OfficeBrainCouponBundle:Admin:add.html.twig")
     */
    public function processAddAction()
    {
        $this->initAction();

        $couponmode = $this->request->get('couponmode');
        $errorData = array();
        $importError=array();
        if ($couponmode == 'smartimport') {
            $importError = $this->processimport();
            
            $errorData = array_merge($errorData, $importError);
        }

        $this->responseArray = $this->couponManager->processAddForm($errorData);

        if (!is_array($this->responseArray) && $this->responseArray == 'success') {
            $this->container->get('session')->getFlashBag()->add('success_message', $this->translator->trans('admin.msg.sucess'));

            return $this->redirect($this->generateUrl('office_brain_couponbundle_couponadmin_tab'));
        }
        
        unset($couponmode);
        unset($errorData);
        unset($importError);
        
        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4835
     * Description: get dynamic couponcode through ajax call
     *
     * @param null
     *
     * @Route("/coupongenerateajax",name="office_brain_couponbundle_couponadmin_coupongenerateajax")
     *
     * @Method("POST")
     *
     * @return data
     *
     * @throws Exception : Null
     *
     * @Template("OfficeBrainCouponBundle:Admin:add.html.twig")
     */
    public function coupongenerateAjaxAction()
    {
        $this->initAction();
        
        if ($this->isAjaxRequest) {
            $form = $this->couponManager->getForm();
            $form->handleRequest($this->request);
            if ($form->getData()->getIsAutogenerate() == 1) {
                $prfix = $form->getData()->getcouponPrifix();
                $couponcode = $this->couponManager->generateCoupon($prfix);
                return new Response($couponcode);
            }
        }
    }

    /**
     * @author Employee Id: 4835
     * Description: render form for edit.
     *
     * @param : id for get all details for individual record.
     *
     * @Route("/edit/{id}", name="office_brain_couponbundle_couponadmin_edit")
     *
     * @Method("GET")
     *
     * @return data
     *
     * @throws Exception : Null
     *
     * @Template("OfficeBrainCouponBundle:Admin:edit.html.twig")
     */
    public function editAction($id)
    {
        $this->initAction();

        return $this->responseArray = $this->couponManager->generateEditForm($id);
    }

    /**
     * @author Employee Id: 4835
     * Description: process for edit.
     *
     * @param : id for get all details for individual record.
     *
     * @Route("/editcoupon/{id}", name="office_brain_couponbundle_couponadmin_processedit")
     *
     * @Method("POST")
     *
     * @return data
     *
     * @throws Exception : Null
     *
     * @Template("OfficeBrainCouponBundle:Admin:edit.html.twig")
     */
    public function processEditAction($id)
    {
        $this->initAction();
        $this->responseArray = $this->couponManager->processEditForm($id);

        if (!is_array($this->responseArray)) {
            $this->container->get('session')->getFlashBag()->add('success_message', $this->translator->trans('admin.msg.update'));

            return $this->redirect($this->generateUrl('office_brain_couponbundle_couponadmin_tab'));
        }

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4835
     * Description: Listing Of Coupons
     *
     * @param 1: page for pagination.
     * @param 2: country for filter records.
     * @param 3: language for filter records.
     *
     * @Route("/list/{country}/{page}",
     * name="office_brain_couponbundle_couponadmin_tab",
     * requirements={"records_per_page"="2|4|8|16|996","page"="\d+"},
     * defaults={"records_per_page"=8,"page"=1,"language"="en","country"="us"})
     *
     * @Method("GET")
     *
     * @return data
     *
     * @throws Exception : Null
     *
     * @Template("OfficeBrainCouponBundle:Admin:tab.html.twig")
     */
    public function tabAction()
    {
        $this->initAction();

        $this->responseArray = $this->couponManager->listCoupon($this->discountType);

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4835
     * Description: Ajax call for getting dynamic lists.
     *
     * @param 1: page for pagination.
     * @param 2: country for filter records.
     * @param 3: language for filter records.
     *
     * @Route("/listajax/{page}",
     * name="office_brain_couponbundle_couponadmin_listajax",
     * requirements={"records_per_page"="2|4|8|16|996","page"="\d+"},
     * defaults={"records_per_page"=8,"page"=1},options={"expose"=true})
     *
     * @Method("GET")
     *
     * @return data
     *
     * @throws Exception : Null
     *
     * @Template("OfficeBrainCouponBundle:Admin:list.html.twig")
     */
    public function listAjaxAction()
    {
        $this->initAction();

        $this->responseArray = $this->couponManager->listCoupon($this->discountType);

        if ($this->isAjaxRequest) {
            $var_jason = $this->get('twig')->render('OfficeBrainCouponBundle:Admin:list.html.twig', $this->responseArray);

            return new JsonResponse($var_jason);
        } else {
            return $this->render('OfficeBrainCouponBundle:AdmgetFormin:list.html.twig', $this->responseArray);
        }
    }

    /**
     * @author Employee Id: 4835
     * Description: Remove coupon from list(Soft Remove)
     *
     * @param : id for remove  individual record.
     *
     * @Route("/remove/", name="office_brain_couponbundle_couponadmin_remove")
     *
     * @return data
     *
     * @throws Exception : Null
     *
     * @Template()
     */
    public function removeAction()
    {
        $this->initAction();
		$id=$this->request->get('id');
        $deleteCoupon=$this->couponManager->removeCoupon($id);
        
		if($deleteCoupon == true)
		{
			$this->responseArray['status'] = 'success';
    		$this->responseArray['close_modal'] = true;
    		$this->responseArray['success_message'] = $this->get('translator')->trans('admin.msg.delete');
		}
		else
		{
			$this->responseArray['status'] = 'Error';
    		$this->responseArray['close_modal'] = true;
    		$this->responseArray['error_message'] = $this->get('translator')->trans('currency_conversion.delete_error');
		}
		return new JsonResponse($this->responseArray);
    }

    /**
     * @author Employee Id: 4835
     * Description: ajax call for get product array  dynamically from solr
     *
     * @param : null

     * @Route("/productajax",name="office_brain_couponbundle_couponadmin_productajax",options={"expose"=true})
     *
     * @Method("POST")
     *
     * @return json
     *
     * @throws Exception : Null
     *
     * @Template()
     */
    public function productajaxAction()
    {
        $this->initAction();
        $searchparam = $_POST['data']['q'];

        if ($this->isAjaxRequest) {
            $productdata = $this->couponManager->getProduct($searchparam);
            $results = array();
            if (count($productdata) > 0) {
                foreach ($productdata as $key) {
                    $results[] = array('id' => $key ['product_id'].'|'.$key ['sku'], 'text' => $key ['sku'].' | '.$key ['title']);
                }
            }

            return new JsonResponse(array('q' => $searchparam, 'results' => $results));
        }
    }

    /**
     * @author Employee Id: 4835
     * Description: copy coupons for selected countries
     *
     * @param : null
     *
     * @Route("/copycoupon",name="office_brain_couponbundle_couponadmin_copycoupon")
     *
     * @Method("POST")
     *
     * @return data
     *
     * @throws Exception : Null
     *
     * @Template()
     */
    public function copyCouponAction()
    {
        $this->initAction();

        $this->responseArray = $this->couponManager->copycoupons();
        if ($this->responseArray == 'error') {
            $this->get('session')->getFlashBag()->add('error_message', $this->translator->trans('admin.valid.country'));
        } else {
            $this->get('session')->getFlashBag()->add('success_message', $this->translator->trans('admin.msg.copied'));
        }

        return $this->redirect($this->generateUrl('office_brain_couponbundle_couponadmin_tab'));
    }

    /**
     *@author Employee Id: 4835
     *Description: show details of coupon
     *
     *@Route("/view/{id}",name="office_brain_couponbundle_coupon_view")
     *
     *@Method("GET")
     *
     *@return data
     *
     *@throws Exception : Null
     *
     *@Template("OfficeBrainCouponBundle:Admin:viewCoupon.html.twig")
     */
    public function viewAction($id)
    {
        $this->initAction();

        $couponObj = $this->couponManager->viewCouoponDetails($id);
        $this->responseArray['couponObj']=$couponObj;
        return $this->responseArray;
    }

	/**
     *@author Employee Id: 4835
     *Description: copy of coupon
     *
     *@Route("/copy",name="office_brain_couponbundle_coupon_copy")
     *
     *@Method("GET")
     *
     *@return data
     *
     *@throws Exception : Null
     *
     *@Template("OfficeBrainCouponBundle:Admin:makeCopyModal.html.twig")
     */
    public function makeCopyModalAction()
    {
        $this->initAction();
		$couponId = $this->request->get('id');
        return array('coupon_id'=>$couponId);
    }


    /**
     * @author Employee Id: 4835
     * Description : List Product Category for dropdown.
     *
     * @param 1 : String country
     *
     * @return data
     *
     * @throws Exception : Null
     *
     * @Route("/getproductcategorylist/{country_id}",
     * name="office_brain_couponbundle_coupon_catagorylist")
     *
     * @Method("GET")
     *
     * @Template("OfficeBrainCouponBundle:Admin:productCategoryList.html.twig")
     */
    public function getproductcategoryListAction($country_id)
    {
        $this->initAction();
        $this->responseArray = array();
        $localization = $this->couponManager->getlocaleFromCountryId($country_id);
        $eventCategoryList = $this->prodctCategory->getList($localization);
        $this->responseArray['selcatlist'] = array();
        $this->responseArray['catList'] = $eventCategoryList[$localization[0]];
        
        unset($localization);
        unset($eventCategoryList);
        
        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4835
     * Description : Serve a file by forcing the download
     *
     * @param 1 : null
     *
     * @return data
     *
     * @throws Exception : Null
     *
     * @Route("/download", name="office_brain_couponbundle_coupon_download")
     *
     * @Template()
     */
    public function downloadFileAction()
    {
        $filename = 'sample.csv';
        $basePath = $this->container->get('kernel')->locateResource('@OfficeBrainCouponBundle/Resources/public');
        $filePath = $basePath.'/'.$filename;

        $response = new Response();
        $response->headers->set('Content-Type', 'text/csv');
        $response->headers->set('Content-Description', 'Submissions Export');
        $response->headers->set('Content-Disposition', 'filename='.$filename);
        $response->headers->set('Content-Transfer-Encoding', 'binary');
        $response->headers->set('Pragma', 'no-cache');
        $response->headers->set('Expires', '0');
        //$response->sendHeaders();
        $response->sendContent(readfile($filePath));
        
        unset($filename);
        unset($basePath);
        unset($filePath);
        
        return $response;
    }

    /**
     * @author Employee Id: 4835
     *
     * Description : csv import process
     *
     * @return data
     *
     * @throws Exception : Null
     *
     * @Template()
     */
    public function processimport()
    {
        $this->responseArray = $this->couponManager->processimport();

        if (isset($this->responseArray['sucessMsg']) and $this->responseArray['sucessMsg'] != '' and $this->responseArray['unsavedRaw'] == 0) {
            $this->get('session')->getFlashBag()->add('success_message', $this->responseArray['sucessMsg']);
        }

        return $this->responseArray;
    }
}
