<?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\DependencyInjection\ContainerInterface;
use OfficeBrain\Bundle\CompanyBundle\Form\CompanyType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use OfficeBrain\Bundle\CompanyBundle\Manager\Extended;
use OfficeBrain\Bundle\CompanyBundle\Entity\Company;
use Symfony\Component\HttpFoundation\JsonResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

/**
 *
 * @author 4488
 * @Route("admin/{_locale}/")
 */

class BranchController extends Controller
{
    /**
     * @author Employee Id: 4493
     * Modification of company
     */
    
    public function __construct(ContainerInterface $container=null)
    {
    	$this->entityManager=null;
        $this->branchManager=null;
        $this->coreManager=null;
        $this->request=null;
        $this->responseArray['status']=null;
        $this->projectSetting=null;
        $this->projectUserSetting =null;
        $this->location=null;
        $this->logoUrl =null;
        $this->branchAccessField= null;
        $this->branchConfigurationField=null;
        $this->companyConfigurationField=null;
        $this->companyAccessField= null;
        $this->branchLogoParameter=null;
        $this->per_page=null;
        $this->employeeConfigrations = null;
        $this->employeeAccess= null;
        $this->signUpManager = null;
        $this->userManager =null;
        $this->translator = null;
        $this->session= null;
        $this->activeStatus = null;
        $this->inactiveStatus =null;
        $this->branchCountFlagForView = null;
        $this->branchCountFlagForStatus = 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;
        $this->queueApiManager = null;
    }

    public function __destruct()
    {
        unset($this->request);
        unset($this->entityManager);
        unset($this->branchManager);
        unset($this->coreManager);
        unset($this->responseArray['status']);
        unset($this->projectSetting);
        unset($this->projectUserSetting);
        unset($this->location);
        unset($this->logoUrl);
        unset($this->branchAccessField);
        unset($this->branchConfigurationField);
        unset($this->companyConfigurationField);
        unset($this->companyAccessField);
        unset($this->branchLogoParameter);
        unset($this->per_page);
        unset($this->employeeConfigrations);
        unset($this->employeeAccess);
        unset($this->signUpManager);
        unset($this->userManager);
        unset($this->translator);
        unset($this->session);
        unset($this->activeStatus);
        unset($this->inactiveStatus);
        unset($this->branchCountFlagForView);
        unset($this->branchCountFlagForStatus);
        unset($this->searchParameterArray);
        unset($this->responseArray['total_active']);
        unset($this->responseArray['total_inactive']);
        unset($this->responseArray['total_record']);
        unset($this->option);
        unset($this->keywords);
        unset($this->queueApiManager);
    }
    

    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->projectSetting=$this->request->get('project_setting');
    	$this->projectUserSetting = $this->request->get('project_user_setting');
    	$this->translator = $this->get('translator');
    	
        $this->branchAccessField = $this->projectSetting['access_rule']['user']['option']['branch'];
        $this->branchConfigurationField=$this->projectSetting['configuration_rule']['user']['branch'];
        $this->branchLogoParameter=$this->projectSetting['configuration_rule']['user']['branch']['company_logo_upload_parameter'];
        
        $this->branch_per_page=$this->branchConfigurationField['no_of_record_per_page'];
        $this->activeStatus = '1';
        $this->inactiveStatus = '0';
        
        $this->branchManager=$this->get("office_brain_company_manager");
        $this->coreManager=$this->get("office_brain_core_manager");
        
        $this->userId = $this->projectSetting['user_id'];
        $this->user = $this->projectUserSetting['user_data'];
        $this->loginUserCompanyId = null;
        if(is_object($this->user->getUserCompany())){
        	$this->loginUserCompanyId = $this->user->getUserCompany()->getId();
        }        
        $this->page = $this->request->get('page', '1');
        $this->branchRecordsPerPage = $this->request->get('records_per_page', $this->branch_per_page);
        $this->requestStatus = $this->request->get('status','');
        $this->activeStatus = '1';
        $this->inactiveStatus = '0';
        $this->branchCountFlagForView = '0';
        $this->branchCountFlagForStatus = '1';
        $this->option = $this->request->get('option',null);
        $this->keywords = $this->request->get('keywords',null);
        $this->companyId = $this->request->get('companyId',null);
        $this->searchFlag = $this->request->get('searchFlag',null);
        
        $this->responseArray['location'] = $this->location.'/company_logo/';
        $this->responseArray['branch_records_per_page'] = $this->branchRecordsPerPage;
        $this->responseArray['page'] = $this->page;
        $this->responseArray['branchConfigrationField']=$this->branchConfigurationField;
        $this->responseArray['branchAccessField'] = $this->branchAccessField;
        $this->responseArray['status']='error';
        $this->responseArray['companyId'] = $this->companyId;
        
        if ($this->has('office_brain_queue_api_manager')) {
            $this->request->attributes->set('object', 'Branch');
            $this->queueApiManager = $this->get('office_brain_queue_api_manager');
        }  
    }
    
    
    
    /**
     * @author Employee Id: 4488 - (modified by : 4493)
     * OB eCommerce Product -  Branch View
     *
     * @Route("branch/view/{companyId}",
     * 	name="office_brain_companybundle_company_viewbranch",
     *  options={"expose"=true},
     *  defaults={"companyId"=NULL}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainCompanyBundle:Company:viewBranch.html.twig")
     */
    
    public function viewBranchAction()
    {	
    	$this->initAction();
    	$this->getStatusCountAction();    	   	
    	$this->responseArray['record_set'] = $this->branchManager->getCompanyList($this->userId, $this->branchCountFlagForView,$this->searchParameterArray, $this->page, $this->branchRecordsPerPage, $this->requestStatus,$this->companyId);
    	
    	if ($this->searchFlag  == '1') {
    		$this->responseArray['html'] = $this->renderView('OfficeBrainCompanyBundle:Company:viewBranch.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($companyId = '')
    {
    	$this->initAction();    	
    	$this->prepareSearchParameterArray();
		if($companyId != ''){ $this->companyId = $companyId; }
		if($this->companyId == ''){
			$this->companyId  = $this->responseArray['companyId'] = $this->loginUserCompanyId;
		}
    	$this->responseArray['count_record_set']  = $this->branchManager->getCompanyList($this->userId, $this->branchCountFlagForStatus ,$this->searchParameterArray, $this->page, $this->branchRecordsPerPage, $this->requestStatus,$this->companyId);
    	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 Employee Id: 4493
     * OB eCommerce Product -  Ajax Branch View
     *
     * @Route("company-branch/view/{companyId}",
     * 	name="office_brain_companybundle_company_viewbranchtab",
     *  options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainCompanyBundle:Company:viewBranchTab.html.twig")
     */
    
    public function viewBranchTabAction()
    {
        $this->initAction();
        $this->responseArray['items'] = $this->branchManager->getCompanyList($this->userId, $this->branchCountFlagForView,$this->searchParameterArray, $this->page, $this->branchRecordsPerPage, $this->requestStatus,$this->companyId);
        return $this->responseArray;
    }
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - company Add
     * @Route(
     *   "branch/add/{companyId}",
     *    name="office_brain_companybundle_company_addbranch",
     *    options={"expose"=true},
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainCompanyBundle:Company:addBranch.html.twig")
     */
    
    public function addBranchAction()
    {
        $this->initAction();
        $this->form = $this->createForm(new CompanyType($this->container, 'branch',$this->userId), new Company());
        $this->form->handleRequest($this->request);
        $this->responseArray['form_company'] = $this->form->createView();
                
        return $this->responseArray;
    }
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - company Add
     * @Route(
     *   "branch/add/{companyId}",
     *    name="office_brain_companybundle_company_addbranchpost",
     *    options={"expose"=true},
     * )
     * @Method({"POST"})
     * @Template("OfficeBrainCompanyBundle:Company:addBranch.html.twig")
     */
    
    public function addBranchPostAction()
    {
    	$this->initAction();
    	$this->form  = $this->createForm(new CompanyType($this->container, 'branch', $this->userId), new Company());
    	$this->form ->handleRequest($this->request);
    
    	if ($this->form->isValid()) {
    		if($this->branchManager->isCompanyExists($this->form)){    		
	    		$companyData = $this->form->getData();
	    		$this->coreManager->setLocationPath($this->location);
	    		if (is_object($companyData->getCompanyLogo())) {
	    			$this->responseArray['logo']=$this->coreManager->uploadImage($this->branchLogoParameter, $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->branchManager->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->branchConfigurationField['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->branchConfigurationField['company_logo_upload_parameter']['width'],'%height%'=>$this->branchConfigurationField['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->branchConfigurationField['company_logo_upload_parameter']['width'],'%height%'=>$this->branchConfigurationField['company_logo_upload_parameter']['height'])));
	    					break;
	    			}
	    		}else{
	    			$this->responseArray['add']=$this->branchManager->addCompany($companyData,$this->logoUrl);
	    		}
	    		if (array_key_exists('add', $this->responseArray)) {
	    			switch ($this->responseArray['add']['status']) {
	    				case 'SUCCESS':
	                        $erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
                            if ($erpIntegration && $erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager)) {
                                if ($this->has('office_brain_queue_api_manager')) {
                                    $this->queueApiManager->mapQueue("create", $companyData);
                                }
                            }
	                        $this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('admin.company.add.branch_success'));
                            
	                        break;
	                    case 'FAIL':
	                        $this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('admin.company.add.branch_fail'));
	                        break;
	    			}
	    			return $this->redirect($this->generateUrl("office_brain_companybundle_company_viewbranch", array('companyId'=>$this->companyId)));
	    		}
    		}	
    	}
    	$this->responseArray['form_company'] = $this->form->createView();    	
    	return $this->responseArray;
    }
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  Company Delete
     *
     * @Route("branch/delete",
     * 	name="office_brain_companybundle_company_deletebranch",
     *  options={"expose"=true}
     * )
     * @Template()
     */
    
    public function deleteAction()
    {
        $this->initAction();
        $companyId=$this->request->get('id');
        $singleCompanyObj = $this->branchManager->getCompanyListById($companyId);
        
        if($this->exceptionManager->isUserAllowedToAccess($singleCompanyObj->getCreatedUid(), $this->branchConfigurationField['allowed_users']))
        {
	        	
	        $recordDelete=$this->branchManager->deleteCompany($companyId);
	        switch ($recordDelete['status']) {
	            case  'SUCCESS' :
	            $erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
	                            if ($erpIntegration && $erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager)) {
	                                if ($this->has('office_brain_queue_api_manager')) {
	                                    $this->queueApiManager->mapQueue("remove", array('id'=> $companyId));
	                                }
	                            }
	                $this->responseArray['status'] = 'success';
	                $this->responseArray['success_message'] = $this->get('translator')->trans('admin.company.delete.branch_success');
	                break;
	            case  'FAIL':
	                $this->responseArray['error_message'] = $this->get('translator')->trans('admin.company.delete.branch_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 Add
     * @Route(
     *   "branch/edit/{companyId}",
     *    name="office_brain_companybundle_company_editbranch",
     *    options={"expose"=true},
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainCompanyBundle:Company:editBranch.html.twig")
     */
    
    public function editBranchAction()
    {
        $this->initAction();
        $singleCompanyObj = $this->branchManager->getCompanyListById($this->companyId);
        

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

        	$parentCompanyId = $singleCompanyObj->getParent()->getId();
        	$this->form = $this->createForm(new CompanyType($this->container, 'branch' ,$this->userId), $singleCompanyObj);
        	$this->form->handleRequest($this->request);
        	$this->responseArray['form_company'] = $this->form->createView();
        	$this->responseArray['parentId'] = $parentCompanyId;
        	$this->responseArray['companyLogo'] = $singleCompanyObj->getCompanyLogo();
        	
        	return $this->responseArray;
        }else {
        	$this->exceptionManager->throwAccessException();
        	//throw new NotFoundHttpException('Sorry not existing!');
        }
    }
    
    
    /**
     * @author (Modifyed By : 4493)
     * OB eCommerce Product -  Branch Edit form submit
     *
     * @Route("branch/edit/{companyId}",
     * name="office_brain_companybundle_company_editbranchpost",
     * options={"expose"=true}
     * )
     * @Method({"POST"})
     * @Template("OfficeBrainCompanyBundle:Company:editBranch.html.twig")
     */
    
    public function editBranchPostAction()
    {
    	$this->initAction();
    	$singleCompanyObj=$this->branchManager->getCompanyListById($this->companyId);
    	
    	if($this->exceptionManager->isUserAllowedToAccess($singleCompanyObj->getCreatedUid(), $this->branchConfigurationField['allowed_users']))
    	{

    		$parentCompanyId = $singleCompanyObj->getParent()->getId();
    		$this->form  = $this->createForm(new CompanyType($this->container, 'branch' , $this->userId), $singleCompanyObj);
    		$this->form ->handleRequest($this->request);
    		
    		if ($this->form->isValid()) {
    			if($this->entityManager->getRepository('OfficeBrainCompanyBundle:Company')->checkCompanyExists($this->form)){
    				$companyData = $this->form->getData();
    				if($singleCompanyObj->getStatus() && $singleCompanyObj->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->branchLogoParameter, $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->branchManager->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->branchConfigurationField['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->branchConfigurationField['company_logo_upload_parameter']['width'],'%height%'=>$this->branchConfigurationField['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->branchConfigurationField['company_logo_upload_parameter']['width'],'%height%'=>$this->branchConfigurationField['company_logo_upload_parameter']['height'])));
    							break;
    					}
    				}else{
    					$this->responseArray['edit']=$this->branchManager->editCompany($companyData,$this->logoUrl);
    				}
    				if (array_key_exists('edit', $this->responseArray)) {
    					switch ($this->responseArray['edit']['status']) {
    						case 'SUCCESS':
    							$erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
    							if ($erpIntegration && $erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager)) {
    								if ($this->has('office_brain_queue_api_manager')) {
    									$this->queueApiManager->mapQueue("update", $companyData);
    								}
    							}
    							$this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('admin.company.edit.branch_success'));
    							break;
    						case 'FAIL':
    							$this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('admin.company.edit.branch_fail'));
    							break;
    					}
    					return $this->redirect($this->generateUrl('office_brain_companybundle_company_viewbranch', array('companyId'=>$parentCompanyId)));
    				}
    			}
    		}
    		$this->responseArray['form_company'] =  $this->form->createView();
    		$this->responseArray['parentId'] = $parentCompanyId;
    		$this->responseArray['companyLogo'] = $singleCompanyObj->getCompanyLogo();
    		
    		return $this->responseArray;
    	}else {
    		$this->exceptionManager->throwAccessException();
    		//throw new NotFoundHttpException('Sorry not existing!');
    	}
    	
    }
    
   
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  Company Status Update
     *
     * @Route("branch/update-status/{companyId}",
     * 	name="office_brain_companybundle_branch_updatestatus",
     *  options={"expose"=true}
     * )
     * @Template()
     */
    
    public function updateStatusAction()
    {
    	$this->initAction();
    	$branchSingleRecordObj = $this->branchManager->getCompanyListById($this->companyId);
    	

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

    		$status = $branchSingleRecordObj->getStatus();
    		$this->parentCompanyIds = $branchSingleRecordObj->getParent()->getId();
    		if (isset($status) and $status==1) { $status = 0 ; } else { $status=1;}
    		$responseObject=$this->branchManager->updateStatus($this->companyId, $status);
    		$this->getStatusCountAction($this->parentCompanyIds);
    		switch ($responseObject['status']) {
    			case  'SUCCESS' :
    				$erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
    				if ($erpIntegration && $erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager)) {
    					if ($this->has('office_brain_queue_api_manager')) {
    						$this->queueApiManager->mapQueue("updateStatus", array('id'=>$responseObject['data']->getId(), 'status' => $status));
    					}
    				}
    				$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 - preapre  search parameter
     */
    private function prepareSearchParameterArray()
    {
    	$this->searchParameterArray[$this->option]=trim($this->keywords);
    }
}
