<?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 Nelmio\ApiDocBundle\Annotation\ApiDoc;
use OfficeBrain\Bundle\UserBundle\Form\ForgotPasswordType;
use OfficeBrain\Bundle\UserBundle\Form\ResetPasswordType;
use OfficeBrain\Bundle\UserBundle\Form\ChangePasswordType;

class LoginController extends Controller
{
    /**
     *
     * @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->loginConfigrations = $this->projectSetting['configuration_rule']['user']['login'];
        //echo '<pre>'; print_r($this->projectSetting['configuration_rule']['promo_discount']); die;
        $this->forgotPasswordConfigrations = $this->projectSetting['configuration_rule']['user']['forgot_password'];
        $this->userId = $this->projectSetting['user_id'];
        $this->userManager = $this->get('office_brain_user_manager');
        $this->loginManager = $this->get('office_brain_user_login_manager');
        $this->formErrorManager = new FormErrorManager\JsonError();
    }


    /**
     * 
     * @author Employee Id: 4273
     * 
     * OB eCommerce Product - Login
     * 
     * Function created to show login form
     * @Route("/login",
     *  name="office_brain_userbundle_login_login_without_locale",
     *  options={"expose"=true}
     * )
     * 
     * @Route("/{_locale}/login",
     * 	name="office_brain_userbundle_login_login",
     *  options={"expose"=true}
     * )
     * 
     * @Method({"GET"})
     * 
     * @Template("OfficeBrainUserBundle:Login:login.html.twig")
     * 
     */

    public function loginAction()
    {
        if ($this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) { //IS_AUTHENTICATED_FULLY
            return $this->redirect($this->generateUrl('office_brain_page_homepage_view'));
        }
        $this->initAction();
        $data = array();

        if ($this->request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $this->request->attributes->get(
                    SecurityContext::AUTHENTICATION_ERROR
            );
        } else {
            $error = $this->session->get(SecurityContext::AUTHENTICATION_ERROR);
            $this->session->remove(SecurityContext::AUTHENTICATION_ERROR);
        }

        $forgotForm = $this->createForm(new ForgotPasswordType());
        $data['forgot_form'] = $forgotForm->createView();
        $data['username'] = $this->session->get(SecurityContext::LAST_USERNAME);
        $data['error'] = $error;
        if (isset($_COOKIE['userdata'])) {
            $data['user_cookie'] = unserialize($_COOKIE['userdata']);
        }
      //  $data['csrf_token'] = $this->container->get('form.csrf_provider')->generateCsrfToken('authenticate');

        return $data;
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Login
     * Function created to show login pop up
     *
     * @Route("/{_locale}/login-pop/{refer_url}",
     * 	name="office_brain_userbundle_login_login_popup",
     *  options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainUserBundle:Login:loginPopup.html.twig")
     */

    public function loginPopupAction()
    {
        $this->initAction();
        $data = array();
        
        if ($this->request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $this->request->attributes->get(
                    SecurityContext::AUTHENTICATION_ERROR
            );
        } else {
            $error = $this->session->get(SecurityContext::AUTHENTICATION_ERROR);
            $this->session->remove(SecurityContext::AUTHENTICATION_ERROR);
        }

        $forgotForm = $this->createForm(new ForgotPasswordType());
        $data['forgot_form'] = $forgotForm->createView();
        $data['username'] = $this->session->get(SecurityContext::LAST_USERNAME);
        $data['error'] = $error;
        $data ['refer_url'] = $this->request->get ( 'refer_url' );
        if (isset($_COOKIE['userdata'])) {
            $data['user_cookie'] = unserialize($_COOKIE['userdata']);
        }
        return $data;
    }
    
    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Login
     * Function created to show login quick view
     *
     * @Route("/{_locale}/login",
     * 	name="office_brain_userbundle_login_login_quick",
     *  options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainUserBundle:Login:loginQuick.html.twig")
     */

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

        if ($this->request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $this->request->attributes->get(
                    SecurityContext::AUTHENTICATION_ERROR
            );
        } else {
            $error = $this->session->get(SecurityContext::AUTHENTICATION_ERROR);
            $this->session->remove(SecurityContext::AUTHENTICATION_ERROR);
        }

        $forgotForm = $this->createForm(new ForgotPasswordType());
        $data['forgot_form'] = $forgotForm->createView();
        $data['username'] = $this->session->get(SecurityContext::LAST_USERNAME);
        $data['error'] = $error;
        if (isset($_COOKIE['userdata'])) {
            $data['user_cookie'] = unserialize($_COOKIE['userdata']);
        }
        return $data;
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Login
     * Function created to process forget Password
     *
     * @Route("/{_locale}/forgot-pwd",
     * 	name="office_brain_userbundle_login_forgot_password_check",
     *  options={"expose"=true}
     * )

     * @Method({"POST"})
     * @Template("OfficeBrainUserBundle:Login:forgotPassword.html.twig")
     */

    public function forgotPasswordCheckAction()
    {

        $this->initAction();
        $data = array();
        $errors = '';

        $format = $this->request->get('_format', 'html') ;

		if($format == "json"){
			$form = $this->createForm(new ForgotPasswordType(),null,array('csrf_protection' => false));
		}
		else {
        	$form = $this->createForm(new ForgotPasswordType());
		}
        $form->handleRequest($this->request);

        if ($form->isValid()) {
            $form_data = $form->getData();
            $user = $this->userManager->getUserByEmail($form_data ['email']);
	            if ($user) {
	            	if($user->getStatus() == 'active' || $user->getStatus() == 'approve' || $this->forgotPasswordConfigrations['allow_pending_user']['status']==1)
	            	{
	                	$process = $this->loginManager->doForgotPasswordProcess($user, $this->translator->trans('user.forget.email_subject'));
	                	if ($process) {
			            	$success_msg = $this->translator->trans('user.forget.success');
			                if ($this->request->isXmlHttpRequest()) {
			                	$data['success'] = $success_msg;
			                } 
			                else {
			                	$this->get('session')->getFlashBag()->set('success_message', $success_msg);
			                }
			            }
			            else {
			            	$fail_msg = $this->translator->trans('user.forget.exists');
			                if ($this->request->isXmlHttpRequest()) {
			                	$data['fail'] = $fail_msg;
			                }
			                else {
			                	$this->get('session')->getFlashBag()->set('error_message', $fail_msg);
			                }
			            }
			            if ($this->request->isXmlHttpRequest()) {
			            	return new JsonResponse($data);
			           }
			           if( $format == 'json'){
			           		return array('status'=>1,'message'=>$this->translator->trans('user.forget.success'));
			           }
			           else {
			           		return $this->redirect($this->generateUrl('office_brain_page_homepage_view'));
			           }
			      }
			      else{
			      	$errors['email'] = $this->translator->trans('user.forget.pending_status');
			      }
			   }       
	            else {
	                $errors['email'] = $this->translator->trans('user.forget.user_not_exists');
	            }
            }
        else {
            $errors = $this->formErrorManager->prepareErrorArray($this->get('validator')->validate($form));
        }
        $data['errors'] = $errors;
        if ($this->request->isXmlHttpRequest()) {
            return new JsonResponse($data);
        }        
    	if( $format == 'json'){
        	if (count($errors)<=0){
        		foreach ($form as $child) {
        			if (!$child->isValid()) {
        				$thiserror = $form->get($child->getName())->getErrors();
        				$errors[$child->getName().$key] = $thiserror[0]->getMessage();
        			}
        		}
        	}
        	$error = array_values($errors);
        	$msg= $error[0];
        	return array('status'=>0,'message'=>$msg);
        }        
        $data['form'] = $form->createView();
        return $data;
    }

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

    public function resetPasswordAction($secret_key)
    {
        $this->initAction();
        $data = array();
        $user = $this->userManager->getUserByConfirmationToken($secret_key);

        if ($user) {
            $reqDate = $user->getPasswordRequestedAt();
            $minutes = $this->forgotPasswordConfigrations['expire_time']['option']['minutes'];

            if($this->forgotPasswordConfigrations['expire_time']['status']==1  && strtotime($reqDate->format('Y-m-d H:i:s')) >= strtotime("+".$minutes." minutes")) {
                $this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('user.reset_password.expired'));
                return $this->redirect($this->generateUrl('office_brain_page_homepage_view'));
            }
        } else {
            $this->get('session')->getFlashBag()->set('error_message', $this->translator->trans('user.reset_password.not_exists'));
            return $this->redirect($this->generateUrl('office_brain_page_homepage_view'));
        }

        $form = $this->createForm(new ResetPasswordType());
        $data['secret_key'] = $secret_key;
        $data['form'] = $form->createView();

        return $data;
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Login
     * Function created to reset Password
     *
     * @Route("/{_locale}/reset-password/{secret_key}",
     * 	name="office_brain_userbundle_login_reset_password_check",
     *  options={"expose"=true}
     * )
     * @Method({"POST"})
     * @Template("OfficeBrainUserBundle:Login:resetPassword.html.twig")
     */
    public function resetPasswordCheckAction($secret_key)
    {
        $this->initAction();
        $data = array();
        $user = $this->userManager->getUserByConfirmationToken($secret_key);

        $form = $this->createForm(new ResetPasswordType());
        $form->handleRequest($this->request);

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

            $this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('user.reset_password.success'));

            if ($this->forgotPasswordConfigrations['expire_time']['option']['redirect_login_after_reset']==1) {
                return $this->redirect($this->generateUrl('office_brain_userbundle_login_login'));
            } else {
                return $this->redirect($this->generateUrl('office_brain_page_homepage_view'));
            }
        }

        $data['secret_key'] = $secret_key;
        $data['form'] = $form->createView();

        return $data;
    }




    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Login
     * Function created to show change password
     *
     * @Route("/{_locale}/my-account/change-password",
     * 	name="office_brain_userbundle_login_change_password",
     *  options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainUserBundle:Login:changePassword.html.twig")
     */

    public function changePasswordAction()
    {
        $this->initAction();
        $data = array();
        $user = $this->projectUserSetting['user_data'];

        $form = $this->createForm(new ChangePasswordType($user));
        $data['form'] = $form->createView();

        return $data;
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Login
     * Function created to change Password
     *
     * @Route("/{_locale}/my-account/change-password",
     * 	name="office_brain_userbundle_login_change_password_check",
     *  options={"expose"=true}
     * )
     * @Method({"POST"})
     * @Template("OfficeBrainUserBundle:Login:changePassword.html.twig")
     */
    public function changePasswordCheckAction()
    {
        $this->initAction();
        $data = array();
        $user = $this->projectUserSetting['user_data'];

        $form = $this->createForm(new ChangePasswordType($user));
        $form->handleRequest($this->request);

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

            $this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('user.change_password.success'));

            return $this->redirect($this->generateUrl('office_brain_userbundle_login_change_password'));
        }

        $data['form'] = $form->createView();

        return $data;
    }


    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Login
     * Function created to logout
     *
     * @Route("/logout")
     *
     * @Route("/{_locale}/logout",
     * 	name="office_brain_userbundle_login_logout",
     *  options={"expose"=true}
     * )
     *
     * @Template()
     */

    public function logoutAction()
    {
    }
}
