<?php 
namespace OfficeBrain\Bundle\CompanyBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Form\FormError;
use OfficeBrain\Bundle\CompanyBundle\Manager\Extended;
use OfficeBrain\Bundle\CompanyBundle\Entity\Company;
use OfficeBrain\Bundle\CompanyBundle\Form\CompanyType;
use OfficeBrain\Bundle\CompanyBundle\Entity\Employee;
use OfficeBrain\Bundle\CompanyBundle\Form\EmployeeType;
use OfficeBrain\Bundle\UserBundle\Entity\User;
use OfficeBrain\Bundle\UserBundle\Form\UserType;
use OfficeBrain\Bundle\UserBundle\Entity\EmployeeInfo;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

/**
 *
 * @author 4488
 * @Route("admin/{_locale}/")
 */
class CompanyController extends Controller
{
    /**
     * @author Employee Id: 4493
     * Modification of company
     */
    
    public function __construct(ContainerInterface $container=null)
    {
        $this->entityManager=null;
        $this->companyManager=null;
        $this->coreManager=null;
        $this->request=null;
        $this->responseArray['status']=null;        
        $this->projectSetting=null;
        $this->location=null;
        $this->logoUrl =null;
        $this->companyAccessField=null;
        $this->companyConfigurationField=null;
        $this->companyLogoParameter=null;
        $this->per_page=null;
        $this->erpConfigrationField = null;
        $this->employeeConfigrationsField = null;
        $this->employeeAccessField= null;
        $this->signUpManager = null;
        $this->userManager = null;
        $this->translator = null;
        $this->session= null;
        $this->queueApiManager = null;
        $this->activeStatus = null;
        $this->inactiveStatus = null;
        $this->countFlagForView = null;
        $this->countFlagForStatus = null;
        $this->searchParameterArray = array();
        $this->responseArray['total_active'] = 0;
        $this->responseArray['total_inactive'] = 0;
        $this->responseArray['total_record'] = 0;
        $this->option = null;
        $this->keywords = null;        
    }

    public function __destruct()
    {
        unset($this->entityManager);
        unset($this->companyManager);
        unset($this->coreManager);
        unset($this->request);
        unset($this->responseArray['status']);
        unset($this->projectSetting);
        unset($this->location);
        unset($this->logoUrl);
        unset($this->companyAccessField);
        unset($this->companyConfigurationField);
        unset($this->companyLogoParameter);
        unset($this->per_page);        
        unset($this->erpConfigrationField);
        unset($this->employeeConfigrationsField);
        unset($this->employeeAccessField);
        unset($this->signUpManager);
        unset($this->userManager);
        unset($this->translator);
        unset($this->session);
        unset($this->queueApiManager);
        unset($this->activeStatus);
        unset($this->inactiveStatus);
        unset($this->countFlagForView);
        unset($this->countFlagForStatus);
        unset($this->searchParameterArray);
        unset($this->responseArray['total_active']);
        unset($this->responseArray['total_inactive']);
        unset($this->responseArray['total_record']);
        unset($this->option);
        unset($this->keywords);
    }
    

    private function prepareFormJsonError()
    {
        return array(
                'form_name' => $this->form->getName(),
                'form_status' => 'error',
                'form_errors' => $this->formErrorManager->prepareErrorArray($this->get('validator')->validate($this->form))
        );
    }
    
    
    public function initAction()
    {
    	$this->request=$this->getRequest();
    	$this->session= $this->request->getSession();
    	$this->entityManager = $this->getDoctrine()->getEntityManager();    	
    	$this->location=$this->get('kernel')->getRootDir().'/../web/images/uploads/';
    	$this->logoUrl = $this->request->getScheme().'://'.$this->request->getHttpHost().$this->request->getBasePath().'/images/uploads/company_logo/';    	
    	$this->translator = $this->get('translator');    	
    	$this->projectSetting=$this->request->get('project_setting');
    	$this->projectUserSetting = $this->request->get('project_user_setting');
    	$this->erpConfigrationField = $this->projectSetting['configuration_rule']['erp_integration'];
    	$this->companyAccessField= $this->projectSetting['access_rule']['user']['option']['company'];    	
        $this->companyConfigurationField=$this->projectSetting['configuration_rule']['user']['company'];        
        $this->companyLogoParameter=$this->projectSetting['configuration_rule']['user']['company']['company_logo_upload_parameter'];
        $this->company_per_page=$this->projectSetting['configuration_rule']['user']['company']['no_of_record_per_page'];
        $this->employeeConfigrationsField = $this->projectSetting['configuration_rule']['user']['company_employee'];
        $this->employeeAccessField= $this->projectSetting['access_rule']['user']['option']['company_employee'];
        $this->employeeParameter = $this->employeeConfigrationsField['user_photo_upload_parameter'];
        $this->employee_per_page=$this->projectSetting['configuration_rule']['user']['company_employee']['no_of_record_per_page'];
        $this->signUpManager = $this->get('office_brain_user_sign_up_manager');
        $this->userManager = $this->get('office_brain_user_manager');
        $this->companyManager = $this->get("office_brain_company_manager");
        $this->coreManager=$this->get("office_brain_core_manager");
        $this->user = $this->projectUserSetting['user_data'];
        $this->loginUserCompanyId = null;
        if(is_object($this->user->getUserCompany())){
        	$this->loginUserCompanyId = $this->user->getUserCompany()->getId();
        }                         
        $this->userId = $this->projectSetting['user_id'];
        $this->page = $this->request->get('page', '1');
        $this->companyRecordsPerPage = $this->request->get('records_per_page', $this->company_per_page);
        $this->employeeRecordsPerPage = $this->request->get('records_per_page', $this->employee_per_page);
        $this->requestStatus = $this->request->get('status','');
        $this->activeStatus = '1';
        $this->inactiveStatus = '0';
        $this->countFlagForView = '0';
        $this->countFlagForStatus = '1';
        $this->option = $this->request->get('option',null);
        $this->keywords = $this->request->get('keywords',null);
        $this->searchFlag = $this->request->get('searchFlag',null);
        $this->requestCompanyId = $this->request->get('companyId',null);
        $this->requestUserId = $this->request->get('userId',null);
        $this->responseArray['company_records_per_page'] = $this->companyRecordsPerPage;
        $this->responseArray['employee_records_per_page'] = $this->employeeRecordsPerPage;
        $this->responseArray['page'] = $this->page;
        $this->responseArray['companyConfigrationField']=$this->companyConfigurationField;
        $this->responseArray['companyAccessField'] = $this->companyAccessField;
        $this->responseArray['employeeConfigrationField']=$this->employeeConfigrationsField;
        $this->responseArray['employeeAccessField'] = $this->employeeAccessField;
        $this->responseArray['companyId'] = $this->requestCompanyId;
        $this->responseArray['userId'] = $this->requestUserId;
        $this->responseArray['status']='error';
        $this->responseArray['states'] = $this->coreManager->getStateData();
        $this->responseArray['distributors'] = $this->userManager->getDistributors();
        $this->responseArray['location'] = $this->location.'/company_logo/';
        
        if ($this->has('office_brain_queue_api_manager')) {
            $this->request->attributes->set('object', 'Company');
            $this->queueApiManager = $this->get('office_brain_queue_api_manager');
        }
        $this->exceptionManager = $this->get('access_authorized_exception');
    }
    
    

    /**
     * @author Employee Id: 4488 - (modified by : 4493)
     * OB eCommerce Product -  Company View
     *
     * @Route("company/view",
     * 	name="office_brain_companybundle_company_viewcompany",
     *  options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template()
     */
    
    public function viewCompanyAction()
    {
        $this->initAction();
        $this->getStatusCountAction();
        $this->responseArray['record_set'] = $this->companyManager->getCompanyList($this->userId, $this->countFlagForView,$this->searchParameterArray, $this->page, $this->companyRecordsPerPage, $this->requestStatus);        
        if ($this->searchFlag == '1') {
        	$this->responseArray['html'] = $this->renderView('OfficeBrainCompanyBundle:Company:viewCompany.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 getStatusCountAction()
    {
        $this->initAction();
        $this->prepareSearchParameterArray();
        $this->responseArray['count_record_set'] = $this->companyManager->getCompanyList($this->userId, $this->countFlagForStatus ,$this->searchParameterArray, $this->page, $this->companyRecordsPerPage, $this->requestStatus);        
        foreach ($this->responseArray['count_record_set'] as $key=>$val){
        	if($val['status']=='1'){
        		$this->responseArray['total_active'] = $val[1];
        	}else{
        		$this->responseArray['total_inactive'] = $val[1];
        	}
        	$this->responseArray['total_record']= $this->responseArray['total_active'] + $this->responseArray['total_inactive'];
        }      
    }
    

    /**
     * @author : 4493)
     * OB eCommerce Product - get sindle record of company
     * @Route(
     *   "company/view/popup/{companyId}",
     *    name="office_brain_companybundle_company_viewcompanypopup",
     *    options={"expose"=true},
     * )
     * @Method({"GET"})
     * @Template()
     */
    public function viewCompanyPopupAction()
    {
        $this->initAction();
        $companyObj = $this->companyManager->getCompanyListById($this->requestCompanyId);
        if($this->exceptionManager->isUserAllowedToAccess($companyObj->getCreatedUid(), $this->companyConfigurationField['allowed_users']))
        {
        	$this->responseArray['items'] = $companyObj;
        	return $this->responseArray;
        }else {
        	$this->exceptionManager->throwAccessException();
        	//throw new NotFoundHttpException('Sorry not existing!');
        }
    }
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - company Add
     * @Route(
     *   "company/add",
     *    name="office_brain_companybundle_company_addcompany",
     *    options={"expose"=true},
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainCompanyBundle:Company:addCompany.html.twig")
     */
    
    public function addCompanyAction()
    {
        $this->initAction();
        $this->form = $this->createForm(new CompanyType($this->container, 'company'), new Company());
        $this->form->handleRequest($this->request);        
        $this->responseArray['form_company'] = $this->form->createView();
        
        return $this->responseArray;
    }
    
    
    /**
     * @author (Modifyed By : 4493)
     * OB eCommerce Product -  company submit
     *
     * @Route(
     *    "company/add",
     * 	  name="office_brain_companybundle_company_addcompanypost",
     *    options={"expose"=true},
     * )
     * @Method({"POST"})
     * @Template("OfficeBrainCompanyBundle:Company:addCompany.html.twig")
     */
    
    public function addCompanyPostAction()
    {
        $this->initAction();
        $this->form  = $this->createForm(new CompanyType($this->container, 'company'), new Company());
        $this->form->handleRequest($this->request);
        
        if ($this->form->isValid()) {
        	if($this->companyManager->isCompanyExists($this->form)){
	            $companyData = $this->form->getData();
                
	            $this->coreManager->setLocationPath($this->location);
	            if (is_object($companyData->getCompanyLogo())) {
	              
	                $this->responseArray['logo']=$this->coreManager->uploadImage($this->companyLogoParameter, $companyData->getCompanyLogo(), 'company_logo');
	                switch ($this->responseArray['logo']) {
	                    case 'SUCCESS':
                           	$this->responseArray['status'] = $this->get('translator')->trans('admin.company.upload.success');
	                        $this->responseArray['add']=$this->companyManager->addCompany($companyData,$this->logoUrl);
	                        break;
	                    case 'FAIL':
	                        $this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('admin.company.upload.fail'));
	                        break;
	                    case 'TYPE':
	                        $this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('admin.company.upload.type'));
	                        break;
	                    case 'SIZE':
	                        $this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('admin.company.upload.size',array('%size%'=>$this->companyConfigurationField['company_logo_upload_parameter']['size'])));
	                        break;
	                    case 'HEIGHT':
	                        $this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('admin.company.upload.height',array('%width%'=>$this->companyConfigurationField['company_logo_upload_parameter']['width'],'%height%'=>$this->companyConfigurationField['company_logo_upload_parameter']['height'])));
	                        break;
	                    case 'WIDTH':
	                        $this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('admin.company.upload.width',array('%width%'=>$this->companyConfigurationField['company_logo_upload_parameter']['width'],'%height%'=>$this->companyConfigurationField['company_logo_upload_parameter']['height'])));
	                        break;
	                }
	            }else{
	            	$this->responseArray['add']=$this->companyManager->addCompany($companyData,$this->logoUrl);
	            }	
	            if (array_key_exists('add', $this->responseArray)) {
	                switch ($this->responseArray['add']['status']) {
	                    case 'SUCCESS':
	                        if ($this->erpConfigrationField  && $this->erpConfigrationField ['userManagement'] == 1 && !empty($this->queueApiManager)) {
	                            $this->queueApiManager->mapQueue("create", $this->responseArray['add']['data']);
	                        }
	                        $this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('admin.company.add.success'));	                        
	                        break;
	                    case 'FAIL':            	
	                    	$this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('admin.company.add.fail'));
	                        break;
	                }
	                return $this->redirect($this->generateUrl("office_brain_companybundle_company_viewcompany"));
	            }
        	}
        }        
        
        $this->responseArray['form_company']= $this->form->createView();                        
        return $this->responseArray;
    }
    
    
    
    /**
     * @author (Modifyed By : 4493)
     * OB eCommerce Product - company Add
     * @Route(
     *   "company/edit/{companyId}",
     *    name="office_brain_companybundle_company_editcompany",
     *    options={"expose"=true},
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainCompanyBundle:Company:editCompany.html.twig")
     */
    public function editCompanyAction()
    {
        $this->initAction();
        $companyObj=$this->companyManager->getCompanyListById($this->requestCompanyId); 
        if($this->exceptionManager->isUserAllowedToAccess($companyObj->getCreatedUid(), $this->companyConfigurationField['allowed_users']))
        {
        	
	        $this->form = $this->createForm(new CompanyType($this->container, 'company'), $companyObj);
	        $this->responseArray['companyLogo'] = $companyObj->getCompanyLogo();
	        $this->responseArray['form_company'] = $this->form->createView();   

	        return $this->responseArray;
        }else {
        	$this->exceptionManager->throwAccessException();
        	//throw new NotFoundHttpException('Sorry not existing!');
        }     
              
    }
    

    /**
     * @author (Modifyed By : 4493)
     * OB eCommerce Product -  Company Edit form submit
     *
     * @Route("company/edit/{companyId}",
     * name="office_brain_companybundle_company_editcompanypost",
     * options={"expose"=true}
     * )
     * @Method({"POST"})
     * @Template("OfficeBrainCompanyBundle:Company:editCompany.html.twig")
     */
    
    public function editCompanyPostAction()
    {
        $this->initAction();
        $companyObj=$this->companyManager->getCompanyListById($this->requestCompanyId);    
        if($this->exceptionManager->isUserAllowedToAccess($companyObj->getCreatedUid(), $this->companyConfigurationField['allowed_users']))
        {

        	$this->form  = $this->createForm(new CompanyType($this->container, 'company'), $companyObj);
        	$this->form ->handleRequest($this->request);
        	if ($this->form->isValid()) {
        		if($this->companyManager->isCompanyExists($this->form)){
        			$companyData = $this->form->getData();
        			if($companyObj->getStatus() && $companyObj->getStatus() == 1 ){
        				$companyData->setStatus('1');
        			}else{
        				$companyData->setStatus('0');
        			}
        			$this->coreManager->setLocationPath($this->location);
        			if (is_object($companyData->getCompanyLogo())) {
        				$this->responseArray['logo']=$this->coreManager->uploadImage($this->companyLogoParameter, $companyData->getCompanyLogo(), 'company_logo');
        				switch ($this->responseArray['logo']) {
        					case 'SUCCESS':
        						$this->responseArray['status'] = $this->get('translator')->trans('admin.company.upload.success');
        						$this->responseArray['edit']=$this->companyManager->editCompany($companyData,$this->logoUrl);
        						break;
        					case 'FAIL':
        						$this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('admin.company.upload.fail'));
        						break;
        					case 'TYPE':
        						$this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('admin.company.upload.type'));
        						break;
        					case 'SIZE':
        						$this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('admin.company.upload.size',array('%size%'=>$this->companyConfigurationField['company_logo_upload_parameter']['size'])));
        						break;
        					case 'HEIGHT':
        						$this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('admin.company.upload.height',array('%width%'=>$this->companyConfigurationField['company_logo_upload_parameter']['width'],'%height%'=>$this->companyConfigurationField['company_logo_upload_parameter']['height'])));
        						break;
        					case 'WIDTH':
        						$this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('admin.company.upload.width',array('%width%'=>$this->companyConfigurationField['company_logo_upload_parameter']['width'],'%height%'=>$this->companyConfigurationField['company_logo_upload_parameter']['height'])));
        						break;
        				}
        			}else{
        				$this->responseArray['edit']=$this->companyManager->editCompany($companyData,$this->logoUrl);
        			}
        			if (array_key_exists('edit', $this->responseArray)) {
        				switch ($this->responseArray['edit']['status']) {
        					case 'SUCCESS':
        						if ($this->erpConfigrationField  && $this->erpConfigrationField ['userManagement'] == 1 && !empty($this->queueApiManager)){
        							if($this->responseArray['edit']['data']->getErpId() >0) {
        								$this->queueApiManager->mapQueue("update", $this->responseArray['edit']['data']);
        							} else {
        								$this->queueApiManager->mapQueue("create", $this->responseArray['edit']['data']);
        							}
        						}
        						$this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('admin.company.edit.success'));
        						break;
        					case 'FAIL':
        						$this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('admin.company.edit.fail'));
        						break;
        				}
        				return $this->redirect($this->generateUrl('office_brain_companybundle_company_viewcompany'));
        			}
        		}
        	}
        	$this->responseArray['form_company'] = $this->form->createView();
        	$this->responseArray['companyLogo'] = $companyObj->getCompanyLogo();
        	return $this->responseArray;
        }else {
        	$this->exceptionManager->throwAccessException();
        	//throw new NotFoundHttpException('Sorry not existing!');
        }
         
    }
    
    

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  Company Delete
     *
     * @Route("company/delete",
     * 	name="office_brain_companybundle_company_deletecompany",
     *  options={"expose"=true}
     * )
     * @Template()
     */
    
    public function deleteAction()
    {
        $this->initAction();
        $companyId=$this->request->get('id');
        
        $companyObj=$this->companyManager->getCompanyListById($companyId);
        if($this->exceptionManager->isUserAllowedToAccess($companyObj->getCreatedUid(), $this->companyConfigurationField['allowed_users']))
        {

        	$recordDelete=$this->companyManager->deleteCompany($companyId);
        	
        	switch ($recordDelete['status']) {
        		case 'ISEXIST' :
        			// $erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
        			// if ($erpIntegration && $erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager)) {
        			// $this->queueApiManager->mapQueue("remove", array('id' => $companyId));
        				// }
        				$this->responseArray['status'] = 'isexist';
        				$this->responseArray['success_message'] = $this->get('translator')->trans('admin.company.delete.success');
        				break;
        		case  'SUCCESS' :
        			if ($this->erpConfigrationField && $this->erpConfigrationField['userManagement'] == 1 && !empty($this->queueApiManager)) {
        				$this->queueApiManager->mapQueue("remove", array('id' => $companyId));
        			}
        			$this->responseArray['status'] = 'success';
        			$this->responseArray['success_message'] = $this->get('translator')->trans('admin.company.delete.success');
        			break;
        		case  'FAIL':
        			$this->responseArray['error_message'] = $this->get('translator')->trans('admin.company.delete.fail');
        			break;
        	}
        	return new JsonResponse($this->responseArray);
        }else {
        	$this->exceptionManager->throwAccessException();
        	//throw new NotFoundHttpException('Sorry not existing!');
        }
        
    }


    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  Company Status Update
     *
     * @Route("company/update-status/{companyId}",
     * 	name="office_brain_companybundle_company_updatestatus",
     *  options={"expose"=true}
     * )
     * @Template()
     */
    
    public function updateStatusAction()
    {
        $this->initAction();
        $companySingleRecordObj = $this->companyManager->getCompanyListById($this->requestCompanyId);
        if($this->exceptionManager->isUserAllowedToAccess($companySingleRecordObj->getCreatedUid(), $this->companyConfigurationField['allowed_users']))
        {

        	$status = $companySingleRecordObj->getStatus();
        	if (isset($status) and $status==1) { $status = 0 ; } else { $status=1;}
        	
        	$responseObject=$this->companyManager->updateStatus($this->requestCompanyId, $status);
        	$this->getStatusCountAction();
        	
        	switch ($responseObject['status']) {
        		case  'SUCCESS' :
        			if ($this->erpConfigrationField && $this->erpConfigrationField['userManagement'] == 1 && !empty($this->queueApiManager)) {
        				$companyObj = $responseObject['data'];
        				if ($companyObj->getErpId()) {
        					$this->queueApiManager->mapQueue("updateStatus", array('id' => $this->requestCompanyId, 'status'=>$status));
        				} else {
        					$this->queueApiManager->mapQueue("create", $companyObj);
        				}
        			}
        			$this->responseArray['status'] = 'success';
        			$this->responseArray['status_value'] = $status;
        			$this->responseArray['status_message'] = $this->get('translator')->trans('admin.company.status.success');
        			break;
        		case  'FAIL':
        			$this->responseArray['error_message'] = $this->get('translator')->trans('admin.company.status.fail');
        			break;
        	}
        	return new JsonResponse($this->responseArray);
        }else {
        	$this->exceptionManager->throwAccessException();
        	//throw new NotFoundHttpException('Sorry not existing!');
        }
    }
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Company Employee Form
     * @Route(
     *    "employee/add/{companyId}",
     *    name="office_brain_companybundle_company_addcompanyemployee",
     *    options={"expose"=true},
     *    defaults={"companyId"=NULL}
     * )
     * @method({"GET"})
     * @Template()
     */
    
    public function addCompanyEmployeeAction()
    {
        $this->initAction();
        $userType = 'employee';
        $signUpFormFields = $this->signUpManager->getsignUpFormData($userType);        
        
        $entityArray = array();
        $user = new User();
        $user->setUserCompany($this->companyManager->getCompanyListById($this->requestCompanyId));        
        $entityArray['user'] = $user;
        $entityArray['employeeinfo'] = new EmployeeInfo();
        
        $this->form = $this->createForm(new EmployeeType($this->coreManager, $signUpFormFields, 'emp_add') ,$entityArray);
        $this->form->handleRequest($this->request);
        
        $this->responseArray['form_employee'] = $this->form->createView();
        $this->responseArray['form_fields'] = $signUpFormFields;
        $this->responseArray['userType'] = $userType;
    
        return $this->responseArray;
    }
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  Company Employee form post submit
     *
     * @Route("employee/add/{companyId}", name="office_brain_companybundle_company_addcompanyemployeepost",  options={"expose"=true},defaults={"companyId"=NULL})
     * @method({"POST"})
     * @Template("OfficeBrainCompanyBundle:Company:addCompanyEmployee.html.twig")
     */
    
    public function addCompanyEmployeePostAction()
    {
        $this->initAction();
        $userType = $this->request->get('userType', 'employee');
        $signUpFormFields = $this->signUpManager->getsignUpFormData($userType);
        
        $entityArray = array();
        $user = new User();
        $user->setUserCompany($this->companyManager->getCompanyListById($this->requestCompanyId));
        $entityArray['user'] = $user;
        $entityArray['employeeinfo'] = new EmployeeInfo();
        
        $this->form = $this->createForm(new EmployeeType($this->coreManager, $signUpFormFields, 'emp_add') ,$entityArray);        
        $this->form->handleRequest($this->request);
        
        if ($this->form->isValid()) {        	
        	$userData = $this->form->getData()['user'];        	        
        	$this->coreManager->setLocationPath($this->location);
        	if (is_object($userData->getPhoto())) {        			
        		$this->responseArray['photo']=$this->coreManager->uploadFile($this->employeeParameter, $userData->getPhoto(), 'user_photo');
        		switch ($this->responseArray['photo']) {
        			case 'SUCCESS':
        				$this->responseArray['status'] = $this->get('translator')->trans('admin.company.upload.success');        					
        				$this->responseArray['add'] = $this->userManager->addEmployee($this->form);
        				break;
        			case 'FAIL':
        				$this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('admin.employee.upload.fail'));
        				break;
        			case 'TYPE':
        				$this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('admin.employee.upload.type'));
        				break;
        			case 'SIZE':
        				$this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('admin.employee.upload.size',array('%size%'=>$this->employeeParameter['size'])));
        				break;
        			/*case 'HEIGHT':
        				$this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('admin.employee.upload.height',array('%width%'=>$this->employeeParameter['width'],'%height%'=>$this->employeeParameter['height'])));
        				break;
        			case 'WIDTH':
        				$this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('admin.employee.upload.width',array('%width%'=>$this->employeeParameter['width'],'%height%'=>$this->employeeParameter['height'])));
        				break;*/
        		}
        	}else{
        		$this->responseArray['add'] = $this->userManager->addEmployee($this->form);
        	}
        //	echo $this->responseArray['add']; exit;
        	if (array_key_exists('add', $this->responseArray) && $this->responseArray['add']) {
        	    if ($this->erpConfigrationField  && $this->erpConfigrationField ['userManagement'] == 1 && !empty($this->queueApiManager) && ($this->responseArray['add']) && ($this->responseArray['add']->getStatus() == 'active' || $this->responseArray['add']->getStatus() == 'inactive')) {
	        		if ($this->has('office_brain_queue_api_manager')) {
	        			$this->request->attributes->set('object', 'Employee');
	        			$this->queueApiManager->mapQueue("create", $this->responseArray['add']);
	        		}
        		}
        		$this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('user.add_message.success_msg'));
        		return $this->redirect($this->generateUrl('office_brain_companybundle_company_viewcompanyemployee', array('companyId'=>$this->requestCompanyId)));
        	}
        	
       	}
        $this->responseArray['form_employee'] = $this->form->createView();
        $this->responseArray['form_fields'] = $signUpFormFields;
        $this->responseArray['userType'] = $userType;
        if ($this->request->isXmlHttpRequest()) {
        	if ($this->request->get('call_type')=='country_code' || $this->request->get('call_type')=='state_code') {
        		return $this->responseArray;
        	} else {
        		$errors = array(
        			'form_name' => $this->form->getName(),
        			'form_status' => 'error',
        			'form_errors' => $this->formErrorManager->prepareErrorArray($this->get('validator')->validate($this->form))
        		);
        		return new JsonResponse($errors);
        	}
        }
        return $this->responseArray;
    }
    
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Company Employee Form Edit
     * @Route(
     *    "employee/edit/{userId}",
     *    name="office_brain_companybundle_company_editcompanyemployee",
     *    options={"expose"=true}
     * )
     * @method({"GET"})
     * @Template()
     */
    
    public function editCompanyEmployeeAction()
    {
        $this->initAction();
        $userType = 'employee';
        $signUpFormFields = $this->signUpManager->getsignUpFormData($userType);
        
        $user = $this->userManager->getUserById($this->requestUserId);
        $employeeInfo = $this->userManager->getEmplyeeInfoById($this->requestUserId);
        if($this->exceptionManager->isUserAllowedToAccess($employeeInfo->getUser()->getCreatedUid(), $this->employeeConfigrationsField['allowed_users']))
        {

        	$companyId = $user->getUserCompany()->getId();
        	
        	$entityArray['user'] = $user;
        	$entityArray['employeeinfo'] = $employeeInfo;
        	
        	//$userTypeObj = new UserType($this->coreManager, $signUpFormFields, 'emp_edit');
        	
        	$this->form = $this->createForm(new EmployeeType($this->coreManager, $signUpFormFields, 'emp_edit'), $entityArray);
        	$this->form->handleRequest($this->request);
        	
        	$this->responseArray['form_employee'] = $this->form->createView();
        	$this->responseArray['form_fields'] = $signUpFormFields;
        	$this->responseArray['companyId'] = $companyId;
        	$this->responseArray['userType'] = $userType;
        	return $this->responseArray;        
        }else {
        	$this->exceptionManager->throwAccessException();
        	//throw new NotFoundHttpException('Sorry not existing!');
        }
    }
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  Company Employee Edit form post submit
     *
     * @Route("employee/edit/{userId}", name="office_brain_companybundle_company_editcompanyemployeepost",  options={"expose"=true})
     * @method({"POST"})
     * @Template("OfficeBrainCompanyBundle:Company:editCompanyEmployee.html.twig")
     */
    
    public function editCompanyEmployeePostAction()
    {
        $this->initAction();
        $userType = 'employee';
        $signUpFormFields = $this->signUpManager->getsignUpFormData($userType);
        
        $user = $this->userManager->getUserById($this->requestUserId);
        $employeeInfo = $this->userManager->getEmplyeeInfoById($this->requestUserId);
        
        if($this->exceptionManager->isUserAllowedToAccess($employeeInfo->getUser()->getCreatedUid(), $this->employeeConfigrationsField['allowed_users']))
        {
        

        	$companyId = $user->getUserCompany()->getId();
        	
        	$entityArray['user'] = $user;
        	$entityArray['employeeinfo'] = $employeeInfo;
        	
        	$this->form = $this->createForm(new EmployeeType($this->coreManager, $signUpFormFields, 'emp_edit'), $entityArray);
        	$this->form->handleRequest($this->request);
        	
        	if ($this->form->isValid()) {
        		$userData = $this->form->getData()['user'];
        		$this->coreManager->setLocationPath($this->location);
        		if (is_object($userData->getPhoto())) {
        			$this->responseArray['photo']=$this->coreManager->uploadFile($this->employeeParameter, $userData->getPhoto(), 'user_photo');
        			switch ($this->responseArray['photo']) {
        				case 'SUCCESS':
        					$this->responseArray['status'] = $this->get('translator')->trans('admin.company.upload.success');
        					$this->responseArray['edit'] = $this->userManager->editEmployee($this->form);
        					break;
        				case 'FAIL':
        					$this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('admin.employee.upload.fail'));
        					break;
        				case 'TYPE':
        					$this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('admin.employee.upload.type'));
        					break;
        				case 'SIZE':
        					$this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('admin.employee.upload.size',array('%size%'=>$this->employeeParameter['size'])));
        					break;
        					/*case 'HEIGHT':
        					 $this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('admin.employee.upload.height',array('%width%'=>$this->employeeParameter['width'],'%height%'=>$this->employeeParameter['height'])));
        					 break;
        					 case 'WIDTH':
        					 $this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('admin.employee.upload.width',array('%width%'=>$this->employeeParameter['width'],'%height%'=>$this->employeeParameter['height'])));
        					 break;*/
        			}
        		}else{
        			$this->responseArray['edit'] = $this->userManager->editEmployee($this->form);
        		}
        		if (array_key_exists('edit', $this->responseArray) && $this->responseArray['edit']) {
        			if ($this->erpConfigrationField && $this->erpConfigrationField['userManagement'] == 1 && !empty($this->queueApiManager) && ($this->responseArray['edit']) && ($this->responseArray['edit']->getStatus() == 'active' || $this->responseArray['edit']->getStatus() == 'inactive')) {
        				if ($this->responseArray['edit']->getErpId()) {
        					$action = 'update';
        				} else {
        					$action = 'create';
        				}
        				$this->request->attributes->set('object', 'Employee');
        				$this->queueApiManager->mapQueue($action, $this->responseArray['edit']);
        			}
        			$this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('user.edit_message.success_msg'));
        			return $this->redirect($this->generateUrl('office_brain_companybundle_company_viewcompanyemployee', array('companyId'=>$companyId)));
        		}
        	
        	}
        	$this->responseArray['form_employee'] = $this->form->createView();
        	$this->responseArray['form_fields'] = $signUpFormFields;
        	$this->responseArray['companyId'] = $companyId;
        	$this->responseArray['userType'] = $userType;
        	
        	if ($this->request->isXmlHttpRequest()) {
        		if ($this->request->get('call_type')=='country_code' || $this->request->get('call_type')=='state_code') {
        			return $this->responseArray;
        		} else {
        			$errors = array(
        					'form_name' => $this->form->getName(),
        					'form_status' => 'error',
        					'form_errors' => $this->formErrorManager->prepareErrorArray($this->get('validator')->validate($this->form))
        			);
        			return new JsonResponse($errors);
        		}
        	}
        	return $this->responseArray;
        }else {
        	$this->exceptionManager->throwAccessException();
        	//throw new NotFoundHttpException('Sorry not existing!');
        }
    }
    

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  Admin Company List
     *
     * @Route("employee/view/{companyId}",
     * 	name="office_brain_companybundle_company_viewcompanyemployee",
     *  options={"expose"=true},
     *  defaults={"companyId"=NULL}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainCompanyBundle:Company:viewCompanyEmployee.html.twig")
     */
    
    public function viewCompanyEmployeeAction()
    {
        $this->initAction();
        $this->prepareSearchParameterArray();
        $this->getEmployeeStatusCountAction();

        /* start : for company and branch employee breadcrumb */
        $companyObj=$this->companyManager->getCompanyListById($this->requestCompanyId);
        
        if($this->exceptionManager->isUserAllowedToAccess($companyObj->getCreatedUid(), $this->employeeConfigrationsField['allowed_users']))
        {

        	$this->responseArray['employee_type'] = 'companyEmployee';
        	$this->responseArray['parent_company_id'] = '';
        	if(is_object($companyObj->getParent())){
        		$this->responseArray['employee_type'] = 'branchEmployee';
        		$this->responseArray['parent_company_id'] = $companyObj->getParent()->getId();
        	}
        	/* end : for company and branch employee breadcrumb */
        	
        	$this->responseArray['record_set'] = $this->userManager->getCompanyEmployee($this->requestCompanyId, $this->countFlagForView,$this->searchParameterArray, $this->page, $this->employeeRecordsPerPage, $this->requestStatus);
        	
        	if ($this->searchFlag == '1') {
        		$this->responseArray['html'] = $this->renderView('OfficeBrainCompanyBundle:Company:viewCompanyEmployee.html.twig', $this->responseArray);
        		return new JsonResponse($this->responseArray);
        	}
        	return $this->responseArray;
        }else {
        	$this->exceptionManager->throwAccessException();
        	//throw new NotFoundHttpException('Sorry not existing!');
        }
        
        
    }
    
    
    /**
     * @author : 4493)
     * OB eCommerce Product - get sindle record of company
     * @Route(
     *   "employee/view/popup/{userId}",
     *    name="office_brain_companybundle_company_viewyemployeepopup",
     *    options={"expose"=true},
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainCompanyBundle:Company:viewEmployeePopup.html.twig")
     */
    public function viewEmployeePopupAction()
    {
    	
    	$this->initAction();
    	$userType = 'employee';
    	$signUpFormFields = $this->signUpManager->getsignUpFormData($userType);
    	$employeeInfo = $this->userManager->getUserById($this->requestUserId);
    	
    	if($this->exceptionManager->isUserAllowedToAccess($employeeInfo->getCreatedUid(), $this->employeeConfigrationsField['allowed_users']))
    	{
	    	
    		$this->responseArray['items'] = $employeeInfo;
	    	$this->responseArray['form_fields'] = $signUpFormFields;
	    	
	    	return $this->responseArray;
    	}else {
    		$this->exceptionManager->throwAccessException();
    		//throw new NotFoundHttpException('Sorry not existing!');
    	}
    }
    
    
    /** @author  4493
     * OB eCommerce Product - For get count of active or inactive status
     */
    public function getEmployeeStatusCountAction($requestCompanyId='')
    {
        $this->initAction();
        if($requestCompanyId !=''){
        	$this->requestCompanyId = $requestCompanyId;
        }

        if($this->requestCompanyId == ''){
        	$this->requestCompanyId = $this->responseArray['companyId'] = $this->loginUserCompanyId;        	
        }
        $this->responseArray['count_record_set'] = $this->userManager->getCompanyEmployee($this->requestCompanyId, $this->countFlagForStatus,$this->searchParameterArray, $this->page, $this->employeeRecordsPerPage, $this->requestStatus);
        foreach ($this->responseArray['count_record_set'] as $key=>$val){
        	if($val['status']=='active'){
        		$this->responseArray['total_active'] = $val[1];
        	}else{
        		$this->responseArray['total_inactive'] = $val[1];
        	}
        	$this->responseArray['total_record']= $this->responseArray['total_active'] + $this->responseArray['total_inactive'];
        }
    }
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  Admin Employee Status Update
     *
     * @Route("employee/update-status/{userId}",
     * 	name="office_brain_companybundle_company_updatecompanystatus",
     *  options={"expose"=true}
     * )
     * @Template()
     */
    
    public function updateEmployeeStatusAction()
    {
    	$this->initAction();
    	$user = $this->userManager->getUserById($this->requestUserId);
    	
    	if($this->exceptionManager->isUserAllowedToAccess($user->getCreatedUid(), $this->employeeConfigrationsField['allowed_users']))
    	{

    		$status = $user->getStatus();
    		$this->requestCompanyId = $user->getUserCompany()->getId();
    		if (isset($status) and $status=='active') {  $status = 'inactive' ;   } else {      $status='active';       }
    			
    		$responseObject = $this->userManager->updateUserStatus($this->requestUserId, $status);
    		$this->getEmployeeStatusCountAction($this->requestCompanyId);
    		switch ($responseObject['status']) {
    			case  'SUCCESS' :
    				if ($this->erpConfigrationField && $this->erpConfigrationField['userManagement'] == 1 && !empty($this->queueApiManager)) {
    					$this->request->attributes->set('object', 'Employee');
    					$userObj = $responseObject['data'];
    					if ($userObj->getErpId()) {
    						$this->queueApiManager->mapQueue("updateStatus", array('id' =>$responseObject['data']->getId(), 'status'=> $status));
    					} else {
    						$this->queueApiManager->mapQueue("create", $userObj);
    					}
    				}
    				$this->responseArray['status'] = 'success';
    				$this->responseArray['status_value'] = $status;
    				$this->responseArray['status_message'] = $this->get('translator')->trans('user.update_status.success_msg');
    				break;
    			case  'FAIL':
    				$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: 4493
     * OB eCommerce Product -  Admin Company Employee Delete
     *
     * @Route("employee/delete",
     * 	name="office_brain_companybundle_companyemployee_deleteemployee",
     *  options={"expose"=true}
     * )
     * @Template()
     */
    
    public function deleteEmployeeAction()
    {
        $this->initAction();
        $data = array();
        $userId = $this->request->get('id');
        $user = $this->userManager->getUserById($userId);
        
        if($this->exceptionManager->isUserAllowedToAccess($user->getCreatedUid(), $this->employeeConfigrationsField['allowed_users']))
        {

        	$companyId = $user->getUserCompany()->getId();
        	$userStatus = $this->userManager->deleteUser($userId);
        	$totalActiveCompany= $this->getEmployeeStatusCountAction($companyId, $this->activeStatus);
        	$totalInctiveCompany=$this->getEmployeeStatusCountAction($companyId, $this->inactiveStatus);
        	switch ($userStatus['status']) {
        		case  'SUCCESS' :
        			if ($this->erpConfigrationField && $this->erpConfigrationField['userManagement'] == 1 && !empty($this->queueApiManager)) {
        				$this->request->attributes->set('object', 'Employee');
        				$userObj = $userStatus['data'];
        				if ($userObj->getErpId()) {
        					$this->queueApiManager->mapQueue("remove", array('id' =>$userId,'deleted_at'=> $userObj->getDeletedAt()->format('Y-m-d H:i:s')));
        				} else {
        					$this->queueApiManager->mapQueue("create", $userObj);
        				}
        			}
        			$this->responseArray['status'] = 'success';
        			$this->responseArray['success_message'] = $this->get('translator')->trans('admin.employee.delete_success');
        			$this->responseArray['total'] = $totalActiveCompany+$totalInctiveCompany;
        			$this->responseArray['total_active'] = $totalActiveCompany;
        			$this->responseArray['total_inactive'] = $totalInctiveCompany;
        			//$this->responseArray['page_url'] = $this->generateUrl('office_brain_userbundle_adminuser_viewadminuser');
        			break;
        		case  'FAIL':
        			$this->responseArray['error_message'] = $this->get('translator')->trans('admin.company.delete_fail');
        			break;
        	}
        	return new JsonResponse($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);
    }
    
}
