<?php

namespace OfficeBrain\CustomBundle\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use OfficeBrain\Bundle\UserBundle\Entity\User;
use OfficeBrain\Bundle\UserBundle\Form\UserType;
use OfficeBrain\Bundle\CoreBundle\CustomeHandler as FormErrorManager;
use Symfony\Component\HttpFoundation\JsonResponse;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use OfficeBrain\Bundle\UserBundle\Controller\SignUpController as BaseSignUpController;
use OfficeBrain\Bundle\CoreBundle\Cache\RedisCacheService;
use Symfony\Component\Form\FormError;
/**
 *
 * @author Employee Id: 4273
 * OB eCommerce Product - SignUp
 * - SignUp Process for user
 *
 */
class SignUpController extends BaseSignUpController
{
    /**
     *
     * @author Employee Id: 4273
     *
     *         To set member variables default value
     *
     * @return NULL
     */
    public function __construct()
    {
        parent::__construct();
        $this->statsh_cache_wrapper=RedisCacheService::create();
    }

    /**
     *
     * @author Employee Id: 4273
     *
     *         To unset member variables
     *
     * @return NULL
     */
    public function __destruct()
    {
        parent::__destruct();
    }

    /**
     *
     * @author Employee Id: 4273
     *
     *         Create various objects required action in this class
     *
     * @return NULL
     */
    public function initAction()
    {
        $this->request = $this->getRequest();
        parent::initAction();
        $this->userId = $this->projectSetting['user_id'];
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - SignUp
     * Function created to show sign up form
     *
     * @Route("/{_locale}/distributor-registration",
     * 	name="office_brain_userbundle_sign_up_distributor_registration",
     *  options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainCustomBundleUserBundle:SignUp:register.html.twig")
     */

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

        if($this->userId!=0){
        	return $this->redirect ( $this->generateUrl ( 'office_brain_page_homepage_view' ) );
        }

        $userType = 'end_user';

        // -----------------------------------------------------------------------
      //  $cacheRegisterKey = array('prepareUserRegister',$this->projectSetting['instance_id'],$userType);
      //  $this->moduleCachePrefix = '__UserRegisterManagement__';
        //$cacheKey = $this->moduleCachePrefix.RedisCacheService::generateKey($this->statsh_cache_wrapper,$cacheRegisterKey);
        //$cacheData = RedisCacheService::getCacheData($this->statsh_cache_wrapper,$cacheKey);
        //if($cacheData){
        //	return $cacheData;
      //  }
        // -----------------------------------------------------------------------

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

        //echo '<pre/>';print_r($signUpFormFields);exit;
        $user = new User();
        $userTypeObj = new UserType($this->coreManager, $signUpFormFields, 'main_register');

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

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

        $response = $this->render('OfficeBrainCustomBundleUserBundle:SignUp:register.html.twig', $data);

        if(!empty($cacheKey))
        {
        	RedisCacheService::saveCacheData($this->statsh_cache_wrapper,$cacheKey,$response);
        }

        return $response;
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - SignUp
     * Function created to validate sign up form
     *
     * @Route("/{_locale}/distributor-registration",
     * 	name="office_brain_userbundle_sign_up_register_post",
     *  options={"expose"=true}
     * )
     *
     * @Method({"POST"})
     * @Template("OfficeBrainCustomBundleUserBundle:SignUp:register.html.twig")
     */

    public function registerPostAction()
    {   
        $this->initAction();
        $data = array();
        $format = $this->request->get('_format', 'html') ;

        $userType = $this->request->get('userType', 'end_user');
        $signUpFormFields = $this->signUpManager->getsignUpFormData($userType);
        //echo '<pre/>';print_r($_POST);exit;
        $user = new User();
        $userTypeObj = new UserType($this->coreManager, $signUpFormFields, 'main_register');

        $form = $this->createForm($userTypeObj, $user);
        $form->handleRequest($this->request);
        //$form=$this->signUpManager->filterFormData($form);
        $userStatus = $this->signUpManager->registerUser($form);
        //print_r($userStatus);exit;
        //echo "<pre>";
        // \Doctrine\Common\Util\Debug::dump($userStatus);
        $customeError = NULL;
        if( empty($_POST['membership_id']) && $_POST['membership_id'] == '' ) {
			$customeError['membership_id'] = 'Membership Id';
		}
        $userEmail = $form->getData()->getEmail();
        $userEmailExists = $this->signUpManager->getUserByEmail($userEmail);
        if($userEmailExists!=NULL){
			$customeError['email'] = 'Email Id Already Exists!.';
		}
        if ($userStatus) {

            $erp_flag = TRUE;
            $user_type = $userStatus->getUserType();
            $is_individual = $userStatus->getIsIndividual();
            if (($user_type == 'end_user' && $this->projectSetting['instance_type'] == 'supplier') || ($is_individual == TRUE && $this->projectSetting['instance_type'] == 'supplier')) {
                $erp_flag = FALSE;
            }
            $erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
            if ($erpIntegration && $erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager) && $userStatus->getuserCompany() && ($userStatus->getStatus()=="active" || $userStatus->getStatus()=="inactive") && $erp_flag == TRUE) {
                $this->queueApiManager->mapQueue("create", $userStatus);
            }

            //if ($this->request->get('billing_address')) {
                //$billingArray['id'] = 1; $billingArray['default'] = $this->request->get('billing_address',null);
                $billingAddressId = 1;
                $billingAddress = $this->signUpManager->addAddress($user, $billingAddressId);
                if ($erpIntegration && $erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager) && $userStatus->getuserCompany() && ($userStatus->getStatus()=="active" || $userStatus->getStatus()=="inactive") && $erp_flag == TRUE) {
                    $this->request->attributes->set('object', 'ContactBook');
                    $this->queueApiManager->mapQueue("create", $billingAddress);
                }
            //}
            //if ($this->request->get('shipping_address')) {
                //$shippingArray['id'] = 2;$shippingArray['default'] = $this->request->get('shipping_address',null);
                $shippingAddressId = 2;
                $shippingAddress = $this->signUpManager->addAddress($user, $shippingAddressId);
                if ($erpIntegration && $erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager) && ($userStatus->getStatus()=="active" || $userStatus->getStatus()=="inactive") && $userStatus->getuserCompany() && $erp_flag == TRUE) {
                    $this->request->attributes->set('object', 'ContactBook');
                    $this->queueApiManager->mapQueue("create", $shippingAddress);
                }
            //}

            $this->signUpManager->sendEmail($form, $this->translator->trans('user.register.mail.subject'));
            $this->signUpManager->sendAdminEmail($form);

            if ($signUpFormFields['approval_configuration']['is_auto_approve']->option->approval_email==1) {
                $this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('user.register.success'));
            } else {
                $this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('user.register.success'));
            }

            if ($this->signUpConfigrations['option']['allow_login_after_signup']==1) {
                $this->loginManager->doLogin($form);

                return $this->redirect($this->generateUrl($this->projectSetting['configuration_rule']['user']['login']['option']['after_login_url']));
            } else {

                return $this->redirect($this->generateUrl('office_brain_page_homepage_view'));
            }
        }
        $data['form_user'] = $form->createView();
        $data['userType'] = $userType;
        $data['form_fields'] = $signUpFormFields;
        $data['states'] = $this->coreManager->getStateData();
        $data['distributors'] = array();
//         $data['distributors'] = $this->userManager->getDistributors();
		$data['membership_value'] = $_POST['membership_id'];

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

}
