<?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;


class ContactBookController 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->field = null;
        $this->form = null;
        $this->contactBookId = null;
        $this->translator = null;
        $this->formErrorManager = new FormErrorManager\JsonError();
        $this->erpIntegration = null;
        $this->queueApiManager = null;
    }

    /**
     *
     * @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->field);
        unset($this->form);
        unset($this->formErrorManager) ;
        unset($this->erpIntegration);
        unset($this->queueApiManager);
    }


    protected 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->contactBookId = $this->request->get('contactBookId', null);
        $this->responseArray['status'] = 'error';
        $this->translator = $this->get('translator');
        $this->projectSetting = $this->request->get('project_setting');
        $this->locale = $this->projectSetting['locale_language'];
        $this->addressBookAccessField= $this->projectSetting['access_rule']['user']['option']['address_book'];
        $this->addressBookConfigrationField = $this->projectSetting['configuration_rule']['user']['address_book'];
        $this->erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
        $this->contactbookmanager = $this->get('office_brain_user_contact_book_manager');
        $this->page = $this->request->get('page', '1');
        $this->recordsPerPage = $this->request->get('records_per_page', $this->addressBookConfigrationField['no_of_record_per_page']);
        $this->responseArray['records_per_page'] = $this->recordsPerPage;
        $this->responseArray['page'] = $this->page;
        $this->responseArray['addressBookConfigrationField'] = $this->addressBookConfigrationField;
        $this->responseArray['addressBookAccessField']=$this->addressBookAccessField;


        $this->addressBookFlag = '1';
        $this->changeAddressTypeFlag = 0;
        $this->userId = $this->projectSetting['user_id'];;
        if ($this->has('office_brain_queue_api_manager')) {
            $this->request->attributes->set('object', 'ContactBook');
            $this->queueApiManager = $this->get('office_brain_queue_api_manager');
        }
        $this->exceptionManager = $this->get('access_authorized_exception');
    }

    public function initActionMyContactBook()
    {
    	$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 -  contact book form
     *
     * @Route("{_locale}/my-account/address-book/add",
     * 	name="office_brain_userbundle_contactbook_addcontactbook",
     *  options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainUserBundle:ContactBook:addContactBook.html.twig")
     */

    public function addContactBookAction()
    {
        $this->initAction();
        $this->form = $this->createForm(new ContactBookType($this->container), new 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("{_locale}/my-account/address-book/add",
     * 	name="office_brain_userbundle_contactbook_addcontactbookpost",
     *  options={"expose"=true}
     * )
     * @Method({"POST"})
     * @Template("OfficeBrainUserBundle:ContactBook:addContactBook.html.twig")
     */

    public function addContactBookPostAction()
    {
        $this->initAction();
        $this->form = $this->createForm(new ContactBookType($this->container), new ContactBook());
        $this->form ->handleRequest($this->request);
        if ($this->form->isValid()) {
            $contactBookData = $this->form->getData();
            
            $emailExist = $this->contactbookmanager->getContactBookByEmail($contactBookData->getEmail(), $contactBookData->getAdressType()->getId());
            if(count($emailExist)>0 && $emailExist[0]->getId() != $contactBookId) {
            	$this->responseArrayNew['form_status'] = 'error';
            	$this->responseArrayNew['error_message'] = $this->get('translator')->trans('request_quote.shipping_type.email_already_exist');
            	return new JsonResponse($this->responseArrayNew);
            }

            $add=$this->contactbookmanager->addContactBook($contactBookData, '', 1);
            switch ($add['status']) {
            	case  'SUCCESS' :
            		if ($this->erpIntegration && $this->erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager)) {
            			$this->queueApiManager->mapQueue("create", $add['data']);
            		}
            		//DO NOT ADD MESSAGE IN FLAHBAG IF IT'S AJAX REQUEST  
            		if(!$this->request->isXmlHttpRequest ()){
            			$this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('user.contact_book.add_message.address_success'));
            		}
            		break;
            	case  'FAIL':
            		//DO NOT ADD MESSAGE IN FLAHBAG IF IT'S AJAX REQUEST
            		if(!$this->request->isXmlHttpRequest ()){
            			$this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('user.contact_book.add_message.address_fail'));
            		}
            		break;
            }
            
            if($this->request->isXmlHttpRequest ()){
            	$this->responseArray['status'] = 'success';
            	$this->responseArray['call_ajax_url_checkout'] = $this->generateUrl("office_brain_requestquotebundle_requestquote_getshippingaddressbyid") ; //'office_brain_requestquotebundle_requestquote_getshippingaddressbyid';
            	$this->responseArray['contact_book_id'] = $contactBookData->getId();
    			$this->responseArray['success_message'] = $this->get('translator')->trans('request_quote.shipping_type.address_added_successfully');
    			$counter = $this->request->get('counter',null); // Used for request Quote Add Address
    			if($counter!=null){
    				$this->responseArray['counter'] = $counter;
    			}
    			return new JsonResponse($this->responseArray);
            }
            return $this->redirect($this->generateUrl("office_brain_userbundle_contactbook_viewcontactbook"));
        }
        $this->responseArray['contactBookForm'] = $this->form->createView();

        if($this->request->isXmlHttpRequest ()){
        	if ($this->request->get('call_type')=='country_code' || $this->request->get('call_type')=='state_code') {
                return $this->responseArray;
            } else {
              	return new JsonResponse ( $this->prepareFormJsonError ($this->form) );
            }
        }

        return $this->responseArray;
    }


    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  contact book form
     *
     * @Route("{_locale}/my-account/address-book/edit/{contactBookId}",
     * 	name="office_brain_userbundle_contactbook_editcontactbook",
     *  options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainUserBundle:ContactBook:editContactBook.html.twig")
     */

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


    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  contact book form submit
     *
     * @Route("{_locale}/my-account/address-book-checkout/edit/{contactBookId}",
     *  name="office_brain_userbundle_contactbook_editcontactbookcheckoutpost",
     *  options={"expose"=true}
     * )
     * @Method({"POST"})
     * @Template("OfficeBrainUserBundle:ContactBook:editContactBook.html.twig")
     */

    public function editContactBookCheckoutPostAction()
    {
        $this->initAction();
        $contactBookId = $this->request->get('contactBookId');
        $contactBookObject = $this->contactbookmanager->getSingleContactBook($contactBookId);
        
        $previousAddressType=$contactBookObject->getAdressType()->getId();
        $this->form  = $this->createForm(new ContactBookType($this->container), $contactBookObject);
        $this->form ->handleRequest($this->request);
        if ($this->form->isValid()) {
            $contactBookData = $this->form->getData();
            if($previousAddressType!=$contactBookData->getAdressType()->getId()) {
                $this->changeAddressTypeFlag=1;
            }

            $emailExist = $this->contactbookmanager->getContactBookByEmail($contactBookData->getEmail(), $contactBookData->getAdressType()->getId());
            if(count($emailExist)>0 && $emailExist[0]->getId() != $contactBookId) {
                $this->responseArrayNew['form_status'] = 'error';
                $this->responseArrayNew['error_message'] = $this->get('translator')->trans('request_quote.shipping_type.email_already_exist');
                return new JsonResponse($this->responseArrayNew);
            }
            
            $edit=$this->contactbookmanager->editContactBook($contactBookData,$this->changeAddressTypeFlag);
            /*switch ($edit['status']) {
                case  'SUCCESS' :
                    if ($this->erpIntegration && $this->erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager) ) {
                        if($edit['data']->getErpId()){
                            $this->queueApiManager->mapQueue("update", $edit['data']);
                        }else{
                            $this->queueApiManager->mapQueue("create", $edit['data']);
                        }
                    }
                    $this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('user.contact_book.edit_message.address_success'));
                    break;
                case  'FAIL':
                    $this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('user.contact_book.edit_message.address_fail'));
                    break;
            }*/
            if($this->request->isXmlHttpRequest ()){
                $this->responseArray['status'] = 'success';
                if(count($this->request->get('is_edit_from_payment'))>0 && $this->request->get('is_edit_from_payment')==1)
                {
                    $this->responseArray['call_ajax_url_checkout'] = $this->generateUrl("office_brain_orderbundle_order_getcheckoutshippingaddressbyid");
                }
                else
                {
                    $this->responseArray['call_ajax_url'] = $this->generateUrl("office_brain_requestquotebundle_requestquote_getshippingaddressbyid");
                }

                $this->responseArray['contact_book_id'] = $contactBookId;
                $this->responseArray['success_message'] = $this->get('translator')->trans('request_quote.shipping_type.edit_address_added_successfully');
                $counter = $this->request->get('counter',null); // Used for request Quote Edit Address
                if($counter!=null){
                    $this->responseArray['counter'] = $counter;
                }
                return new JsonResponse($this->responseArray);
            }
            return $this->redirect($this->generateUrl("office_brain_userbundle_contactbook_viewcontactbook"));
        }

        if($this->request->isXmlHttpRequest ()){
            if ($this->request->get('call_type')=='country_code' || $this->request->get('call_type')=='state_code') {
                return $this->responseArray;
            } else {
                return new JsonResponse ( $this->prepareFormJsonError ($this->form) );
            }
        }

        return array('contactBookForm'=> $this->form->createView(),'contactBookId'=>$contactBookId);
        
    }

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  contact book form submit
     *
     * @Route("{_locale}/my-account/address-book/edit/{contactBookId}",
     * 	name="office_brain_userbundle_contactbook_editcontactbookpost",
     *  options={"expose"=true}
     * )
     * @Method({"POST"})
     * @Template("OfficeBrainUserBundle:ContactBook:editContactBook.html.twig")
     */

    public function editContactBookPostAction()
    {
        $this->initAction();
        $contactBookId = $this->request->get('contactBookId');
        $contactBookObject = $this->contactbookmanager->getSingleContactBook($contactBookId);
        
        if($this->exceptionManager->isUserAllowedToAccess($contactBookObject->getCreatedUid(), $this->addressBookConfigrationField['allowed_users']))
        {
        	$previousAddressType=$contactBookObject->getAdressType()->getId();
	        $this->form  = $this->createForm(new ContactBookType($this->container), $contactBookObject);
	        $this->form ->handleRequest($this->request);
	        if ($this->form->isValid()) {
	        	$contactBookData = $this->form->getData();
	        	if($previousAddressType!=$contactBookData->getAdressType()->getId()) {
	        		$this->changeAddressTypeFlag=1;
	        	}

	        	$emailExist = $this->contactbookmanager->getContactBookByEmail($contactBookData->getEmail(), $contactBookData->getAdressType()->getId());
	        	if(count($emailExist)>0 && $emailExist[0]->getId() != $contactBookId) {
	        		$this->responseArrayNew['form_status'] = 'error';
	        		$this->responseArrayNew['error_message'] = $this->get('translator')->trans('request_quote.shipping_type.email_already_exist');
	        		return new JsonResponse($this->responseArrayNew);
	        	}
	        	
	            $edit=$this->contactbookmanager->editContactBook($contactBookData,$this->changeAddressTypeFlag);
	            switch ($edit['status']) {
	        		case  'SUCCESS' :
	        			if ($this->erpIntegration && $this->erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager) ) {
	                        if($edit['data']->getErpId()){
	                            $this->queueApiManager->mapQueue("update", $edit['data']);
	                        }else{
	                            $this->queueApiManager->mapQueue("create", $edit['data']);
	                        }
	                    }
	                    $this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('user.contact_book.edit_message.address_success'));
	        			break;
	        		case  'FAIL':
	        			$this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('user.contact_book.edit_message.address_fail'));
	        			break;
	        	}
	        	if($this->request->isXmlHttpRequest ()){
	        		$this->responseArray['status'] = 'success';
	        		if(count($this->request->get('is_edit_from_payment'))>0 && $this->request->get('is_edit_from_payment')==1)
	        		{
	        			$this->responseArray['call_ajax_url_checkout'] = $this->generateUrl("office_brain_orderbundle_order_getcheckoutshippingaddressbyid");
	        		}
	        		else
	        		{
	        			$this->responseArray['call_ajax_url'] = $this->generateUrl("office_brain_requestquotebundle_requestquote_getshippingaddressbyid");
	        		}
	
	        		$this->responseArray['contact_book_id'] = $contactBookId;
	        		$this->responseArray['success_message'] = $this->get('translator')->trans('request_quote.shipping_type.edit_address_added_successfully');
	        		$counter = $this->request->get('counter',null); // Used for request Quote Edit Address
	        		if($counter!=null){
	        			$this->responseArray['counter'] = $counter;
	        		}
	        		return new JsonResponse($this->responseArray);
	        	}
	        	return $this->redirect($this->generateUrl("office_brain_userbundle_contactbook_viewcontactbook"));
	        }
	
	        if($this->request->isXmlHttpRequest ()){
	        	if ($this->request->get('call_type')=='country_code' || $this->request->get('call_type')=='state_code') {
	        		return $this->responseArray;
	        	} else {
	        		return new JsonResponse ( $this->prepareFormJsonError ($this->form) );
	        	}
	        }
	
	        return array('contactBookForm'=> $this->form->createView(),'contactBookId'=>$contactBookId);
        }else {
        	$this->exceptionManager->throwAccessException();
        	//throw new NotFoundHttpException('Sorry not existing!');
        }
    }



    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  contact book View
     *
     * @Route("{_locale}/my-account/address-book/view",
     * 	name="office_brain_userbundle_contactbook_viewcontactbook",
     *  options={"expose"=true}
     * )
     * @Method({"GET","POST"})
     * @Template("OfficeBrainUserBundle:ContactBook:viewContactBook.html.twig")
     */

    public function viewContactBookAction()
    {
        $this->initAction();
        $this->prepareSearchParameterArray();
        
        $this->responseArray['option'] = $this->request->get('option', null);
        $this->responseArray['keywords'] = $this->request->get('keywords', null);
        $this->responseArray['record_set'] = $this->contactbookmanager->getContactBook($this->userId, $this->addressBookFlag,$this->page,$this->recordsPerPage, $this->searchParameterArray);
        return $this->responseArray;
    }


    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  contact book Delete
     *
     * @Route("{_locale}/my-account/address-book/delete",
     * 	name="office_brain_userbundle_contactbook_deletecontactbook",
     *  options={"expose"=true}
     * )
     * @Template()
     */

    public function deleteContactBookAction()
    {
        $this->initAction();
        $contactBookArray = $this->contactbookmanager->getSingleContactBook($this->contactBookId);
        
        if($this->exceptionManager->isUserAllowedToAccess($contactBookArray->getCreatedUid(), $this->addressBookConfigrationField['allowed_users']))
        {
        	$contactBook = $this->contactbookmanager->deleteContactBook($this->contactBookId);
        	
        	switch ($contactBook['status']) {
	            case  'SUCCESS' :
	                if ($this->erpIntegration && $this->erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager)) {
	                    $this->queueApiManager->mapQueue("remove", array('id' => $this->contactBookId));
	                }
	                $this->responseArray['status'] = 'success';
	                //$this->responseArray['status_message'] = $this->get('translator')->trans('user.contact_book.remove_message.address_success');
	                $this->responseArray['page_url'] = $this->generateUrl('office_brain_userbundle_contactbook_viewcontactbook');
	                break;
	            case  'FAIL':
	                $this->responseArray['error_message'] = $this->translator->trans('user.contact_book.remove_message.address_fail');
	                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("{_locale}/my-account/address-book/is-default",
     * 	name="office_brain_userbundle_contactbook_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->translator->trans('user.contact_book.update_default.address_success');
                break;
            case  'FAIL':
                $this->responseArray['error_message'] = $this->translator->trans('user.contact_book.update_default.address_fail');
                break;
        }
        return new JsonResponse($this->responseArray);
    }
    
    

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - contact book form
     * @Route(
     *   "/{_locale}/mycontact-book/add/{userId}",
     *    name="office_brain_userbundle_mycontactbook_addcontactbook",
     *    options={"expose"=true},
     *    defaults={"userId"=0}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainUserBundle:ContactBook:addMyContactBook.html.twig")
     */
    
    public function addMyContactBookAction()
    {
    	$this->initActionMyContactBook();
    	$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(
     *    "/{_locale}/mycontact-book/add/{userId}",
     * 	  name="office_brain_userbundle_mycontactbook_addcontactbookpost",
     *    options={"expose"=true},
     *    defaults={"userId"=0}
     * )
     * @Method({"POST"})
     * @Template("OfficeBrainUserBundle:ContactBook:addMyContactBook.html.twig")
     */
    
    public function addMyContactBookPostAction()
    {
    	$this->initActionMyContactBook();
    	$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_mycontactbook_viewcontactbook"));
    				}else{
    					return $this->redirect($this->generateUrl("office_brain_userbundle_mycontactbook_viewcontactbook", array('userId'=>$userId)));
    				}
    				break;
    		}
    	}
    	$this->responseArray['contactBookForm'] = $this->form->createView();
    	return  $this->responseArray;
    }
    
    
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  contact book View
     *
     * @Route("/{_locale}/mycontact-book/view/{userId}",
     * 	name="office_brain_userbundle_mycontactbook_viewcontactbook",
     *  options={"expose"=true},
     *  defaults={"userId"=NULL}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainUserBundle:ContactBook:viewMyContactBook.html.twig")
     */
    
    public function viewMyContactBookAction()
    {
    	$this->initActionMyContactBook();
    
    	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(
     *   "/{_locale}/mycontact-book/view/popup/{id}",
     *    name="office_brain_userbundle_mycontactbook_viewcontactbookpopup",
     *    options={"expose"=true},
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainUserBundle:ContactBook:viewMyContactBookPopup.html.twig")
     */
    public function viewMyContactBookPopupAction()
    {
    	$this->initActionMyContactBook();
    	$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 -  contact book form
     * @Route(
     *   "/{_locale}/mycontact-book/edit/{contactBookId}",
     *    name="office_brain_userbundle_mycontactbook_editcontactbook",
     *    options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainUserBundle:ContactBook:editMyContactBook.html.twig")
     */
    
    public function editMyContactBookAction()
    {
    	$this->initActionMyContactBook();
    	$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("/{_locale}/mycontact-book/edit/{contactBookId}",
     * name="office_brain_userbundle_mycontactbook_editcontactbookpost",
     * options={"expose"=true}
     * )
     * @Method({"POST"})
     * @Template("OfficeBrainUserBundle:ContactBook:editMyContactBook.html.twig")
     */
    
    public function editMyContactBookPostAction()
    {
    	$this->initActionMyContactBook();
    	$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_mycontactbook_viewcontactbook"));
    					}else{
    						return $this->redirect($this->generateUrl("office_brain_userbundle_mycontactbook_viewcontactbook", 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 -   contact book Delete
     *
     * @Route("/{_locale}/mycontact-book/delete",
     * 	name="office_brain_userbundle_mycontactbook_deletecontactbook",
     *  options={"expose"=true}
     * )
     * @Template()
     */
    public function deleteMyContactBookAction()
    {
    	$this->initActionMyContactBook();
    	$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("/{_locale}/mycontact-book/is-default",
     * 	name="office_brain_userbundle_mycontactbook_isdefault",
     *  options={"expose"=true}
     * )
     * @Template()
     */
    
    public function isDefaultActionMyContactBookAction()
    {
    	$this->initActionMyContactBook();
    	$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));
    }
}
