<?php

namespace OfficeBrain\CustomBundle\ServiceGroupBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use OfficeBrain\CustomBundle\ServiceGroupBundle\Form\PromoCouponType;
use OfficeBrain\CustomBundle\ServiceGroupBundle\Form\CouponUsersType;

/**
 * @author OfficeBrain 5497 <info@officebrain.com>
 *
 * Description : Promo Coupon Admin controller class
 *
 * @Route("/admin/{_locale}/promo-coupon")
 **/
class PromoCouponAdminController extends Controller
{
    private $request;

    private $session;

    private $translator;

    private $projectSetting;

    private $recordsPerPage;

    private $promoCoupon;

    private $responseArray;

    public function __destruct()
    {
        unset($this->request);
        unset($this->session);
        unset($this->translator);
        unset($this->projectSetting);
        unset($this->promoCoupon);
        unset($this->responseArray);
    }

    public function initAction()
    {
        $this->request = $this->getRequest();
        $this->session = $this->request->getSession();
        $this->translator = $this->get('translator');
        $this->projectSetting = $this->request->get('project_setting');
        $this->promoCoupon = $this->get('office_brain_promo_coupon_manager');
        $this->user = $this->get('office_brain_custom_user_manager');
        $this->couponUsers = $this->get('office_brain_coupon_users_manager');
        $this->customUsers = $this->get('office_brain_custom_user_manager');
        $this->responseArray = array();
    }

    /**
     * @author Employee Id: 5497
     * Description : Get the list of coupon names
     *
     * @Route("/list/{instance_id}/{page}", name="office_brain_servicegroupbundle_promocouponadmin_list",
     * options={"expose"=true},
     * requirements={"instance_id"="\d+", "page"="\d+"},
     * defaults={"instance_id"="0", "page"=1})
     *
     * @Method("GET")
     * @Template("OfficeBrainCustomBundleServiceGroupBundle:PromoCoupon:promoCouponList.html.twig")
     *
     * @return array
     */
    public function promoCouponListAction()
    {
        $this->initAction();
        
        $this->responseArray = $this->promoCoupon->getPromoCouponList();

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 5497
     * Description : Get the list coupon names.
     *
     * @Route("/list-ajax/{page}", name="office_brain_servicegroupbundle_promocouponadmin_listajax",
     * options={"expose"=true},
     * requirements={ "page"="\d+"},
     * defaults={ "page"=1})
     *
     * @Method("POST")
     * @Template("OfficeBrainCustomBundleServiceGroupBundle:PromoCoupon:promoCouponListAjax.html.twig")
     *
     * @return array
     */
    public function promoCouponListAjaxAction()
    {
        $this->initAction();
        $this->responseArray = $this->promoCoupon->getPromoCouponList();

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 5497
     * Description : Display coupon name form.
     *
     * @param 1 : No paramater
     *
     * @return type : Form view.
     *
     * @throws Exception: Null
     *
     * @Route("/add/{instance_id}", name="office_brain_servicegroupbundle_promocouponadmin_add",
     * defaults={"instance_id"="0"},
     * requirements={"instance_id"="\d+"},
     * options={"expose"=true})
     * @Method("GET")
     * @Template("OfficeBrainCustomBundleServiceGroupBundle:PromoCoupon:add.html.twig")
     */
    public function couponNameAddAction()
    {
        $this->initAction();

        $this->responseArray['form'] = $this->createForm(new PromoCouponType())->createView();

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 5497
     * Description : Save coupon Name
     *
     * @param 1 : No paramater
     *
     * @return type : Form view.
     *
     * @throws Exception: Null
     *
     * @Route("/add/{instance_id}", name="office_brain_servicegroupbundle_promocouponadmin_processpageadd",
     * defaults={"instance_id"="0"},
     * requirements={"instance_id"="\d+"},
     * options={"expose"=true})
     *
     * @Method({"POST"})
     *
     * @Template("OfficeBrainCustomBundleServiceGroupBundle:PromoCoupon:add.html.twig")
     */
    public function processCouponNameAddAction()
    {
        $this->initAction();

        $form = $this->createForm(new PromoCouponType());

        $form->handleRequest($this->request);

        if ($form->isValid()) {
            $resultArray = $this->promoCoupon->setPromoCoupon($form->getData());
            
            if ($resultArray == 'ERROR_COUPON_NAME_ALREADY_EXISTS') {
                $this->responseArray['form'] = $form->createView();  // if error than render form and show error
                 $this->get('session')->getFlashBag()->add('error_message', $this->translator->trans('service_group.admin.action.page.coupon_duplicate_err'));
                                 
                return $this->responseArray;
            }
            
            $this->session->getFlashBag()->set('success_message', $this->translator->trans('service_group.admin.action.page.coupon_add_success'));
            
            if ($this->request->isXmlHttpRequest()) {
                return new JsonResponse(array('success' => 'success', 'page_url' => 'office_brain_servicegroupbundle_promocouponadmin_list'));
            } else {
                return $this->redirect($this->generateUrl('office_brain_servicegroupbundle_promocouponadmin_list'));
            }
        }

        $this->responseArray['form'] = $form->createView();

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 5497
     * Description : Display page form.
     *
     * @param 1 : No paramater
     *
     * @return type : Form view.
     *
     * @throws Exception: Null
     *
     * @Route("/edit/{id}/{instance_id}", name="office_brain_servicegroupbundle_promocouponadmin_edit",
     * defaults={"instance_id"="0"},
     * requirements={"id"="\d+", "instance_id"="\d+"},
     * options={"expose"=true})
     * @Method("GET")
     * @Template("OfficeBrainCustomBundleServiceGroupBundle:PromoCoupon:edit.html.twig")
     */
    public function pageEditAction()
    {
        $this->initAction();

        $this->responseArray['form'] = $this->createForm(new PromoCouponType(), $this->promoCoupon->getPromoCouponById())->createView();

        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 5497
     * Description : Display page form.
     *
     * @param 1 : No paramater
     *
     * @return type : Form view.
     *
     * @throws Exception: Null
     *
     * @Route("/edit/{id}/{instance_id}", name="office_brain_servicegroupbundle_promocouponadmin_processpageedit",
     * defaults={"instance_id"="0"},
     * requirements={"id"="\d+", "instance_id"="\d+"},
     * options={"expose"=true})
     * @Method("POST")
     * @Template("OfficeBrainCustomBundleServiceGroupBundle:PromoCoupon:edit.html.twig")
     */
    public function processPageEditAction()
    {
        $this->initAction();

        $form = $this->createForm(new PromoCouponType(), $this->promoCoupon->getPromoCouponById());

        $form->handleRequest($this->request);

        if ($form->isValid()) {
            $pageObj = $this->promoCoupon->updatePromoCoupon($form->getData());

            $this->session->getFlashBag()->set('success_message', $this->translator->trans('service_group.admin.action.page.coupon_update_success'));

            if ($this->request->isXmlHttpRequest()) {
                return new JsonResponse(array('success' => 'success', 'page_url' => 'office_brain_servicegroupbundle_promocouponadmin_list'));
            } else {
            	if ($this->request->get('iframe')) {
            		return $this->redirect($this->generateUrl('office_brain_servicegroupbundle_promocouponadmin_editbycouponname', array('coupon_name' => $pageObj->getCouponName(), 'instance_id' => $this->request->get('instance_id'), 'iframe' => $this->request->get('iframe'))));
            	}
            	
                return $this->redirect($this->generateUrl('office_brain_servicegroupbundle_promocouponadmin_list'));
            }
        }

        $this->responseArray['form'] = $form->createView();

        return $this->responseArray;
    }


    /**
     * @author Employee Id: 5497
     * Description : Delete coupon name.
     *
     * @Route("/delete/{id}/{instance_id}", name="office_brain_servicegroupbundle_promocouponadmin_delete",
     * defaults={"instance_id"="0"},
     * requirements={"id"="\d+", "instance_id"="\d+"},
     * options={"expose"=true})
     * @Method("GET")
     */
    public function promoCouponDeleteAction()
    {
        $this->initAction();

        $response = $this->promoCoupon->deletePromoCoupon();

        if ($response) {
            $this->session->getFlashBag()->add('success_message', $this->translator->trans('service_group.admin.action.page.coupon_delete_success'));
        } else {
            $this->get('session')->getFlashBag()->add('error_message', $this->translator->trans('service_group.admin.action.page.coupon_delete_error'));
        }

        if ($this->request->isXmlHttpRequest()) {
            return new JsonResponse(array('success' => 'success', 'page_url' => $this->generateUrl('office_brain_servicegroupbundle_promocouponadmin_list', array())));
        } else {
            return $this->redirect($this->generateUrl('office_brain_servicegroupbundle_promocouponadmin_list'));
        }
    }

    /**
     * @author Employee Id: 5497
     *
     * Description : Ajax base promo coupon search
     *
     * @Route("/search/{page}", name="office_brain_servicegroupbundle_promocouponadmin_search",
     * requirements={"page"="\d+"},
     * options={"expose"=true},
     * defaults={"page"=1})
     *
     * @Method("POST")
     * @Template("OfficeBrainCustomBundleServiceGroupBundle:PromoCoupon:promoCouponListAjax.html.twig")
     */
    public function promoCouponSearchAction()
    {
        $this->initAction();

        $this->responseArray = $this->promoCoupon->searchPromoCoupon();

        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 5497
     *
     * Description : Ajax base promo coupon change status
     *
     * @Route("/change-status/{instance_id}", name="office_brain_servicegroupbundle_promocouponadmin_change_status",
     * requirements={"instance_id"="\d+"},
     * options={"expose"=true},
     * defaults={"instance_id"="0"})
     *
     * @Method("POST")
     * @Template()
     */
    public function promoCouponChangeStatusAction()
    {
    	$this->initAction();
    	$id = $this->request->get('id');
    	
    	if ($id) {
    	$status = $this->promoCoupon->changeStatus();
    	if ($status) {
    		return new JsonResponse(array('status' => 'success', 'status_message' => $this->translator->trans('service_group.admin.coupon_status_message_success')));
    	}
    	}
    	return new JsonResponse(array('status' => 'fail', 'status_message' => $this->translator->trans('service_group.admin.coupon_status_message_fail')));
    }
    
    /**
     * @author Employee Id: 5497
     * Description : Display user mapping form.
     *
     * @param 1 : No paramater
     *
     * @return type : Form view.
     *
     * @throws Exception: Null
     *
     * @Route("/user-mapping/{id}/{page}", name="office_brain_servicegroupbundle_promocouponadmin_usermapping",
     * defaults={"page"=1},
     * requirements={"id"="\d+", "page"="\d+"},
     * options={"expose"=true})
     * @Method("GET")
     * @Template("OfficeBrainCustomBundleServiceGroupBundle:PromoCoupon:userMapping.html.twig")
     */
    public function userMappingAction()
    {
    	$this->initAction();
    	
    	$this->responseArray = $this->customUsers->getAllUserList();
    	
    	$this->responseArray = $this->user->getActiveUserList();
    	$this->responseArray['selected_users'] = $this->couponUsers->getSelectedUserList();
    	$this->responseArray['disable_users'] = $this->couponUsers->getUsedRedeemUserList();
    	$this->responseArray['coupon_details'] = $this->promoCoupon->getPromoCouponById();
    	$this->responseArray['form'] = $this->createForm(new CouponUsersType())->createView();
    	
    	return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 5497
     * Description : Display user mapping form.
     *
     * @param 1 : No paramater
     *
     * @return type : Form view.
     *
     * @throws Exception: Null
     *
     * @Route("/user-mapping/{id}/{page}", name="office_brain_servicegroupbundle_promocouponadmin_processusermapping",
     * defaults={"page"="1"},
     * requirements={"id"="\d+", "page"="\d+"},
     * options={"expose"=true})
     * @Method("POST")
     * @Template("OfficeBrainCustomBundleServiceGroupBundle:PromoCoupon:userMapping.html.twig")
     */
    public function processUserMappingAction()
    {
    	$this->initAction();
    	
    	$form = $this->createForm(new CouponUsersType());
    	$form->handleRequest($this->request);
    	
    	if ($form->isValid()) {
    		$this->couponUsers->setCouponUsers();
    
    		$this->session->getFlashBag()->set('success_message', $this->translator->trans('service_group.admin.action.page.user_mapped_success'));
    	}
    	
    	return $this->redirect($this->generateUrl('office_brain_servicegroupbundle_promocouponadmin_usermapping', array('id' => $this->request->get('id'))));
    }
    
    /**
     * @author Employee Id: 5497
     * Description : Display user mapping form
     *
     * @Route("/user-mapping-ajax/{id}/{page}", name="office_brain_servicegroupbundle_promocouponadmin_usermapping_listajax",
     * options={"expose"=true},
     * requirements={"id"="\d+", "page"="\d+"},
     * defaults={ "page"=1})
     *
     * @Method("POST")
     * @Template("OfficeBrainCustomBundleServiceGroupBundle:PromoCoupon:userMappingAjax.html.twig")
     *
     * @return array
     */
    public function userMappingAjaxAction()
    {
    	$this->initAction();
    	
    	$this->responseArray = $this->customUsers->getAllUserList();
    	
    	$this->responseArray = $this->user->getActiveUserList();
    	$this->responseArray['selected_users'] = $this->couponUsers->getSelectedUserList();
    	$this->responseArray['form'] = $this->createForm(new CouponUsersType())->createView();
    	
    	return $this->responseArray;
    }
}
