<?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\ServiceRuleMasterType;
use OfficeBrain\Bundle\ServiceGroupBundle\Entity\ServiceRuleMaster;

/**
 * @author OfficeBrain 4589 <info@officebrain.com>
 * Description : Manages catalog rule master.
 * @author Office Brain - 4589
 * @Route("/admin/{_locale}/catalogue/rule-master")
 */
class CatalogRuleMasterAdminController extends Controller
{
    protected $request;
    protected $session;
    protected $formErrorManager;
    protected $conditionAry;
    protected $cultureList;
    protected $ruleKeyNameAry;
    protected $actionTypes;
    protected $actionLimitPer;
    protected $actionRuleTypes;
    protected $actionChargeTypes;
    protected $actionAmountTypes;
    protected $ruleMasterManager;
    protected $projectSetting;
    protected $responseArray;
    protected $translator;
    protected $serviceGroupServiceManager;
    protected $ruleType;
    protected $OBCommon;

    /**
     * @author Employee Id: 4589
     * Description : set value as null.
     *
     * @param 1 : No parameter
     *
     * @return type : No return type.
     *
     * @throws Exception: No exception
     * */
    public function __construct()
    {
        $this->request = null;
        $this->entityManager = 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->serviceGroupRuleManager = null;
        $this->projectSetting = null;
        $this->responseArray = array();
        $this->translator = null;
        $this->ruleType = null;
        $this->OBCommon = null;
    }

    /**
     * @author Employee Id: 4589
     * Description : unset value.
     *
     * @param 1 : No parameter
     *
     * @return type : No return type.
     *
     * @throws Exception: No exception
     * */
    public function __destruct()
    {
        unset($this->request);
        unset($this->entityManager);
        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->serviceGroupRuleManager);
        unset($this->projectSetting);
        unset($this->responseArray);
        unset($this->translator);
        unset($this->serviceGroupServiceManager);
        unset($this->ruleType);
        unset($this->OBCommon);
    }

    /**
     * @author Employee Id: 4589
     * Description : initialize value.
     *
     * @param 1 : No parameter
     *
     * @return type : No return type.
     *
     * @throws Exception: No exception
     * */
    public function initAction()
    {
        $this->request = $this->getRequest();
        $this->ruleType = 'catalogue';

        $this->projectSetting = $this->request->get('project_setting');
       // echo '<pre>'; print_r($this->projectSetting['configuration_rule']['promo_discount']); die;
        $this->OBCommon = $this->get('office_brain_core_manager');
        $this->session = $this->request->getSession();
        $this->formErrorManager = new FormErrorManager\JsonError();
        $this->serviceGroupRuleManager = $this->get('office_brain_service_group_rule_manager');
        $this->serviceGroupRuleManager->setRuleType($this->ruleType);

        $this->conditionAry = $this->serviceGroupRuleManager->conditionAry = $this->serviceGroupRuleManager->getConditionArray($this->ruleType);
        $this->cultureList = $this->serviceGroupRuleManager->getCultureList();
        $this->ruleKeyNameAry = $this->serviceGroupRuleManager->setRuleKeyNameArray($this->isRuleMapping);
        $this->actionTypes = $this->serviceGroupRuleManager->getActionTypes();
        $this->actionLimitPer = $this->serviceGroupRuleManager->getActionLimitPer();
        $this->actionRuleTypes = $this->serviceGroupRuleManager->getActionRuleTypes();
        $this->actionChargeTypes = $this->serviceGroupRuleManager->getActionChargeTypes();
        $this->actionAmountTypes = $this->serviceGroupRuleManager->getActionAmountTypes();
        $this->translator = $this->get('translator');
    }

    /**
     * @author Employee Id: 4589
     * Description : Display catalog rule master list.
     *
     * @param 1 : Record per page
     * @param 2 : Page number
     *
     * @return type : Data.
     *
     * @throws Exception: Null
     *
     * @Route("/list/{page}",
     * name="office_brain_servicegroupbundle_catalogrulemasteradmin_list",
     * requirements={"page"="\d+"},
     * defaults={"page"=1})
     * )
     *
     * @Method({"GET"})
     * @Template()
     */
    public function listAction()
    {
        $this->initAction();

        $this->responseArray = $this->serviceGroupRuleManager->getRuleMasterList();

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4589
     * Description : Display catalog rule master list using ajax.
     *
     * @param 1 : Record per page
     * @param 2 : Page number
     *
     * @return type : Data.
     *
     * @throws Exception: Null
     *
     *
     * * @Route("/list/{page}",
     * name="office_brain_servicegroupbundle_catalogrulemasteradmin_listajax",
     * requirements={"page"="\d+"},
     * defaults={"page"=1})
     * )
     *
     * @Method({"POST"})
     * @Template()
     */
    public function listAjaxAction()
    {
        $this->initAction();

        $this->responseArray = $this->serviceGroupRuleManager->getRuleMasterList();

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4589
     * Description : Display Rule Master Data in popup.
     *
     * @param 1 : Rule Master Id
     *
     * @return type : Rule Master Array
     *
     * @throws Exception: NotFoundException
     *
     * @Route("/view", name="office_brain_servicegroupbundle_catalogrulemasteradmin_view")
     * @Template()
     */
    public function viewAction()
    {
        $this->initAction();
        $id = $this->request->get('id', false);

        $serviceRuleMaster = $this->serviceGroupRuleManager->getRuleMasterById($id);
        //echo "<pre>",print_r($serviceRuleMaster);exit;

        if (!$serviceRuleMaster) {
            throw $this->createNotFoundException($this->translator->trans('admin.service_group_management.rule_master.not_found', array('%id%' => $id)));
        }

        $serviceRuleMaster['status'] = ($serviceRuleMaster['status'] == 1 ? true : false);
        $countryId = $serviceRuleMaster['countryId'];

        $serviceRuleMaster['rule_condition'] = $this->getRuleConditionArray($serviceRuleMaster['serviceRuleMainConditionId'], $readOnly = true);

        $serviceRuleMaster['conditions'] = json_encode(array_values($this->serviceGroupRuleManager->getConditionArray($countryId)));
        $serviceRuleMaster['countryId'] = $this->cultureList[$serviceRuleMaster['countryId']];

        $this->responseArray['data'] = $serviceRuleMaster;

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4589
     * Description : Display Add Rule Master form.
     *
     * @param 1 : No Parameter
     *
     * @return type : Form view
     *
     * @throws Exception: No exception
     *
     * @Route("/add",
     * name="office_brain_servicegroupbundle_catalogrulemasteradmin_add")
     *
     * @Method({"GET"})
     * @Template()
     */
    public function addAction()
    {
        $this->initAction();
        $serviceRuleMaster = new ServiceRuleMaster();
        $serviceRuleMaster->setRuleType($this->ruleType);
        $this->form = $this->createForm(new ServiceRuleMasterType($this->container, array('cultureList' => $this->cultureList)), $serviceRuleMaster);

        $this->responseArray['form'] = $this->form->createView();
        $this->responseArray['conditions'] = json_encode(array_values($this->conditionAry));

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4589
     * Description : Submit Rule Master form.
     *
     * @param 1 : No Parameter
     *
     * @return type : Form view and data
     *
     * @throws Exception: No exception
     *
     * @Route("/add", name="office_brain_servicegroupbundle_catalogrulemasteradmin_processadd")
     *
     * @Method({"POST"})
     * @Template("OfficeBrainServiceGroupBundle:CatalogRuleMasterAdmin:add.html.twig")
     */
    public function processAddAction()
    {
        $this->initAction();
        $serviceRuleMaster = new ServiceRuleMaster();
        $serviceRuleMaster->setRuleType($this->ruleType);
        $ruleMasterObj = new ServiceRuleMasterType($this->container, array('cultureList' => $this->cultureList), $serviceRuleMaster);
        $this->form = $this->createForm($ruleMasterObj);

        $ruleMasterObj->setForm($this->form);
        $ruleMasterObj->setRequest($this->request);
        $ruleMasterObj->setServiceRuleManager($this->serviceGroupRuleManager);

        if (!is_array($ruleCondError = $this->serviceGroupRuleManager->setRuleMaster($this->form)) && $ruleCondError) {
            $this->session->getFlashBag()->add('success_message', $this->translator->trans('admin.service_group_management.rule_master.add_message_success'));

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

    /**
     * @author Employee Id: 4589
     * Description : Display Edit Rule Master form.
     *
     * @param 1 : Rule Master Id
     *
     * @return type : Form view and data
     *
     * @throws Exception: No exception
     *
     * @Route("/edit/{id}",
     * name="office_brain_servicegroupbundle_catalogrulemasteradmin_edit")
     *
     * @Method({"GET"})
     * @Template()
     */
    public function editAction()
    {
        $this->initAction();

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

        if ($id) {
            $serviceGroup = $this->serviceGroupRuleManager->getRuleMasterById($id);
        }

        if (!isset($serviceGroup) || !$serviceGroup) {
            throw $this->createNotFoundException($this->translator->trans('admin.service_group_management.rule_master.not_found', array('%id%' => $id)));
        }

        $serviceGroupUpdate = $serviceGroup;

        $serviceGroupUpdate['status'] = ($serviceGroupUpdate['status'] == 1 ? true : false);

        $countryId = $serviceGroupUpdate['countryId'];

        if (isset($serviceGroupUpdate['serviceRuleMainConditionId'])) {
            $serviceGroupUpdate['rule_condition'] = $this->getRuleConditionArray($serviceGroupUpdate['serviceRuleMainConditionId']);
        }

        $this->form = $this->createForm(new ServiceRuleMasterType($this->container, array('cultureList' => $this->cultureList, 'mode' => 'edit')), $serviceGroupUpdate);
        $this->responseArray['form'] = $this->form->createView();
        $this->responseArray['conditions'] = json_encode(array_values($this->serviceGroupRuleManager->getConditionArray($countryId)));

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4589
     * Description : Submit Edit Rule Master form.
     *
     * @param 1 : Rule Master Id
     *
     * @return type : Form view and data
     *
     * @throws Exception: No exception
     *
     * @Route("/edit/{id}", name="office_brain_servicegroupbundle_catalogrulemasteradmin_processedit")
     *
     * @Method({"POST"})
     * @Template("OfficeBrainServiceGroupBundle:CatalogRuleMasterAdmin:edit.html.twig")
     */
    public function processEditAction()
    {
        $this->initAction();

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

        if ($id) {
            $serviceGroup = $this->serviceGroupRuleManager->getRuleMasterById($id);
        }

        if (!isset($serviceGroup) || !$serviceGroup) {
            throw $this->createNotFoundException($this->translator->trans('admin.service_group_management.rule_master.not_found', array('%id%' => $id)));
        }

        $serviceGroupUpdate = $serviceGroup; //$this->OBCommon->camelCaseKeys($serviceGroup);

        $serviceGroupUpdate['status'] = ($serviceGroupUpdate['status'] == 1 ? true : false);

        if (isset($serviceGroupUpdate['serviceRuleMainConditionId'])) {
            $serviceGroupUpdate['rule_condition'] = $this->getRuleConditionArray($serviceGroupUpdate['serviceRuleMainConditionId']);
        }

        $countryId = $serviceGroupUpdate['countryId'];

        $ruleMasterObj = new ServiceRuleMasterType($this->container, array('cultureList' => $this->cultureList, 'mode' => 'edit'));
        $this->form = $this->createForm($ruleMasterObj, $serviceGroupUpdate);

        $ruleMasterObj->setForm($this->form);
        $ruleMasterObj->setRequest($this->request);
        $ruleMasterObj->setServiceRuleManager($this->serviceGroupRuleManager);

        if (!is_array($ruleCondError = $this->serviceGroupRuleManager->updateRuleMaster($this->form, $id, $countryId)) && $ruleCondError) {
            $this->session->getFlashBag()->add('success_message', $this->translator->trans('admin.service_group_management.rule_master.edit_message_success'));

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

    /**
     * @author Employee Id: 4589
     * Description : Delete Rule Master.
     *
     * @param 1 : Rule Master Id
     *
     * @return type : JsonResponse object
     *
     * @throws Exception: No exception
     *
     * @Route("/delete", name="office_brain_servicegroupbundle_catalogrulemasteradmin_delete")
     *
     * @Method({"GET"})
     * @Template()
     */
    public function deleteAction()
    {
        $this->initAction();
        $id = $this->request->get('id');

        $serviceGroup = null;
        if ($id) {
            $serviceGroup = $this->serviceGroupRuleManager->deleteRuleMaster($id);

            if ($serviceGroup) {
                $this->session->getFlashBag()->add('success_message', $this->translator->trans('admin.service_group_management.rule_master.delete_message_success'));
            } else {
                $this->session->getFlashBag()->add('error_message', $this->translator->trans('admin.service_group_management.rule_master.delete_message_error'));
            }

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

    /**
     * @author Employee Id: 4273
     * Description : Change Status Rule Master.
     *
     * @param 1 : Rule Master Id
     *
     * @return type : JsonResponse object
     *
     * @throws Exception: No exception
     *
     * @Route("/change-status", name="office_brain_servicegroupbundle_catalogrulemasteradmin_change_status")
     *
     * @Method({"POST"})
     * @Template()
     */
    public function changeStatusAction()
    {
        $this->initAction();

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

        $serviceGroup = null;
        if ($id) {
            $serviceGroup = $this->serviceGroupRuleManager->changeRuleMasterStatus($id);
            if ($serviceGroup) {
                return new JsonResponse(array('status' => 'success', 'status_message' => $this->translator->trans('admin.service_group_management.rule_master.status_message_success')));
            }
        }

        return new JsonResponse(array('status' => 'fail', 'status_message' => $this->translator->trans('admin.service_group_management.rule_master.status_message_fail')));
    }

    /**
     * @author Employee Id: 4589
     * Description : Display Add Rule Mapping Rule form.
     *
     * @param 1 : No parameter
     *
     * @return type : Form view and data
     *
     * @throws Exception: No exception
     *
     * @Route("/add-mapping-rules",
     * name="office_brain_servicegroupbundle_catalogrulemasteradmin_listajaxmodal",options={"expose"=true})
     *
     * @Method({"POST"})
     * @Template()
     */
    public function listAjaxModalAction()
    {
        $this->initAction();

        $dataAry = $this->request->request->all();
        $this->responseArray['rule_master_ids'] = array();
        if (isset($dataAry['rule_master_id']) && count($dataAry['rule_master_id']) > 0) {
            $this->responseArray['rule_master_ids'] = $dataAry['rule_master_id'];
        }

        // call repository
        $this->responseArray['rules'] = $this->serviceGroupRuleManager->getRuleMasterListByCountry();

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4589
     * Description : Get rule filter by culture for add rule master form.
     *
     * @param 1 : countryId
     *
     * @return type : JsonResponse object
     *
     * @throws Exception: No exception
     *
     * @Route("/rule-filters/{countryId}", name="office_brain_servicegroupbundle_catalogrulemasteradmin_getrulefilters")
     *
     * @Method({"GET"})
     * @Template()
     */
    public function getRuleFiltersAction()
    {
        $this->initAction();

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

        $this->responseArray = array_values($this->serviceGroupRuleManager->getConditionArray($countryId));

        return new JsonResponse(array('data' => $this->responseArray));
    }

    /**
     * @author Employee Id: 4589
     * Description : Check Rule Name exist.
     *
     * @param 1 : Rule Name
     * @param 2 : Culture
     *
     * @return type : Boolean
     *
     * @throws Exception: No exception
     */
    public function checkRuleNameExist($ruleName, $countryId)
    {
        $this->initAction();
        $ruleName = trim($ruleName);
        $id = $this->request->get('id', null);

        if ($ruleName != null && $countryId) {
            if ($this->serviceGroupRuleManager->checkRuleNameExistServiceRuleMaster($ruleName, $countryId, $id)) {
                return true;
            }
        }

        return false;
    }

    /**
     * @author Employee Id: 4589
     * Description : Prepare form error
     *
     * @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,
        );
    }

    /**
     * @author Employee Id: 4589
     * Description : Get Rule condition Array
     *
     * @param 1 : array $condOrderAry
     * @param 2 : bool  $readOnly
     *
     * @return array
     * */
    public function getRuleConditionArray($conditionAry, $readOnly = false)
    {
        if (!$conditionAry || $conditionAry == null) {
            return;
        }

        // ************** Get All the condition in single array ************** //
        //$parentRelAry = array_column($conditionAry, $this->ruleKeyNameAry['parent_id'], 'key');
        $parentRelAry = $this->OBCommon->get_array_column($conditionAry, $this->ruleKeyNameAry['parent_id'], 'key');
        $allCondition = $this->serviceGroupRuleManager->getAllCondition($conditionAry, $parentRelAry);

        // ******************** Set Array in sorting of 'order' ****************** //
        //$condOrderAry = array_column($allCondition, $this->ruleKeyNameAry['display_order']);
        $condOrderAry = $this->OBCommon->get_array_column($allCondition, $this->ruleKeyNameAry['display_order']);
        array_multisort($condOrderAry, SORT_ASC, $allCondition);

        // ********* Set array in Json Format(jquery Plugin format) to show it on Edit/View ****** //
        $jsonAry = $this->serviceGroupRuleManager->setArrayWithJsonFormat($allCondition, $readOnly);

        if ($jsonAry && count($jsonAry) > 0) {
            return json_encode($jsonAry);
        } else {
            return;
        }
    }
}
