<?php

namespace OfficeBrain\Bundle\UserBundle\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\UserBundle\Entity\ContactBook;
use OfficeBrain\Bundle\CoreBundle\CustomeHandler as FormErrorManager;
use Symfony\Component\HttpFoundation\JsonResponse;
use OfficeBrain\Bundle\UserBundle\Form\ContactBookType;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class AdminContactBookController extends Controller
{
    /**
     * @author Employee Id: 4493
     * set default value
     * @return NULL
     */

    public function __construct()
    {
        $this->request = null;
        $this->user = null;
        $this->userId = null;
        $this->locale = null;
        $this->session = null;
        $this->form = null;
        $this->contactBookField = null;
        $this->contactBookId = null;
        $this->translator = null;
        $this->formErrorManager = new FormErrorManager\JsonError();
        $this->responseArray = null ;
        $this->contactBookAccessField = null ;
        $this->erpIntegration = null ;
        $this->contactbookmanager = null ;
        $this->queueApiManager = null ;
        $this->userManager = null ;
        $this->searchParameterArray = array();
    }

    /**
     * @author Employee Id: 4493
     * To unset value
     * @return NULL
     */

    public function __destruct()
    {
        unset($this->request);
        unset($this->user);
        unset($this->userId);
        unset($this->locale);
        unset($this->session);
        unset($this->contactBookId);
        unset($this->translator);
        unset($this->form);
        unset($this->contactBookField);
        unset($this->formErrorManager);
        unset($this->responseArray);
        unset($this->contactBookAccessField);
        unset($this->erpIntegration);
        unset($this->contactbookmanager);
        unset($this->queueApiManager);
        unset($this->userManager);
        unset($this->searchParameterArray);
        unset($this->projectUserSetting);
    }


    private function prepareFormJsonError()
    {
        return array(
            'form_name' => $this->form->getName(),
            'form_status' => 'error',
            'form_errors' => $this->formErrorManager->prepareErrorArray($this->get('validator')->validate($this->form))
        );
    }


    /**
     * @author Employee Id: 4493
     * Create objects which use this class
     * @return NULL
     */

    public function initAction()
    {
        $this->request = $this->getRequest();
        $this->session = $this->request->getSession();
        $this->projectSetting = $this->request->get('project_setting');
        $this->locale = $this->projectSetting['locale_language'];
        $this->projectUserSetting = $this->request->get('project_user_setting');
        $this->contactBookId = $this->request->get('id', null);
        $this->responseArray['status'] = 'error';
        $this->translator = $this->get('translator');
        $this->contactBookAccessField= $this->projectSetting['access_rule']['user']['option']['contact_book'];
        $this->contactBookConfigurationField= $this->projectSetting['configuration_rule']['user']['contact_book'];
        $this->erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
        $this->contactbookmanager = $this->get('office_brain_user_contact_book_manager');
        $this->userId = $this->projectSetting['user_id'];
        $this->user = $this->projectUserSetting['user_data'];
        $this->contactBookFlag = 0;
        $this->addressBookFlag = 1;
        $this->changeAddressTypeFlag = 0;
        $this->page = $this->request->get('page', '1');
        $this->requestUserId = $this->request->get('userId', $this->userId);

        $this->dashboardFlag = 'myContactBook';
        if($this->requestUserId > 0){
        	$this->dashboardFlag = 'adminSide';
        }

        $this->recordsPerPage = $this->request->get('records_per_page', $this->contactBookConfigurationField['no_of_record_per_page']);

        $this->responseArray['records_per_page'] = $this->recordsPerPage;
        $this->responseArray['page'] = $this->page;
        $this->responseArray['contactBookField'] = $this->contactBookConfigurationField;
        $this->responseArray['contactBookAccessField'] = $this->contactBookAccessField;
        $this->responseArray['userId'] = $this->requestUserId;
        $this->responseArray['dashboardFlag'] = $this->dashboardFlag;


        if ($this->has('office_brain_queue_api_manager')) {
            $this->request->attributes->set('object', 'ContactBook');
            $this->queueApiManager = $this->get('office_brain_queue_api_manager');
        }
        $this->userManager = $this->get('office_brain_user_manager');
        $this->exceptionManager = $this->get('access_authorized_exception');
    }


    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - admin contact book form
     * @Route(
     *   "admin/{_locale}/contact-book/add/{userId}",
     *    name="office_brain_userbundle_admincontactbook_addadmincontactbook",
     *    options={"expose"=true},
     *    defaults={"userId"=0}
     * )
     * @Method({"GET"})
     * @Template()
     */

    public function addAdminContactBookAction()
    {
        $this->initAction();
        $contactBook = new ContactBook();
        if($this->requestUserId == '' || $this->requestUserId == null){
          $this->requestUserId = $this->userId;
          $user = $this->user;
        }else{
          $user = $this->contactbookmanager->getValidUserById($this->requestUserId);
        }
        if ($user and $user != '') {
        	$contactBook->setUser($user);
        }
        $contactBookObj = new ContactBookType($this->container, $this->dashboardFlag);
        $this->form = $this->createForm($contactBookObj, $contactBook);
        $this->form->handleRequest($this->request);
        $this->responseArray['contactBookForm'] = $this->form->createView();
        return $this->responseArray;
    }


    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  contact book form submit
     *
     * @Route(
     *    "admin/{_locale}/contact-book/add/{userId}",
     * 	  name="office_brain_userbundle_admincontactbook_addadmincontactbookpost",
     *    options={"expose"=true},
     *    defaults={"userId"=0}
     * )
     * @Method({"POST"})
     * @Template("OfficeBrainUserBundle:AdminContactBook:addAdminContactBook.html.twig")
     */

    public function addAdminContactBookPostAction()
    {
        $this->initAction();
        $contactBook = new ContactBook();
        if($this->requestUserId == '' || $this->requestUserId == null){
          $this->requestUserId = $this->userId;
          $user = $this->user;
        }else{
          $user = $this->contactbookmanager->getValidUserById($this->requestUserId);
        }
        if ($user and $user != '') {
        	$contactBook->setUser($user);
        }

        $contactBookObj = new ContactBookType($this->container, $this->dashboardFlag);
        $this->form = $this->createForm($contactBookObj, $contactBook);
        $this->form ->handleRequest($this->request);
        if ($this->form->isValid()) {
            $contactBookData = $this->form->getData();
            $add=$this->contactbookmanager->addContactBook($contactBookData, $this->dashboardFlag, $this->contactBookFlag);
            switch ($add['status']) {
                case  'SUCCESS' :
                    $userId = $add['data']->getUser()->getId();
                    if ($this->erpIntegration && $this->erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager)) {
                        if ($user->getUserType() != 'end_user' && !empty($user->getUserCompany())) {
                            $this->queueApiManager->mapQueue("create", $add['data']);
                        } else if ($user->getUserType() == 'end_user') {
                            $this->queueApiManager->mapQueue("create", $add['data']);
                        }
                    }
                    $this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('user.contact_book.add_message.success_msg'));
                    if($this->dashboardFlag == 'myContactBook'){
                    	return $this->redirect($this->generateUrl("office_brain_userbundle_admincontactbook_viewadmincontactbook"));
                    }else{
                    	return $this->redirect($this->generateUrl("office_brain_userbundle_admincontactbook_viewadmincontactbook", array('userId'=>$userId)));
                    }
                    break;
            }
        }
        $this->responseArray['contactBookForm'] = $this->form->createView();
        return  $this->responseArray;
    }




    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  Admincontact book View
     *
     * @Route("admin/{_locale}/contact-book/view/{userId}",
     * 	name="office_brain_userbundle_admincontactbook_viewadmincontactbook",
     *  options={"expose"=true},
     *  defaults={"userId"=NULL}
     * )
     * @Method({"GET"})
     * @Template()
     */

    public function viewAdminContactBookAction()
    {
        $this->initAction();

        if($this->requestUserId == '' || $this->requestUserId == null){ $this->requestUserId = $this->userId; }
        $this->prepareSearchParameterArray();
        $this->responseArray['record_set'] = $this->contactbookmanager->getContactBook($this->requestUserId, $this->contactBookFlag, $this->page, $this->recordsPerPage, $this->searchParameterArray);
        $this->responseArray['total_record'] = $this->contactbookmanager->getTotal();

        return $this->responseArray;
    }


    /**
     * @author : 4493)
     * OB eCommerce Product - get sindle record of Contact Book
     * @Route(
     *   "admin/{_locale}/contact-book/view/popup/{id}",
     *    name="office_brain_userbundle_admincontactbook_viewcontactbookpopup",
     *    options={"expose"=true},
     * )
     * @Method({"GET"})
     * @Template()
     */
    public function viewContactBookPopupAction()
    {
        $this->initAction();
        $contactBook = $this->contactbookmanager->getSingleContactBook($this->contactBookId);
        
        if($this->exceptionManager->isUserAllowedToAccess($contactBook->getCreatedUid(), $this->contactBookConfigurationField['allowed_users']))
        {
        	$this->responseArray['items'] = $contactBook;
        	return $this->responseArray;
        }else {
        	$this->exceptionManager->throwAccessException();
        	//throw new NotFoundHttpException('Sorry not existing!');
        }
        
    }


    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - admin contact book form
     * @Route(
     *   "admin/{_locale}/contact-book/edit/{contactBookId}",
     *    name="office_brain_userbundle_admincontactbook_editadmincontactbook",
     *    options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template()
     */

    public function editAdminContactBookAction()
    {
        $this->initAction();
        $contactBookId = $this->request->get('contactBookId');
        $contactBookArray = $this->contactbookmanager->getSingleContactBook($contactBookId);
		
		if($this->exceptionManager->isUserAllowedToAccess($contactBookArray->getCreatedUid(), $this->contactBookConfigurationField['allowed_users']))
        {
       	        $userId = $contactBookArray->getUser()->getId();
		        if($userId == $this->userId){
		        	$this->dashboardFlag = 'myContactBook';
		        	$user = $this->user;
		        }else{
		        	$user = $this->contactbookmanager->getValidUserById($userId);
		        }
		        $contactBookForm = $this->createForm(new ContactBookType($this->container, $this->dashboardFlag), $contactBookArray);
		
		        return array('contactBookForm'=> $contactBookForm->createView(),'contactBookId'=>$contactBookId, 'userId'=>$userId,'dashboardFlag'=>$this->dashboardFlag);
		        
        }else {
        	$this->exceptionManager->throwAccessException();
        	//throw new NotFoundHttpException('Sorry not existing!');
        }
    }



    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  contact book form submit
     *
     * @Route("admin/{_locale}/contact-book/edit/{contactBookId}",
     * name="office_brain_userbundle_admincontactbook_editadmincontactbookpost",
     * options={"expose"=true}
     * )
     * @Method({"POST"})
     * @Template("OfficeBrainUserBundle:AdminContactBook:editAdminContactBook.html.twig")
     */

    public function editAdminContactBookPostAction()
    {
        $this->initAction();
        $contactBookId = $this->request->get('contactBookId');
        $contactBookObject = $this->contactbookmanager->getSingleContactBook($contactBookId);
        

        if($this->exceptionManager->isUserAllowedToAccess($contactBookObject->getCreatedUid(), $this->contactBookConfigurationField['allowed_users']))
        {
        	    $userId = $contactBookObject->getUser()->getId();
		        if($userId == $this->userId){
		        	$this->dashboardFlag = 'myContactBook';
		        	$user = $this->user;
		        }else{
		        	$user = $this->contactbookmanager->getValidUserById($userId);
		        }
		        $previousAddressType=$contactBookObject->getAdressType()->getId();
		        $this->form  = $this->createForm(new ContactBookType($this->container, $this->dashboardFlag), $contactBookObject);
		        $this->form ->handleRequest($this->request);
		
		        if ($this->form->isValid()) {
		            $contactBookData = $this->form->getData();
		            if($previousAddressType!=$contactBookData->getAdressType()->getId()) {
		            	$this->changeAddressTypeFlag=1;
		            }
		            $add = $this->contactbookmanager->editContactBook($contactBookData,$this->changeAddressTypeFlag);
		            switch ($add['status']) {
		                case  'SUCCESS' :
		                    //$userId = $add['data']->getUser()->getId();
		                    if ($this->erpIntegration && $this->erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager)){
                                if ($user->getUserType() != 'end_user' && !empty($user->getUserCompany())) {
                                    if ($add['data']->getErpId() > 0) {
                                        $this->queueApiManager->mapQueue("update", $add['data']);
                                    } else {
                                        $this->queueApiManager->mapQueue("create", $add['data']);
                                    }
                                } else if ($user->getUserType() == 'end_user') {
                                    if ($add['data']->getErpId() > 0) {
                                        $this->queueApiManager->mapQueue("update", $add['data']);
                                    } else {
                                        $this->queueApiManager->mapQueue("create", $add['data']);
                                    }
                                }
                            }
		                    $this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('user.contact_book.edit_message.success_msg'));
		                    if($this->dashboardFlag == 'myContactBook'){
		                    	return $this->redirect($this->generateUrl("office_brain_userbundle_admincontactbook_viewadmincontactbook"));
		                    }else{
		                    	return $this->redirect($this->generateUrl("office_brain_userbundle_admincontactbook_viewadmincontactbook", array('userId'=>$userId)));
		                    }
		                    break;
		            }
		        }
		
		        return array('contactBookForm'=> $this->form->createView(),'contactBookId'=>$contactBookId,'userId'=>$userId,'dashboardFlag'=>$this->dashboardFlag);
        
        }else {
        	$this->exceptionManager->throwAccessException();
        	//throw new NotFoundHttpException('Sorry not existing!');
        }
		
    }

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  Admin contact book Delete
     *
     * @Route("admin/{_locale}/contact-book/delete",
     * 	name="office_brain_userbundle_admincontactbook_deleteadmincontactbook",
     *  options={"expose"=true}
     * )
     * @Template()
     */
    public function deleteContactBookAction()
    {
        $this->initAction();
        $contactBookObject = $this->contactbookmanager->getSingleContactBook($this->contactBookId);
        
        if($this->exceptionManager->isUserAllowedToAccess($contactBookObject->getCreatedUid(), $this->contactBookConfigurationField['allowed_users']))
        {
        	
		        $userId = $contactBookObject->getUser()->getId();
		        $erpId = $contactBookObject->getErpId();
		        $contactBook = $this->contactbookmanager->deleteContactBook($this->contactBookId);
		
		        switch ($contactBook['status']) {
		            case  'SUCCESS' :
		                $this->responseArray['status'] = 'success';
		
		                $this->responseArray['success_message'] = $this->get('translator')->trans('user.contact_book.remove_message.success_msg');
		                if ($this->erpIntegration && $this->erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager) && $erpId > 0) {
		                    $this->queueApiManager->mapQueue("remove", array('id' => $this->contactBookId, 'erp_id' => $erpId));
		                }
		                //$this->responseArray['page_url'] = $this->generateUrl('office_brain_userbundle_admincontactbook_viewadmincontactbook', array('userId'=>$userId));
		                break;
		            case  'FAIL':
		                $this->responseArray['error_message'] = $this->get('translator')->trans('user.contact_book.remove_message.fail_msg');
		                break;
		        }
		        return new JsonResponse($this->responseArray);
        
        }else {
        	$this->exceptionManager->throwAccessException();
        	//throw new NotFoundHttpException('Sorry not existing!');
        }
        
    }


    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  Is Default Update
     *
     * @Route("admin/{_locale}/contact-book/is-default",
     * 	name="office_brain_userbundle_admincontactbook_isdefault",
     *  options={"expose"=true}
     * )
     * @Template()
     */

    public function isDefaultAction()
    {
        $this->initAction();
        $data = array();
        $contactBookId = $this->request->get('id');
        $isDefault = $this->contactbookmanager->updateIsDefault($contactBookId);
        switch ($isDefault['status']) {
            case  'SUCCESS' :
                if ($this->erpIntegration && $this->erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager) ) {
                    if($isDefault['data']->getErpId()){
                        $this->queueApiManager->mapQueue("update", $isDefault['data']);
                    }else{
                        $this->queueApiManager->mapQueue("create", $isDefault['data']);
                    }
                }
                $this->responseArray['status'] = 'success';
                $this->responseArray['addressType'] = $isDefault['data']->getAdressType()->getId();
                $this->responseArray['status_message'] = $this->get('translator')->trans('user.contact_book.update_default.success_msg');
                break;
            case  'FAIL':
                $this->responseArray['error_message'] = $this->get('translator')->trans('user.contact_book.update_default.fail_msg');
                break;
        }
        return new JsonResponse($this->responseArray);
    }



    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - preapre  search parameter
     */
    private function prepareSearchParameterArray()
    {
    	$this->searchParameterArray[$this->request->get('option', null)]=trim($this->request->get('keywords', null));
    }
}
