<?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\CoreBundle\CustomeHandler as FormErrorManager;
use Symfony\Component\HttpFoundation\JsonResponse;
use OfficeBrain\Bundle\UserBundle\Entity\User;
use OfficeBrain\Bundle\UserBundle\Form\UserType;
use OfficeBrain\Bundle\UserBundle\Form\AssignServiceGroupType;
use OfficeBrain\Bundle\UserBundle\Form\ResetPasswordType;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

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

    public function __construct(ContainerInterface $container=null)
    {
        $this->request = null;
        $this->translator = null;
        $this->projectSetting = null;
        $this->projectUserSetting = null;
        $this->signUpConfigrations = null;
        $this->userConfigrations = null;
        $this->userAccess= null;
        $this->userId = null;
        $this->user = null;
        $this->coreManager = null;
        $this->signUpManager = null;
        $this->loginManager = null;
        $this->userManager = null;
        $this->formErrorManager = new FormErrorManager\JsonError();
        $this->activeStatus = null;
        $this->inactiveStatus = null;
        $this->responseArray = array();
        $this->queueApiManager = null;
        $this->searchParameterArray = array();
        $this->option = null;
        $this->keywords = null;
        $this->serviceGroupId = null;
        $this->requestStatus = null;
        $this->responseArray['total_active']=0;
    	$this->responseArray['total_inactive']=0;
    	$this->responseArray['total_approve']=0;
    	$this->responseArray['total_unapprove']=0;
    	$this->responseArray['total_pending']=0;
    	$this->responseArray['total_record'] = 0;

    }

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

    public function __destruct()
    {
        unset($this->request);
        unset($this->translator);
        unset($this->projectSetting);
        unset($this->projectUserSetting);
        unset($this->signUpConfigrations);
        unset($this->userConfigrations);
        unset($this->userAccess);
        unset($this->userId);
        unset($this->user);
        unset($this->coreManager);
        unset($this->signUpManager);
        unset($this->loginManager);
        unset($this->userManager);
        unset($this->formErrorManager);
        unset($this->activeStatus);
        unset($this->inactiveStatus);
        unset($this->responseArray);
        unset($this->queueApiManager);
        unset($this->searchParameterArray);
        unset($this->option);
        unset($this->keywords);
        unset($this->serviceGroupId);
        unset($this->requestStatus);
        unset($this->responseArray['total_active']);
    	unset($this->responseArray['total_inactive']);
    	unset($this->responseArray['total_approve']);
    	unset($this->responseArray['total_unapprove']);
    	unset($this->responseArray['total_pending']);
    	unset($this->responseArray['total_record']);
    }


    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->translator = $this->get('translator');
        $this->projectSetting = $this->request->get('project_setting');
        $this->projectUserSetting = $this->request->get('project_user_setting');
        $this->signUpConfigrations = $this->projectSetting['configuration_rule']['user']['sign_up'];
        $this->userConfigrations = $this->projectSetting['configuration_rule']['user']['user'];
        $this->userAccess= $this->projectSetting['access_rule']['user']['option']['user'];
        $this->coreManager = $this->get('office_brain_core_manager');
        $this->signUpManager = $this->get('office_brain_user_sign_up_manager');
        $this->loginManager = $this->get('office_brain_user_login_manager');
        $this->userManager = $this->get('office_brain_user_manager');
        $this->userId = $this->projectSetting['user_id'];
        $this->user = $this->projectUserSetting['user_data'];
        $this->requestUserType =  $this->request->get('userType', null);
        $this->signUpFormFields = $this->signUpManager->getsignUpFormData($this->requestUserType);
        $this->requestStatus = $this->request->get('status',null);
        $this->requestUserStatusTab = $this->request->get('userStatusTab','requested');
        $this->option = $this->request->get('option',null);
        $this->keywords = $this->request->get('keywords',null);
        $this->searchFlag = $this->request->get('searchFlag',null);
        $this->page = $this->request->get('page', '1');
        $this->recordsPerPage = $this->request->get('records_per_page', $this->userConfigrations['no_of_record_per_page']);
        $this->userCountFlag = '1';
        $this->instanceType = $this->projectSetting['instance_type'];
        $this->instanceId = $this->projectSetting['instance_id'];
        $this->serviceGroupId = null;
        $this->responseArray['userType'] = $this->requestUserType ;
        $this->responseArray['form_fields'] = $this->signUpFormFields ;
        $this->responseArray['states'] = $this->coreManager->getStateData();
        $this->responseArray['distributors'] = array();
//         $this->responseArray['distributors'] = $this->userManager->getDistributors();
        $this->responseArray['records_per_page'] = $this->recordsPerPage;
        $this->responseArray['page'] = $this->page;
        $this->responseArray['field'] = $this->userConfigrations;
        $this->responseArray['accessField'] = $this->userAccess;
        $this->responseArray['requestUserStatusTab'] = $this->requestUserStatusTab;
        $this->responseArray['instanceType'] = $this->instanceType;
        $this->formErrorManager = new FormErrorManager\JsonError();
        $this->activeStatus = '1';
        $this->inactiveStatus = '0';
        if ($this->has('office_brain_queue_api_manager')) {
            $this->request->attributes->set('object', 'User');
            $this->queueApiManager = $this->get('office_brain_queue_api_manager');
        }
        $this->exceptionManager = $this->get('access_authorized_exception');
    }


    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - admin User form
     * @Route(
     *   "admin/{_locale}/user/add-user",
     *    name="office_brain_userbundle_adminuser_adduser",
     *    options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainUserBundle:AdminUser:addAdminUser.html.twig")
     */
    public function addUserAction()
    {
        $this->initAction();
        $userType = 'end_user';
        $form = $this->createForm(new UserType($this->coreManager, $this->signUpFormFields ,'admin_add'), new User());
        $form->handleRequest($this->request);
        $this->responseArray['form_user'] = $form->createView();
        $this->responseArray['userType'] = $userType;

        return $this->responseArray;
    }


    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - admin User form
     * @Route(
     *   "admin/{_locale}/user/add-user",
     *    name="office_brain_userbundle_adminuser_addadminuser",
     *    options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainUserBundle:AdminUser:addAdminUser.html.twig")
     */

    public function addAdminUserAction()
    {
        $this->initAction();
        $userType = 'end_user';
        $form = $this->createForm(new UserType($this->coreManager, $this->signUpFormFields ,'admin_add'),  new User());
        $form->handleRequest($this->request);
        $this->responseArray['form_user'] = $form->createView();
        $this->responseArray['userType'] = $userType;

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - admin User form
     * @Route(
     *   "admin/{_locale}/user/add-supplier",
     *    name="office_brain_userbundle_adminuser_addadminuser_supplier",
     *    options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainUserBundle:AdminUser:addAdminUser.html.twig")
     */

    public function addAdminSupplierUserAction()
    {
        $this->initAction();
        $data = array();
        $userType = 'supplier';
        $signUpFormFields = $this->signUpManager->getsignUpFormData($userType);

        $user = new User();
        $userTypeObj = new UserType($this->coreManager, $signUpFormFields,'admin_add');
        $form = $this->createForm($userTypeObj, $user);
        $form->handleRequest($this->request);
        $data['form_user'] = $form->createView();
        $data['userType'] = $userType;
        $data['form_fields'] = $signUpFormFields;
        $data['states'] = $this->coreManager->getStateData();
        $data['distributors'] = $this->userManager->getDistributors();

        return $data;
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - admin User form
     * @Route(
     *   "admin/{_locale}/user/add-distributor",
     *    name="office_brain_userbundle_adminuser_addadminuser_distributor",
     *    options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainUserBundle:AdminUser:addAdminUser.html.twig")
     */

    public function addAdminDistributorUserAction()
    {
        $this->initAction();
        $data = array();
        $userType = 'distributor';
        $signUpFormFields = $this->signUpManager->getsignUpFormData($userType);
        $user = new User();
        $userTypeObj = new UserType($this->coreManager, $signUpFormFields,'admin_add');
        $form = $this->createForm($userTypeObj, $user);
        $form->handleRequest($this->request);
        $data['form_user'] = $form->createView();
        $data['userType'] = $userType;
        $data['form_fields'] = $signUpFormFields;
        $data['states'] = $this->coreManager->getStateData();
        $data['distributors'] = $this->userManager->getDistributors();

        return $data;
    }


    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  User form post submit
     *
     * @Route(
     *    "admin/{_locale}/user/add",
     * 	  name="office_brain_userbundle_adminuser_addadminuserpost",
     *    options={"expose"=true}
     * )
     * @Method({"POST"})
     * @Template("OfficeBrainUserBundle:AdminUser:addAdminUser.html.twig")
     */

    public function addAdminUserPostAction()
    {
        $this->initAction();
        $data = array();
        $userType = $this->request->get('userType', 'supplier');
        $signUpFormFields = $this->signUpManager->getsignUpFormData($userType);

        $user = new User();
        $userTypeObj = new UserType($this->coreManager, $signUpFormFields,'admin_add');

        $form = $this->createForm($userTypeObj, $user);
        $form->handleRequest($this->request);

        $userStatus = $this->userManager->addAdminUser($form);

        if ($userStatus)
        {
            $erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
            $erp_flag = TRUE;
            $user_type = $userStatus->getUserType();
            $is_individual = $userStatus->getIsIndividual();
            if ((($user_type == 'end_user' || $user_type == 'supplier') && $this->projectSetting['instance_type'] == 'supplier') || ($is_individual == TRUE && $this->projectSetting['instance_type'] == 'supplier')) {
                $erp_flag = FALSE;
            }
            if ($erp_flag == TRUE && $userStatus->getUserType() != 'end_user' && empty($userStatus->getUserCompany())) {
                $erp_flag = FALSE;
            }
            if ($erpIntegration && $erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager) && $erp_flag == TRUE && ($userStatus->getStatus()=="active" || $userStatus->getStatus()=="inactive")) {
                $this->queueApiManager->mapQueue("create", $userStatus);
            }
            //if ($this->request->get('billing_address')) {
                //$billingArray['id'] = 1;$billingArray['default'] = $this->request->get('billing_address',null);
                $billingAddressId = 1;
                $billingAddress = $this->signUpManager->addAddress($user,$billingAddressId);
                if ($erpIntegration && $erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager) && $erp_flag == TRUE &&  ($userStatus->getStatus()=="active" || $userStatus->getStatus()=="inactive")) {
                    $this->request->attributes->set('object', 'ContactBook');
                    $this->queueApiManager->mapQueue("create", $billingAddress);
                }
            //}
            //if ($this->request->get('shipping_address')) {
                //$shippingArray['id'] = 2; $shippingArray['default'] = $this->request->get('shipping_address',null);
                $shippingAddressId = 2;
                $shippingAddress = $this->signUpManager->addAddress($user, $shippingAddressId);
                if ($erpIntegration && $erpIntegration['userManagement'] == 1  && !empty($this->queueApiManager) && $erp_flag == TRUE && ($userStatus->getStatus()=="active" || $userStatus->getStatus()=="inactive")) {
                    $this->request->attributes->set('object', 'ContactBook');
                    $this->queueApiManager->mapQueue("create", $shippingAddress);
                }
            //}
            $this->signUpManager->sendEmail($form, $this->translator->trans('user.register.mail.subject'));

            if ($signUpFormFields['approval_configuration']['is_auto_approve']->option->approval_email==1) {
            	$this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('user.add_message.success_msg'));
            } else {
            	$this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('user.add_message.success_msg'));
            }
            return $this->redirect($this->generateUrl('office_brain_userbundle_adminuser_viewadminuser'));
        }


        $data['form_user'] = $form->createView();
        $data['userType'] = $userType;
        $data['form_fields'] = $signUpFormFields;
        $data['states'] = $this->coreManager->getStateData();
        $data['distributors'] = $this->userManager->getDistributors();


        if ($this->request->isXmlHttpRequest()) {
            if ($this->request->get('call_type')=='country_code' || $this->request->get('call_type')=='state_code') {
                return $data;
            } else {
                $errors = array(
                        'form_name' => $form->getName(),
                        'form_status' => 'error',
                        'form_errors' => $this->formErrorManager->prepareErrorArray($this->get('validator')->validate($form))
                );
                return new JsonResponse($errors);
            }
        }
        return $data;
    }



    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  Admin User List
     *
     * @Route("admin/{_locale}/user/view",
     * 	name="office_brain_userbundle_adminuser_viewadminuser",
     *  options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainUserBundle:AdminUser:viewAdminUser.html.twig")
     */

    public function viewAdminUserAction()
    {
       $this->initAction();
       $this->getUserCountByTypeAction();
       $this->responseArray['record_set'] = $this->userManager->getAdminAllUsers($this->userId,$this->requestUserStatusTab,$this->page, $this->recordsPerPage,$this->searchParameterArray,$this->requestUserType,$this->requestStatus);

       if ($this->searchFlag == '1') {
	      $this->responseArray['html'] = $this->renderView('OfficeBrainUserBundle:AdminUser:viewAdminUser.html.twig', $this->responseArray);
	      return new JsonResponse($this->responseArray);
       }

       return $this->responseArray;
    }


    /** @author  4493
     * OB eCommerce Product - For get count of active or inactive status
     */
    public function getUserCountByTypeAction()
    {
    	$this->initAction();
    	$this->prepareSearchParameterArray();
    	$this->responseArray['count_record_set']= $this->userManager->getAdminAllUsersCount($this->userId,$this->requestUserStatusTab,$this->userCountFlag,$this->page, $this->recordsPerPage,$this->searchParameterArray,$this->requestUserType);
    	foreach ($this->responseArray['count_record_set'] as $key=>$val){
    		if($val['status'] == 'active'){
    			$this->responseArray['total_active'] = $val[1];
    		}
    		if($val['status'] == 'inactive'){
    			$this->responseArray['total_inactive'] = $val[1];
    		}
    		if($val['status'] == 'approve'){
    			$this->responseArray['total_approve'] = $val[1];
    		}
    		if($val['status'] == 'unapprove'){
    			$this->responseArray['total_unapprove'] = $val[1];
    		}
    		if($val['status'] == 'pending'){
    			$this->responseArray['total_pending'] = $val[1];
    		}
    		$this->responseArray['total_record'] = $this->responseArray['total_pending']+$this->responseArray['total_unapprove']+$this->responseArray['total_approve']+$this->responseArray['total_active']+$this->responseArray['total_inactive'];
    	}
    }


    /**
     * @author : 4493)
     * OB eCommerce Product - get single record of user
     * @Route(
     *   "admin/{_locale}/user/view/popup/{userId}",
     *    name="office_brain_companybundle_company_viewadminuserpopup",
     *    options={"expose"=true},
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainUserBundle:AdminUser:viewAdminUserPopup.html.twig")
     */
    public function viewAdminUserPopupAction()
    {
    	$this->initAction();
    	$userId = $this->request->get('userId');
    	$userObj=$this->userManager->getUserById($userId);
    	if($this->exceptionManager->isUserAllowedToAccess($userObj->getCreatedUid(), $this->userConfigrations['allowed_users']))
    	{
    		$userType = $userObj->getUserType();
	    	$signUpFormFields = $this->signUpManager->getsignUpFormData($userType);
	    	$data['items'] = $userObj;
	    	$data['form_fields'] = $signUpFormFields;
	    	return $data;
    	}else {
    		$this->exceptionManager->throwAccessException();
    		//throw new NotFoundHttpException('Sorry not existing!');
    	}


    }




    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - admin User form edit
     * @Route(
     *   "admin/{_locale}/user/edit/{userId}",
     *    name="office_brain_userbundle_adminuser_editadminuser",
     *    options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainUserBundle:AdminUser:editAdminUser.html.twig")
     */

    public function editAdminUserAction()
    {
        $this->initAction();
        $data = array();
        $userId = $this->request->get('userId');
        $user = $this->userManager->getUserById($userId);

        if($this->exceptionManager->isUserAllowedToAccess($user->getCreatedUid(), $this->userConfigrations['allowed_users']))
        {

	        $userType = $user->getUserType();
	        $signUpFormFields = $this->signUpManager->getsignUpFormData($userType);

	        $userTypeObj = new UserType($this->coreManager, $signUpFormFields, 'admin_edit');
	        $form = $this->createForm($userTypeObj, $user);
	        $form->handleRequest($this->request);
	        $data['form_user'] = $form->createView();
	        $data['form_fields'] = $signUpFormFields;
	        $data['states'] = $this->coreManager->getStateData();
	        $data['distributors'] = $this->userManager->getDistributors();
	        $data['userId'] = $userId;
	        return $data;
        }else {
        	$this->exceptionManager->throwAccessException();
        	//throw new NotFoundHttpException('Sorry not existing!');
        }

    }




    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - admin User form edit
     * @Route(
     *   "admin/{_locale}/user/edit/{userId}",
     *    name="office_brain_userbundle_adminuser_editadminuserpost",
     *    options={"expose"=true}
     * )
     * @Method({"POST"})
     * @Template("OfficeBrainUserBundle:AdminUser:editAdminUser.html.twig")
     */

    public function editAdminUserPostAction()
    {
        $this->initAction();
        $data = array();

        $userId = $this->request->get('userId');
        $user = $this->userManager->getUserById($userId);

        if($this->exceptionManager->isUserAllowedToAccess($user->getCreatedUid(), $this->userConfigrations['allowed_users']))
        {
		        $userType = $user->getUserType();

		        $signUpFormFields = $this->signUpManager->getsignUpFormData($userType);
		        $userTypeObj = new UserType($this->coreManager, $signUpFormFields, 'admin_edit');
		        $form = $this->createForm($userTypeObj, $user);
		        $form->handleRequest($this->request);
            if ($_POST['membership_id']=='')
		        {
		        	$this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('Please Enter Membership Id'));
		        	return $this->redirect($this->request->getUri().'?=1');
		        }

		        $userStatus = $this->userManager->editUser($form);

		        if ($userStatus) {
		            $erp_flag = TRUE;
		            $is_individual = $userStatus->getIsIndividual();
		            $erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
		            if ((($userStatus->getUserType() == 'end_user' || $userStatus->getUserType() == 'supplier' ) && $this->projectSetting['instance_type'] == 'supplier') || ($is_individual == TRUE && $this->projectSetting['instance_type'] == 'supplier')) {
		                $erp_flag = FALSE;
		            }
                    if ($erp_flag == TRUE && $userStatus->getUserType() != 'end_user' && empty($userStatus->getUserCompany())) {
                        $erp_flag = FALSE;
                    }
		            if ($erpIntegration && $erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager) && $erp_flag == TRUE && ($userStatus->getStatus()=="active" || $userStatus->getStatus()=="inactive")) {
		                if ($userStatus->getErpId()) {
		                    $action = 'update';
		                } else {
		                    $action = 'create';
		                }
		                $this->queueApiManager->mapQueue($action, $userStatus);
		            }
		            if ($this->request->get('billing_address') && ($userStatus->getStatus()=="active" || $userStatus->getStatus()=="inactive")) {
		                //$billingArray['id'] = 1;$billingArray['default'] = $this->request->get('billing_address',null);
		                $billingAddressId = 1;
		                $billingAddress = $this->signUpManager->addAddress($user, $billingAddressId);
		                if ($erpIntegration && $erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager) && $erp_flag == TRUE) {
		                    $this->request->attributes->set('object', 'ContactBook');
		                    $this->queueApiManager->mapQueue($action, $billingAddress);
		                }
		            }
		            if ($this->request->get('shipping_address') && ($userStatus->getStatus()=="active" || $userStatus->getStatus()=="inactive")) {
		                //$shippingArray['id'] = 2;$shippingArray['default'] = $this->request->get('shipping_address',null);
		                $shippingAddressId = 2;
		                $shippingAddress = $this->signUpManager->addAddress($user, $shippingAddressId);
		                if ($erpIntegration && $erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager) && $erp_flag == TRUE) {
		                    $this->request->attributes->set('object', 'ContactBook');
		                    $this->queueApiManager->mapQueue($action, $shippingAddress);
		                }
		            }
		            $this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('user.edit_message.success_msg'));

		            return $this->redirect($this->generateUrl('office_brain_userbundle_adminuser_viewadminuser'));
		        }
		        $data['form_user'] = $form->createView();
		        $data['form_fields'] = $signUpFormFields;
		        $data['states'] = $this->coreManager->getStateData();
		        $data['distributors'] = $this->userManager->getDistributors();
		        $data['userId'] = $userId;
		        if ($this->request->isXmlHttpRequest()) {
		            if ($this->request->get('call_type')=='country_code' || $this->request->get('call_type')=='state_code') {
		                return $data;
		            } else {
		                $errors = array(
		                        'form_name' => $form->getName(),
		                        'form_status' => 'error',
		                        'form_errors' => $this->formErrorManager->prepareErrorArray($this->get('validator')->validate($form))
		                );
		                return new JsonResponse($errors);
		            }
		        }
		        return $data;
        }else {
        	$this->exceptionManager->throwAccessException();
        	//throw new NotFoundHttpException('Sorry not existing!');
        }
    }




    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  Admin User Delete
     *
     * @Route("admin/{_locale}/user/delete",
     * 	name="office_brain_userbundle_adminuser_deleteadminuser",
     *  options={"expose"=true}
     * )
     * @Template()
     */

    public function deleteUserAction()
    {
        $this->initAction();
        $userId = $this->request->get('id');
        $user = $this->userManager->getUserById($userId);

        if($this->exceptionManager->isUserAllowedToAccess($user->getCreatedUid(), $this->userConfigrations['allowed_users']))
        {

        	$userStatus = $this->userManager->deleteUser($userId);
        	$this->getUserCountByTypeAction();
        	switch ($userStatus['status']) {
        		case  'SUCCESS' :

        			$userObj = $userStatus['data'];
        			$is_individual = $userObj->getIsIndividual();
        			$erp_flag = TRUE;
        			$erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
        			if ((($userObj->getUserType() == 'end_user' || $userObj->getUserType() == 'supplier') && $this->projectSetting['instance_type'] == 'supplier') || ($is_individual == TRUE && $this->projectSetting['instance_type'] == 'supplier')) {
        				$erp_flag = FALSE;
        			}
                    if ($erp_flag == TRUE && $userObj->getUserType() != 'end_user' && empty($userObj->getUserCompany())) {
                        $erp_flag = FALSE;
                    }
        			if ($erpIntegration && $erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager) ) {
                        if ($userObj->getErpId() && $erp_flag == TRUE && ($userObj->getStatus()=="active" || $userObj->getStatus()=="inactive")) {
                            $this->queueApiManager->mapQueue("remove", array('id' =>$userId, 'deleted_at'=> $userObj->getDeletedAt()->format('Y-m-d H:i:s')));
                        } else {
                            if($erp_flag == TRUE && ($userObj->getStatus()=="active" || $userObj->getStatus()=="inactive")){
                                $this->queueApiManager->mapQueue("create", $userObj);
                            }
                        }
                    }
        			$this->responseArray['status'] = 'success';
        			$this->responseArray['success_message'] = $this->get('translator')->trans('user.remove_message.success_msg');
        			//$this->responseArray['page_url'] = $this->generateUrl('office_brain_userbundle_adminuser_viewadminuser');
        			break;
        		case  'FAIL':
        			$this->responseArray['error_message'] = $this->get('translator')->trans('user.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 -  Admin User Status Update
     *
     * @Route("admin/{_locale}/user/update-status/{userId}",
     * 	name="office_brain_userbundle_adminuser_updatestatus",
     *  options={"expose"=true}
     * )
     * @Template()
     */

    public function updateStatusAction()
    {
        $this->initAction();
        $userId = $this->request->get('userId');
        $user = $this->userManager->getUserById($userId);

        if($this->exceptionManager->isUserAllowedToAccess($user->getCreatedUid(), $this->userConfigrations['allowed_users']))
        {
        	$ObCustomerIdConfirm = false;
        	$userType = $user->getUserType();

        	$signUpFormFields = $this->signUpManager->getsignUpFormData($userType);
        	$obCustomerIdOption = (array) $signUpFormFields['fields']['obCustomerId'];

        	if($obCustomerIdOption['admin']==1) {
        		$ObCustomerIdConfirm = $this->request->get('ObCustomerIdConfirm');
        	}
        	$userStatus = $this->userManager->updateUserStatus($userId, $this->requestStatus,$ObCustomerIdConfirm);
        	$this->getUserCountByTypeAction();
        	switch ($userStatus['status']) {
        		case  'SUCCESS' :
        			$userObj = $userStatus['data'];
        			$is_individual = $userObj->getIsIndividual();
        			$erp_flag = TRUE;
        			if (($userObj->getUserType() == 'end_user' || $userObj->getUserType() == 'supplier')  && ($this->projectSetting['instance_type'] == 'supplier') || ($is_individual == TRUE && $this->projectSetting['instance_type'] == 'supplier')) {
        				$erp_flag = FALSE;
        			}
                    if ($erp_flag == TRUE && $userObj->getUserType() != 'end_user' && empty($userObj->getUserCompany())) {
                        $erp_flag = FALSE;
                    }
        			$erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
        			if ($erpIntegration && $erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager)) {
        				if ($userObj->getErpId() && $erp_flag == TRUE && ($userObj->getStatus() == "active" || $userObj->getStatus() == "inactive")) {
        					$this->queueApiManager->mapQueue("updateStatus", array('id' =>$userId, 'status'=> $this->requestStatus));
        				} else {
        					if($erp_flag == TRUE && ($userObj->getStatus() == "active" || $userObj->getStatus() == "inactive" ) ){
        						$billingAddressBook = $this->signUpManager->getAddressBookofUser($userObj->getId(), 1);
        						$shippingAddressBook = $this->signUpManager->getAddressBookofUser($userObj->getId(), 2);
        						$this->queueApiManager->mapQueue("create", $userObj);
        						$this->request->attributes->set('object', 'ContactBook');
        						$this->queueApiManager->mapQueue("create", $billingAddressBook);
        						$this->queueApiManager->mapQueue("create", $shippingAddressBook);
        					}
        				}
        			}
        			$this->userManager->sendStatusChangeEmailToUser($userId);
        			$this->responseArray['status'] = 'success';
        			$this->responseArray['status_value'] = $this->requestStatus;
        			$this->responseArray['status_message'] = $this->get('translator')->trans('user.update_status.success_msg');
        			break;
        		case  'NOT MATCH':
        			$this->responseArray['status'] = 'error';
        			$this->responseArray['error_message'] = $this->get('translator')->trans('user.update_status.not_match');
        			break;
        		case  'FAIL':
        			$this->responseArray['status'] = 'error';
        			$this->responseArray['error_message'] = $this->get('translator')->trans('user.update_status.fail_msg');
        			break;
        	}
        	return new JsonResponse($this->responseArray);
        }else {
        	$this->exceptionManager->throwAccessException();
        	//throw new NotFoundHttpException('Sorry not existing!');
        }
    }



    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Login
     * Function created to show reset password
     *
     * @Route("admin/{_locale}/reset-password/{user_id}",
     * 	name="office_brain_userbundle_admin_user_reset_password",
     *  options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainUserBundle:AdminUser:resetPassword.html.twig")
     */

    public function resetPasswordAction($user_id)
    {
        $this->initAction();
        $data = array();
        $id = $user_id;
        $user = $this->userManager->getUserById($id);
        if($this->exceptionManager->isUserAllowedToAccess($user->getCreatedUid(), $this->userConfigrations['allowed_users']))
        {

        	$data['user_id'] = $user_id;
        	if ($user) {
        		$form = $this->createForm(new ResetPasswordType());
        		$data['form'] = $form->createView();
        	} else {
        		$data['error'] = $this->translator->trans('user.admin_reset_password.not_exists');
        	}
        	return $data;
        }else {
        	$this->exceptionManager->throwAccessException();
        	//throw new NotFoundHttpException('Sorry not existing!');
        }
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Login
     * Function created to reset Password
     *
     * @Route("admin/{_locale}/reset-password/{user_id}",
     * 	name="office_brain_userbundle_admin_user_reset_password_check",
     *  options={"expose"=true}
     * )
     * @Method({"POST"})
     * @Template("OfficeBrainUserBundle:AdminUser:resetPassword.html.twig")
     */
    public function resetPasswordCheckAction($user_id)
    {
        $this->initAction();
        $data = array();
        $id = $user_id;
        $user = $this->userManager->getUserById($id);
        if($this->exceptionManager->isUserAllowedToAccess($user->getCreatedUid(), $this->userConfigrations['allowed_users']))
        {

	        $form = $this->createForm(new ResetPasswordType());
	        $form->handleRequest($this->request);
	        $data['user_id'] = $user_id;

	        if ($form->isValid()) {
	            $process = $this->loginManager->doResetPasswordProcess($form->getData(), $user, $this->translator->trans('user.admin_reset_password.email_subject'));

	            $data['success'] = $this->translator->trans('user.admin_reset_password.success');
	            return new JsonResponse($data);
	        }
	        $data['form'] = $form->createView();
	        return $data;
        }else {
        	$this->exceptionManager->throwAccessException();
        	//throw new NotFoundHttpException('Sorry not existing!');
        }
    }


    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - assign Service Group to user
     * @Route(
     *   "admin/{_locale}/user/assign-service-group/{userId}",
     *    name="office_brain_userbundle_adminuser_assignServiceGroup",
     *    options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template()
     */

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

    	$userId = $this->request->get('userId','');
    	$user = $this->userManager->getUserById($userId);

    	if($this->exceptionManager->isUserAllowedToAccess($user->getCreatedUid(), $this->userConfigrations['allowed_users']))
    	{


	    	if(is_object($user->getServiceGroup()) && $user->getServiceGroup()->getId() != ''){
	    		$this->serviceGroupId = $user->getServiceGroup()->getId();
	    	}
	    	if ($user) {
	    		$form = $this->createForm(new AssignServiceGroupType($this->container, $user->getCountryId(), $this->serviceGroupId));
	    		$this->responseArray['form'] = $form->createView();
	    	} else {
	    		$this->responseArray['error'] = $this->translator->trans('user.service_group.not_exist');
	    	}
	    	$this->responseArray['userId'] = $userId;
	    	return $this->responseArray;
    	}else {
    		$this->exceptionManager->throwAccessException();
    		//throw new NotFoundHttpException('Sorry not existing!');
    	}

    }


    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - assign Service Group to user
     * @Route(
     *   "admin/{_locale}/user/assign-service-group-post/{userId}",
     *    name="office_brain_userbundle_adminuser_assignServiceGrouppost",
     *    options={"expose"=true}
     * )
     * @Method({"POST"})
     * @Template("OfficeBrainUserBundle:AdminUser:assignServiceGroup.html.twig")
     */


    public function assignServiceGroupPostAction()
    {
    	$this->initAction();
    	unset($this->responseArray); // no need of other responsearray which define in initAction

    	$userId = $this->request->get('userId','');
    	$user = $this->userManager->getUserById($userId);
    	if($this->exceptionManager->isUserAllowedToAccess($user->getCreatedUid(), $this->userConfigrations['allowed_users']))
    	{
	    	$form = $this->createForm(new AssignServiceGroupType($this->container,$user->getCountryId(),$this->serviceGroupId));
	    	$form->handleRequest($this->request);

	    	if ($form->isValid()) {
	    		$serviceGroupId = $form->getData()['serviceGroup'];
	    		$process = $this->userManager->assignAccessGroup($serviceGroupId, $user);
	    		$this->responseArray['success'] = $this->translator->trans('user.service_group.success');
	    		return new JsonResponse($this->responseArray);
	    	}
	    	else{
	    		$this->responseArray['error'] = $this->translator->trans('user.service_group.not_blank');
	    	}
	    	if ($this->request->isXmlHttpRequest()) {
	    		return new JsonResponse($this->responseArray);
	    	}
	    	$this->responseArray['userId'] = $userId;
	    	$this->responseArray['form'] = $form->createView();
	    	return $this->responseArray;
    	}else {
    		$this->exceptionManager->throwAccessException();
    		//throw new NotFoundHttpException('Sorry not existing!');
    	}
    }

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


    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - find ob customer id
     * @Route(
     *   "admin/{_locale}/user/find-ob-customer-id/{userId}",
     *    name="office_brain_userbundle_adminuser_findobcustomerid",
     *    options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainUserBundle:AdminUser:findObCustomerId.html.twig")
     */

    public function findObCustomerIdAction()
    {
    	$this->initAction();
    	$userId = $this->request->get('userId','');
    	$this->responseArray['obCustomerIdList'] = $this->userManager->findObCustomerIdFromApi($userId);
    	$this->responseArray['userId'] = $userId;
    	return $this->responseArray;
    }

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - find ob customer id
     * @Route(
     *   "admin/{_locale}/user/create-new-ob-customer-id/{userId}",
     *    name="office_brain_userbundle_adminuser_createnewobcustomerid",
     *    options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template()
     */

    public function createNewObCustomerIdAction()
    {
    	$this->initAction();
    	$userId = $this->request->get('userId','');
    	$this->responseArray['obCustomerId'] = '';
    	$userArrayFromApi = $this->userManager->createNewObCustomerIdFromApi($userId);

    	if($userArrayFromApi['dataObj']['ob_customer_id'] && $userArrayFromApi['dataObj']['ob_customer_id'] !=''){
    		$this->responseArray['obCustomerId'] = $userArrayFromApi['dataObj']['ob_customer_id'];
    		$this->responseArray['status'] = 'SUCCESS';
    		$this->responseArray['success_message'] = $this->translator->trans('user.admin_user.create_ob_customer_id.success_message');
    		return new JsonResponse($this->responseArray);
    	}else{
    		$this->responseArray['status'] = 'ERROR';
    		$this->responseArray['error_message'] = $this->translator->trans('user.admin_user.create_ob_customer_id.fail_message');
    	}
    	return new JsonResponse($this->responseArray);

    }

    /**
     * @author Employee Id: 4246
     * OB eCommerce Product - Export User
     * @Route(
     *   "admin/{_locale}/user/export-users",
     *    name="office_brain_userbundle_adminuser_export",
     *    options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template()
     */

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

        $userData = $this->userManager->userListForExport();
        if(!empty($userData) ){
            $titles = array_keys($userData[0]);
        }else{
            $this->responseArray['status'] = 'error';
            $this->responseArray['error_message'] = 'Record Not Found';
            return new JsonResponse($this->responseArray);
        }

        $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
        $phpExcelObject->getProperties()->setCreator("OfficeBrain")
        ->setLastModifiedBy("OfficeBrain")
        ->setTitle("Office 2005 XLSX User Data Document")
        ->setSubject("Office 2005 XLSX User Data Document")
        ->setDescription("This is Document Contains User Data")
        ->setKeywords("office 2005 openxml php")
        ->setCategory("User Data");

        $phpExcelObject->getActiveSheet()->setTitle('Users');
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $phpExcelObject->setActiveSheetIndex(0);

        if($titles){
            $column = 'A';
            foreach($titles as $title){
                $cellName = $column.'1';
                $phpExcelObject->getActiveSheet()->setCellValueExplicit($cellName, $title);
                $phpExcelObject->getActiveSheet()->getStyle("$cellName:$cellName")->getFont()->setSize(10)->setBold(true);
                $column++;
            }
        }

        $i=2;
        foreach ($userData as $values) {
            $column = 'A';
            foreach ($values as $index=>$label) {
                /* 6799: Add TimeStamp */
                if($index == "RegistrationTimestamp"){
                    $label = $label->format('Y-m-d H:i:s');
                }
                /* EO: 6799: Add TimeStamp */
                $cellName = $column.$i;
                $phpExcelObject->getActiveSheet()->setCellValueExplicit($cellName, $label);
                $column++;
            }
            $i++;
        }

        // create the writer
        $writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel5');
        // create the response
        $response = $this->get('phpexcel')->createStreamedResponse($writer);
        // adding headers
        $dispositionHeader = $response->headers->makeDisposition(
            ResponseHeaderBag::DISPOSITION_ATTACHMENT,
            'user-data-'.date("d-m-y").'.xls'
            );
        $response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8');
        $response->headers->set('Pragma', 'public');
        $response->headers->set('Cache-Control', 'maxage=1');
        $response->headers->set('Content-Disposition', $dispositionHeader);

        return $response;
    }

}
