<?php

namespace OfficeBrain\Bundle\ServiceGroupBundle\Controller;

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 OfficeBrain\Bundle\CoreBundle\CustomeHandler as FormErrorManager;
use Symfony\Component\HttpFoundation\JsonResponse;
use OfficeBrain\Bundle\ServiceGroupBundle\Form\RewardRuleMappingType;
use OfficeBrain\Bundle\ServiceGroupBundle\Entity\ServiceRuleMappingMaster;

/**
 * @author OfficeBrain 4589 <info@officebrain.com>
 * Description : This class for base functionality related to reward rule mapping.
 *
 * @Route("/admin/{_locale}/reward-referral/rule-mapping",
 * defaults={"rule_service"="reward_rule_mapping"})
 */
class RewardRuleMappingAdminController extends Controller
{
    protected $viewTwigData;
    protected $request;
    protected $entityManager;
    protected $OBCommon;
    protected $session;
    protected $apiClient;
    protected $formErrorManager;
    protected $conditionAry;
    protected $cultureList;
    protected $isRuleMapping = false;
    protected $ruleKeyNameAry;
    protected $actionTypes;
    protected $actionLimitPer;
    protected $actionRuleTypes;
    protected $actionChargeTypes;
    protected $actionAmountTypes;
    protected $ruleService;
    protected $projectSetting;
    protected $responseArray;

    public function __construct()
    {
        $this->viewTwigData = null;
        $this->request = null;
        $this->entityManager = null;
        $this->OBCommon = null;
        $this->session = null;
        $this->apiClient = null;
        $this->formErrorManager = new FormErrorManager\JsonError();
        $this->conditionAry = null;
        $this->cultureList = null;
        $this->isRuleMapping = false;
        $this->ruleKeyNameAry = null;
        $this->actionTypes = null;
        $this->actionLimitPer = null;
        $this->actionRuleTypes = null;
        $this->actionChargeTypes = null;
        $this->actionAmountTypes = null;
        $this->ruleService = null;
        $this->projectSetting = null;
        $this->responseArray = null;
    }

    public function __destruct()
    {
        unset($this->viewTwigData);
        unset($this->request);
        unset($this->entityManager);
        unset($this->OBCommon);
        unset($this->session);
        unset($this->apiClient);
        unset($this->formErrorManager);
        unset($this->conditionAry);
        unset($this->cultureList);
        unset($this->isRuleMapping);
        unset($this->ruleKeyNameAry);
        unset($this->actionTypes);
        unset($this->actionLimitPer);
        unset($this->actionRuleTypes);
        unset($this->actionChargeTypes);
        unset($this->actionAmountTypes);
        unset($this->ruleService);
        unset($this->projectSetting);
        unset($this->responseArray);
    }

    public function initAction($isRuleMapping = false)
    {
        $this->request = $this->getRequest();
        $this->projectSetting = $this->request->get('project_setting');
        $this->isRuleMapping = true;

        $this->entityManager = $this->getDoctrine()->getManager();
        $this->OBCommon = $this->get('office_brain_core_manager');
        $this->session = $this->request->getSession();
        $this->apiClient = null;//$this->get('office_brain_api_client');
        $this->formErrorManager = new FormErrorManager\JsonError();

        $this->ruleService = $this->get('office_brain_service_group_rule_manager');
        $this->conditionAry = $this->ruleService->getConditionArray();
        $this->cultureList = $this->ruleService->getCultureList();

        $this->ruleKeyNameAry = $this->ruleService->setRuleKeyNameArray($this->isRuleMapping);

        $this->actionTypes = $this->ruleService->getActionTypes();
        $this->actionLimitPer = $this->ruleService->getActionLimitPer();
        $this->actionRuleTypes = $this->ruleService->getActionRuleTypes();
        $this->actionChargeTypes = $this->ruleService->getActionChargeTypes();
        $this->actionAmountTypes = $this->ruleService->getActionAmountTypes();
    }

    /**
     * @author Employee Id: 4589
     * Description : Render form for add Reward rule mapping
     *
     * @param 1 : Null
     *
     * @return : array data
     *
     * @throws Exception: Null
     *
     * @Route("/add", name="office_brain_servicegroupbundle_rewardrulemappingadmin_add")
     *
     * @Method({"GET"})
     * @Template("OfficeBrainServiceGroupBundle:RewardRuleMappingAdmin:add.html.twig")
     */
    public function addAction()
    {
        $this->initAction();

        $this->form = $this->createForm(new RewardRuleMappingType($this->container), new ServiceRuleMappingMaster());
        $this->responseArray['form'] = $this->form->createView();
        $this->responseArray['conditions'] = json_encode(array_values($this->conditionAry));

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4589
     * Description : validate form and add data
     *
     * @param 1 : Null
     *
     * @return : array data
     *
     * @throws Exception: Null
     *
     * @Route("/add", name="office_brain_servicegroupbundle_rewardrulemappingadmin_processaddajax")
     *
     * @Method({"POST"})
     * @Template("OfficeBrainServiceGroupBundle:RewardRuleMappingAdmin:add.html.twig")
     */
    public function processAddAjaxAction()
    {
        $this->initAction();

        $this->form = $this->createForm(new RewardRuleMappingType($this->container), new ServiceRuleMappingMaster());

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

        if (!is_array($rulesError = $this->ruleService->setRuleMapping($this->form))) {
            $this->get('session')->getFlashBag()->add('success_message', $this->get('translator')->trans('admin.service_group_management.rule_mapping.add_message_success'));

            return new JsonResponse(array(
                    'form_name' => $this->form->getName(),
                    'form_status' => 'success',
                    'page_url' => $this->generateUrl('office_brain_servicegroupbundle_rewardrulemappingadmin_list'),
            ));
        } else {
            return new JsonResponse($this->prepareFormJsonError($rulesError));
        }
    }

    /**
     * @author Employee Id: 4589
     * Description : Render form for edit Reward rule mapping
     *
     * @param 1 : int $id update record id
     *
     * @return : array data
     *
     * @throws Exception: Null
     *
     * @Route("/edit/{id}",  name="office_brain_servicegroupbundle_rewardrulemappingadmin_edit",
     * requirements={"id"="\d+"})
     *
     * @Method({"GET"})
     * @Template("OfficeBrainServiceGroupBundle:RewardRuleMappingAdmin:edit.html.twig")
     */
    public function editAction($id)
    {
        $this->initAction();

        if ($id && $id > 0) {
            $ruleMappingMaster = $this->entityManager->getRepository('OfficeBrainServiceGroupBundle:ServiceRuleMappingMaster')->getServiceRuleMappingById($id);
            $ruleMappingRules = $this->entityManager->getRepository('OfficeBrainServiceGroupBundle:ServiceRuleMappingRules')->getMappingRulesByMappingMasterId($id);

            $ruleMapping = array($ruleMappingMaster,$ruleMappingRules);
        }

        if (!isset($ruleMapping) || !$ruleMapping) {
            throw $this->createNotFoundException($this->get('translator')->trans('admin.service_group_management.rule_mapping.not_found_%id%', array('%id%' => $id)));
        }

        $ruleMappingUpdate = $this->OBCommon->camelCaseKeys($ruleMapping[0]);

        $RuleMappSetDataAry['mode'] = 'edit';

        $ruleMappingUpdate['isActive'] = ($ruleMappingUpdate['isActive'] == 1 ? true : false);

        $cultureList = $this->ruleService->getSelectedCultures();

        $RuleMappSetDataAry['culture'] = $cultureList;
        $RuleMappSetDataAry['group'] = null;
        $RuleMappSetDataAry['service'] = null;

        $this->form = $this->createForm(new RewardRuleMappingType($this->container, $RuleMappSetDataAry), $ruleMappingUpdate);
        $this->viewTwigData['form'] = $this->form->createView();
        $this->viewTwigData['ruleMappingRules'] = (isset($ruleMapping[1]) ? $ruleMapping[1] : null);

        return $this->viewTwigData;
    }

    /**
     * @author Employee Id: 4589
     * Description : validate form and update data
     *
     * @param 1 : int $id update record id
     *
     * @return : array data
     *
     * @throws Exception: Null
     *
     * @Route("/edit/{id}",  name="office_brain_servicegroupbundle_rewardrulemappingadmin_processeditajax",
     * requirements={"id"="\d+"})
     *
     * @Method({"POST"})
     * @Template("OfficeBrainServiceGroupBundle:RewardRuleMappingAdmin:edit.html.twig")
     */
    public function processEditAjaxAction($id)
    {
        $this->initAction();

        if ($id && $id > 0) {
            $ruleMappingMaster = $this->entityManager->getRepository('OfficeBrainServiceGroupBundle:ServiceRuleMappingMaster')->getServiceRuleMappingById($id);
            $ruleMappingRules = $this->entityManager->getRepository('OfficeBrainServiceGroupBundle:ServiceRuleMappingRules')->getMappingRulesByMappingMasterId($id);

            $ruleMapping = array($ruleMappingMaster,$ruleMappingRules);
        }

        if (!isset($ruleMapping) || !$ruleMapping) {
            throw $this->createNotFoundException($this->get('translator')->trans('admin.service_group_management.rule_mapping.not_found_%id%', array('%id%' => $id)));
        }

        $ruleMappingUpdate = $this->OBCommon->camelCaseKeys($ruleMapping[0]);

        $ruleMappingUpdate['isActive'] = ($ruleMappingUpdate['isActive'] == 1 ? true : false);
        $culture_id = $ruleMappingUpdate['cultureId'];

        $dataAry = $this->request->request->all();

        $RuleMappSetDataAry['culture'] = $this->ruleService->getSelectedCultures();

        $culture = $this->ruleService->getCultureNameById($culture_id);

        $this->form = $this->createForm(new RewardRuleMappingType($this->container, $RuleMappSetDataAry), $ruleMappingUpdate);

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

        if (!is_array($rulesError = $this->ruleService->updateRuleMapping($this->form, $id, $culture)) && $rulesError) {
            $this->session->set('rule-mapping-success', $this->get('translator')->trans('admin.service_group_management.rule_mapping.edit_message_success'));

            return new JsonResponse(array(
                    'form_name' => $this->form->getName(),
                    'form_status' => 'success',
                    'page_url' => $this->generateUrl('office_brain_servicegroupbundle_rewardrulemappingadmin_list'),
            ));
        } else {
            return new JsonResponse($this->prepareFormJsonError($rulesError));
        }
    }

    /**
     * Get the list of Rule Mapping Master.
     *
     * @Route("/list/{culture}/{page}", name="office_brain_servicegroupbundle_rewardrulemappingadmin_list",
     * requirements={"records_per_page"="12|24|48|96|996", "page"="\d+"},
     * defaults={"rule_service"="rule_mapping","culture"="en_us", "records_per_page"=12,"page"=1})
     *
     * @Method({"GET"})
     * @Template("OfficeBrainServiceGroupBundle:RewardRuleMappingAdmin:list.html.twig")
     */
    public function listAction()
    {
        $this->initAction();

        $param = $this->request->get('_route_params');
        $page = $this->request->get('page', '1');
        $records_per_page = $this->request->get('records_per_page', '2000');

        $culture = $param['culture'];
        $offset = ($page - 1) * $records_per_page;

        $sortBy = $this->request->query->get('sort', 'id');
        $sortType = $this->request->query->get('direction', 'desc');

        $ruleMappingMasterList = $this->getListRuleMapping();

        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate($ruleMappingMasterList, $page, $records_per_page, array(), count($ruleMappingMasterList));

        $this->viewTwigData['sort_by'] = $sortBy;
        $this->viewTwigData['sort_type'] = $sortType;
        $this->viewTwigData['pagination'] = $pagination;
        $this->viewTwigData['page'] = $page;
        $this->viewTwigData['culture'] = $culture;

        return array('data' => $this->viewTwigData);
    }

    /**
     * Get the list of Rule Mapping Master.
     *
     * @Route("/list-ajax/{culture}/{page}", name="office_brain_servicegroupbundle_rewardrulemappingadmin_listajax",
     * requirements={"records_per_page"="12|24|48|96|996", "page"="\d+"},
     * defaults={"rule_service"="rule_mapping","culture"="en_us", "records_per_page"=12,"page"=1})
     *
     * @Method({"GET"})
     * @Template("OfficeBrainServiceGroupBundle:RewardRuleMappingAdmin:tabList.html.twig")
     */
    public function listAjaxAction()
    {
        $this->initAction();

        $data = $ruleMappingMasterList = array();

        $param = $this->request->get('_route_params');
        $page = $this->request->get('page', '1');
        $records_per_page = $this->request->get('records_per_page', '2000');

        $culture = $param['culture'];
        $offset = ($page - 1) * $records_per_page;

        $sortBy = $this->request->query->get('sort', 'id');
        $sortType = $this->request->query->get('direction', 'desc');

        $ruleMappingMasterList = $this->getListRuleMapping();

        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate($ruleMappingMasterList, $page, $records_per_page, array(), count($ruleMappingMasterList));

        $data['pagination'] = $pagination;
        $data['records_per_page'] = $records_per_page;
        $data['page'] = $page;

        return array('data' => $data);
    }

    /**
     * @Route("/view", name="office_brain_servicegroupbundle_rewardrulemappingadmin_view")
     *
     * @Template("OfficeBrainServiceGroupBundle:RewardRuleMappingAdmin:view.html.twig")
     */
    public function viewAction()
    {
        $this->initAction();
        $id = $this->request->get('id', false);

        if ($id && $id > 0) {
            $ruleMappingMaster = $this->entityManager->getRepository('OfficeBrainServiceGroupBundle:ServiceRuleMappingMaster')->getServiceRuleMappingById($id);
            $ruleMappingRules = $this->entityManager->getRepository('OfficeBrainServiceGroupBundle:ServiceRuleMappingRules')->getMappingRulesByMappingMasterId($id);

            $ruleMapping = array($ruleMappingMaster,$ruleMappingRules);
        }

        if (!isset($ruleMapping) || !$ruleMapping) {
            throw $this->createNotFoundException($this->get('translator')->trans('admin.service_group_management.rule_mapping.not_found_%id%', array('%id%' => $id)));
        }

        $ruleMappingUpdate = $this->OBCommon->camelCaseKeys($ruleMapping[0]);

        $this->viewTwigData['data'] = $ruleMappingUpdate;
        $this->viewTwigData['ruleMappingRules'] = (isset($ruleMapping[1]) ? $ruleMapping[1] : null);
        $this->viewTwigData['readOnlyRules'] = true;
        $this->viewTwigData['admin_culture_options'] = $this->cultureList;

        return $this->viewTwigData;
    }

    /**
     * @Route("/delete", name="office_brain_servicegroupbundle_rewardrulemappingadmin_delete")
     *
     * @Method({"GET"})
     * @Template()
     */
    public function deleteAction()
    {
        $this->initAction();
        $id = $this->request->get('id');

        if ($id) {
            $this->ruleService->deleteRuleMapping($id);
            $this->get('session')->getFlashBag()->add('success_message', $this->get('translator')->trans('admin.service_group_management.rule_mapping.delete_message_success'));
        } else {
            $this->get('session')->getFlashBag()->add('success_message', $this->get('translator')->trans('admin.service_group_management.rule_mapping.delete_message_error'));
        }

        return new JsonResponse(array('success' => 'success', 'page_url' => $this->generateUrl('office_brain_servicegroupbundle_rewardrulemappingadmin_list')));
    }

    /**
     * @author Employee Id: 4589
     * Description : make copy of rule mapping
     *
     * @Route("/copy", name="office_brain_servicegroupbundle_rewardrulemappingadmin_copy")
     *
     * @Method({"POST"})
     */
    public function copyAction()
    {
        $this->initAction();

        $this->ruleService->copyRuleMappingMaster();

        $this->get('session')->getFlashBag()->add('success_message', $this->get('translator')->trans('admin.service_group_management.make_copy.copy_message'));

        return $this->redirect($this->generateUrl('office_brain_servicegroupbundle_rewardrulemappingadmin_list', array()));
    }

    public function getListRuleMapping($id = null)
    {
        $page = $this->request->get('page', '1');
        $records_per_page = $this->request->get('page', '2000');
        $culture_id = $culture = $this->request->get('culture', 'en_us');
        if ((int) $culture_id == 0) {
            $country = explode('_', $culture_id);
            if (isset($country[1])) {
                $culture_id = $country[1];
                $language_id = $this->get('office_brain_service_group_service_manager')->getLanguageIdByCode($country[0]);
            } else {
                $culture_id = $country[0];
            }
            $culture_id = $this->get('office_brain_service_group_service_manager')->getCountryIdByCode($culture_id);
        }
        $offset = ($page - 1) * $records_per_page;

        $sortBy = $this->request->query->get('sort', 'id');
        $sortType = $this->request->query->get('direction', 'desc');

        $ruleMappingMasterList = $this->entityManager->getRepository('OfficeBrainServiceGroupBundle:ServiceRuleMappingMaster')->listServiceRuleMapping($language_id, true);

        $returnAry = array();
        if (!empty($ruleMappingMasterList)) {
            if ($id === null) {
                foreach ($ruleMappingMasterList as $recordKey => $recordValue) {
                    if ($culture_id == $recordValue['cultureId']) {
                        $recordValue['cultureName'] = $culture;
                        $returnAry[] = $recordValue;
                    }
                }
            } else {
                foreach ($ruleMappingMasterList as $recordKey => $recordValue) {
                    if ($culture_id == $recordValue['cultureId'] && ($id == $recordValue['id'])) {
                        $recordValue['cultureName'] = $culture;
                        $returnAry = $recordValue;
                    }
                }
            }
        }

        return $returnAry;
    }
    /**
     * @author Employee Id: 4589
     * Description :
     *
     * @param 1 : array $extraFormErrors
     *
     * @return array
     * */
    public function prepareFormJsonError($extraFormErrors = null)
    {
        $formErrors = $this->formErrorManager->prepareErrorArray($this->get('validator')->validate($this->form));
        if ($extraFormErrors != null) {
            $formErrors = array_merge($formErrors, $extraFormErrors);
        }

        return array(
                'form_name' => $this->form->getName(),
                'form_status' => 'error',
                'form_errors' => $formErrors,
        );
    }
}
