<?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 Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Translation\Translator;
use Symfony\Component\HttpFoundation\JsonResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use OfficeBrain\Bundle\CoreBundle\CustomeHandler as FormErrorManager;
use OfficeBrain\Bundle\UserBundle\Entity\User;
use OfficeBrain\Bundle\UserBundle\Form\UserType;
use OfficeBrain\Bundle\UserBundle\Form\UserPhotoType;
use OfficeBrain\Bundle\UserBundle\Form\LocateDistributorType;
use Symfony\Component\Form\FormError;

class UserController extends Controller
{
    /**
     * @author Employee Id: 4834
     * set default value
     * @return NULL
     */
    public function __construct()
    {
        $this->queueApiManager = null;
        $this->biosManager = null;
        $this->searchParameterArray = array();
        $this->searchKeyWordsArray = array();
    }

    /**
     * @author Employee Id: 4834
     * unset default value
     * @return NULL
     */
    public function __destruct()
    {
        unset($this->queueApiManager);
        unset($this->biosManager);
        unset($this->searchParameterArray);
        unset($this->searchKeyWordsArray);
    }
    /**
     *
     * @author Employee Id: 4273
     *
     *         Create various objects required action in this class
     *
     * @return NULL
     */
    public function initAction()
    {
        $this->request = $this->getRequest();
        $this->translator = $this->get('translator');
        $this->session = $this->request->getSession();

        $this->projectSetting = $this->request->get('project_setting');
        $this->projectUserSetting = $this->request->get('project_user_setting');
        $this->userConfigrations = $this->projectSetting['configuration_rule']['user']['user'];
        $this->findDistributorConfigrations = $this->projectSetting['configuration_rule']['user']['find_distributor'];     
        $this->distributorRecordsPerPage = $this->projectSetting['configuration_rule']['user']['find_distributor']['option']['no_of_record_per_page'];
        $this->page = $this->request->get('page',1); 
        $this->userId = $this->projectSetting['user_id'];
        $this->user = $this->projectUserSetting['user_data'];
        $this->companyId = $this->container->getParameter('company_id');
        $this->userManager = $this->get('office_brain_user_manager');
        $this->signUpManager = $this->get('office_brain_user_sign_up_manager');
        $this->coreManager = $this->get('office_brain_core_manager');
        $this->subShopManager = $this->get('office_brain_subshop_manager');        
        $this->biosManager = $this->get('office_brain_bios_manager');
        
        $this->orderManager = $this->get('office_brain_order_manager');
        $this->wishListManager = $this->get('office_brain_wish_list_manager');
        $this->requestQuoteManager = $this->get('office_brain_request_quote_manager');
        $this->quoteManager = $this->get('office_brain_quote_manager');
        
        
        $this->formErrorManager = new FormErrorManager\JsonError();
        if ($this->has('office_brain_queue_api_manager')) {
            $this->request->attributes->set('object', 'User');
            $this->queueApiManager = $this->get('office_brain_queue_api_manager');
        }
    }




    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Login
     * Function created to view my account Info
     *
     * @Route("/{_locale}/my-account/info",
     * 	name="office_brain_userbundle_user_my_account_info",
     *  options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainUserBundle:User:myAccountInfo.html.twig")
     */

    public function myAccountInfoAction()
    {
        $this->initAction();
        $data = array();
        $user = $this->projectUserSetting['user_data'];
        $data['wish_list_count'] = $this->wishListManager->getTotalCount();
        $data['request_quote_list_count'] = $this->requestQuoteManager->getTotalCountUserWiseAdmin();
        $data['quote_list_count'] = $this->quoteManager->getAllTabCount();
        $this->prepareSearchParameterArray();
        $data['order_list_count'] = $this->orderManager->getOrderTotalCount('user');
        return $data;
    }

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

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Login
     * Function created to show edit info form
     *
     * @Route("/{_locale}/my-account/edit-info",
     * 	name="office_brain_userbundle_user_my_account_edit",
     *  options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainUserBundle:User:myAccountEdit.html.twig")
     */
    public function myAccountEditAction()
    {
        $this->initAction();
        $data = array();

        $user = $this->projectUserSetting['user_data'];
        $userType = $user->getUserType();
        /*if($userType=="admin"){
			$userType = null;
		}*/
        $signUpFormFields = $this->signUpManager->getsignUpFormData($userType);
        //unset($signUpFormFields['fields']['password']);
		//print_r($signUpFormFields); die;
        $userTypeObj = new UserType($this->coreManager, $signUpFormFields, 'main_edit');
        $form = $this->createForm($userTypeObj, $user);

        $form_photo = $this->createForm(new UserPhotoType(), $user);

        $data['form_user'] = $form->createView();
        $data['form_fields'] = $signUpFormFields;
        $data['form_photo'] = $form_photo->createView();
        $data['states'] = $this->coreManager->getStateData($user->getCountryId());
        $data['distributors'] = $this->userManager->getDistributors();        
        return $data;
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Login
     * Function created to save edit info
     *
     * @Route("/{_locale}/my-account/edit-info",
     * 	name="office_brain_userbundle_user_my_account_edit_post",
     *  options={"expose"=true}
     * )
     * @Method({"POST"})
     * @Template("OfficeBrainUserBundle:User:myAccountEdit.html.twig")
     */
    public function myAccountEditPostAction()
    {
        $this->initAction();
        $data = array();
        $errors = '';
        $user = $this->projectUserSetting['user_data'];
        $userType = $user->getUserType();
        $signUpFormFields = $this->signUpManager->getsignUpFormData($userType);
		//unset($signUpFormFields['fields']['password']);
        $userTypeObj = new UserType($this->coreManager, $signUpFormFields, 'main_edit');
		$isIndividual = $user->getIsIndividual(); 
        $form = $this->createForm($userTypeObj, $user);
        $form->handleRequest($this->request);
        $form_photo = $this->createForm(new UserPhotoType(), $user);

        $form->getData()->setIsIndividual($isIndividual); // for admin issue
        $userStatus = $this->userManager->editUser($form);
        
        if ($userStatus) {
            $erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
            $is_individual = $userStatus->getIsIndividual();
            $erp_flag = TRUE;
            $user_type = $userStatus->getUserType();
            if (($user_type == 'end_user' && $this->projectSetting['instance_type'] == 'supplier') || ($is_individual == TRUE && $this->projectSetting['instance_type'] == 'supplier')) {
                $erp_flag = FALSE;
            }
            if ($erpIntegration && $erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager) && $userStatus->getErpId()>0 && $erp_flag == TRUE ) {
                $this->queueApiManager->mapQueue("update", $userStatus);
            }

            if ($this->request->isXmlHttpRequest()) {

            	$data['status'] = 'success';
            	$data['page_url'] = $this->generateUrl('office_brain_userbundle_user_my_account_info');
            	$data['success_message'] = $this->translator->trans('user.my_account_edit.success_msg');

				return new JsonResponse($data);

            } else {
            	$this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('user.my_account_edit.success_msg'));
            	
            	return $this->redirect($this->generateUrl('office_brain_userbundle_user_my_account_info'));
            }
            
        }
        $data['form_user'] = $form->createView();
        $data['form_fields'] = $signUpFormFields;
        $data['form_photo'] = $form_photo->createView();
        $data['states'] = $this->coreManager->getStateData($user->getCountryId());
        $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 new JsonResponse($this->prepareFormJsonError($this->get('validator'),$form,$customeError));
            }
        }
        return $data;
    }

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

   private function prepareErrorArray($errors_object=array(),$customeError=array())
    {
    	$error_array = array();
        foreach ($errors_object as $error) {
            $field_name = $error->getPropertyPath();
            $field_name = str_replace(array('children', '[', ']', 'data'), '', $field_name);
            $field_name = preg_replace('/\.+/', '.', $field_name);
            $field_name = preg_replace('/\.$/', '', $field_name);
            $field_name = preg_replace('/^\./', '', $field_name);
            $error_array[$field_name] = $error->getMessage();
        }
        foreach($customeError as $key=>$error){
			$error_array[$key] = $error;
		}
        unset($field_name);
        unset($errors_object);
        return $error_array;
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Login
     * Function created to save edit info
     *
     * @Route("/{_locale}/my-account/edit-photo",
     * 	name="office_brain_userbundle_user_my_account_edit_photo",
     *  options={"expose"=true}
     * )
     * @Method({"POST"})
     * @Template()
     */
    public function myAccountEditPhotoAction()
    {
        $this->initAction();
        $data = array();
        $errors = '';

        $user = $this->projectUserSetting['user_data'];
        $form_photo = $this->createForm(new UserPhotoType(), $user);
        $form_photo->handleRequest($this->request);

        if ($form_photo->isValid()) {
            $this->coreService=$this->get("office_brain_core_manager");
            $baseUrl = $this->getParameter('base_url');
            $this->location=$this->get('kernel')->getRootDir().'/../web/images/uploads/';
            $this->coreService->setLocationPath($this->location);
            $this->parameter = $this->userConfigrations['user_photo_upload_parameter'];
            $code=$this->coreService->uploadImage($this->parameter, $form_photo->getData()->getPhoto(), 'user_photo');
            switch ($code) {
                        case 'SUCCESS':
                            $data['success'] = $this->get('translator')->trans('user.my_account_edit.upload_error.success');
                            break;
                        case 'FAIL':
                            $data['error'] = $this->translator->trans('user.my_account_edit.upload_error.fail');
                            break;
                        case 'TYPE':
                            $data['error'] = $this->translator->trans('user.my_account_edit.upload_error.type');
                            break;
                        case 'SIZE':
                            $data['error'] = $this->translator->trans('user.my_account_edit.upload_error.size', array('%img_size%' => $this->parameter['size'] ));
                            break;
                        case 'HEIGHT':
                            $data['error'] = $this->translator->trans('user.my_account_edit.upload_error.widthheight', array('%img_width%' => $this->parameter['width'],'%img_height%' => $this->parameter['height'] ));
                            break;
                        case 'WIDTH':
                            $data['error'] = $this->translator->trans('user.my_account_edit.upload_error.widthheight', array('%img_width%' => $this->parameter['width'],'%img_height%' => $this->parameter['height'] ));
                            break;
                    }
            if ($code=='SUCCESS') {
                $userPhoto=$this->userManager->editUserPhoto($form_photo->getData());
                $data['userPhoto'] = $baseUrl.'/images/uploads/user_photo/'.$userPhoto;
            }
        } else {
            $data['error'] = $this->translator->trans('user.my_account_edit.upload_error.fail');
        }
        if ($this->request->isXmlHttpRequest()) {
            return new JsonResponse($data);
        }
        return $data;
    }


    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Locate Distributor
     * Function created to show locate distributor form
     *
     * @Route("/{_locale}/my-account/locate-distributor",
     * 	name="office_brain_userbundle_user_my_account_locate_distributor",
     *  options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainUserBundle:User:myAccountLocateDistributor.html.twig")
     */
    public function myAccountLocateDistributorAction()
    {
        $this->initAction();
        $data = array();
        
        $locateConfig = $this->userConfigrations = $this->projectSetting['configuration_rule']['user']['locate_distributor'];
        $form = $this->createForm(new LocateDistributorType($this->coreManager->getLocateDistributorStateData(), $locateConfig),$this->user);

        $data['form'] = $form->createView();
        $data['distributors'] = $this->userManager->getDistributors();
        $data['locatedDistributorId'] = $this->user->getLocatedDistributorId();
        return $data;
    }


    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Locate Distributor
     * Function created to show locate distributor form
     *
     * @Route("/{_locale}/my-account/locate-distributor",
     * 	name="office_brain_userbundle_user_my_account_locate_distributor_post",
     *  options={"expose"=true}
     * )
     * @Method({"POST"})
     * @Template("OfficeBrainUserBundle:User:myAccountLocateDistributor.html.twig")
     */
    public function myAccountLocateDistributorPostAction()
    {
        $this->initAction();
        $data = array();
        $locateConfig = $this->userConfigrations = $this->projectSetting['configuration_rule']['user']['locate_distributor'];
        $form = $this->createForm(new LocateDistributorType($this->coreManager->getLocateDistributorStateData(), $locateConfig),$this->user);
        $form->handleRequest($this->request);
        if ($form->isValid()) {
        	$locateDistributor = $this->userManager->editLocateDistributor($this->user);
        	if($locateDistributor){
            	$this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('user.locate_distributor.success_msg'));
        	}
            return $this->redirect($this->generateUrl('office_brain_userbundle_user_my_account_locate_distributor'));
        }
        $errors = array(
                'form_name' => $form->getName(),
                'form_status' => 'error',
                'form_errors' => $this->formErrorManager->prepareErrorArray($this->get('validator')->validate($form))
        );
        if ($this->request->isXmlHttpRequest()) {
            return new JsonResponse($errors);
        }
        $data['errors'] = $errors;
        $data['form'] = $form->createView();
        $filter['zipcode'] = $this->request->get('zipcode');
        $filter['stateId'] = $this->request->get('stateId');
        $data['distributors'] = $this->userManager->getDistributors($filter);

        return $data;
    }


    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - User
     * Function created to change distributor dropdown
     *
     * @Route("/{_locale}/change-distributor",
     * 	name="office_brain_userbundle_user_change_distributor",
     *  options={"expose"=true}
     * )
     * @Method({"POST"})
     * @Template()
     */
    public function changeDistributorAction()
    {
        $this->initAction();
        $data = array();
        $errors = '';

        $filter['zipcode'] = $this->request->get('zipcode');
        $filter['stateId'] = $this->request->get('stateId');
        $data['distributors'] = $this->userManager->getDistributors($filter);
        if ($this->request->isXmlHttpRequest()) {
            return new JsonResponse($data);
        }
        return $data;
    }
    
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - User
     * Function created to find distributor
     *
     * @Route("/{_locale}/find-distributor",
     * 	name="office_brain_userbundle_user_find_distributor",
     *  options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template()
     */
    public function findDistributorSiteAction()
    {
    	$this->initAction();
		$zipcode = $this->request->get('zipcode');
    	//$this->responseArray['distributor'] = $this->userManager->getStateWiseDistributors($this->page,$this->distributorRecordsPerPage);
    	$this->responseArray['distributor'] = $this->subShopManager->getStateWiseDistributorsSite($this->page,$this->distributorRecordsPerPage,$zipcode);
    	    	
    	return $this->responseArray;    	
    }
    
    /**
     * @author Employee Id: 5051
     * Function created for Employee Information
     *
     * @Route("/{_locale}/bios",
     * 	name="office_brain_userbundle_user_getemployeeinfo"
     * )
     * @Template("OfficeBrainUserBundle:User:bios.html.twig")
     */
    
    public function getEmployeeInfoAction()
    {
    	$this->initAction();
    	$data = array();
    	$data['employeeInfo']=$this->biosManager->getEmployeeDetails($this->companyId);
    	return $data;
    }

    /**
     * @author Employee Id: 4074
     * 
     * Function to get welcome user top menu section
     *
     * @Route("/{_locale}/get-welcome-user-top-menu-section",
     * 	name="office_brain_userbundle_user_getwelcomeusertopmenusection",
     *  options={"expose"=true}
     * )
     * 
     * @Template("OfficeBrainUserBundle:User:getWelcomeUserTopMenuSection.html.twig")
     * 
     */
	public function getWelcomeUserTopMenuSectionAction()
    {
    	return array();
    }
}
