<?php
namespace OfficeBrain\Bundle\UserBundle\Manager\AbstractManager;

use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Translation\Translator;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\JsonResponse;
use OfficeBrain\Bundle\UserBundle\Entity\ContactBook;
use OfficeBrain\Bundle\UserBundle\Service\CustomPasswordEncoder;
use Symfony\Component\Routing\Router;

/**
 *
 * @author Employee Id: 4273
 * OB eCommerce Product - Login
 * LoginAbstract Class Add to define the common function and logic for login process
 */

abstract class LoginAbstract
{
    private $entityManager;
    protected $session;
    protected $request;
    protected $passwordEncoder;

    /**
     * @author Employee Id: 4273
     * Initialize the required variable on class load
     *
     */
    public function __construct($entityManager, $request, $session, $emailService, $router)
    {
        $this->entityManager = $entityManager;
        $this->session = $session;
        $this->request = $request;
        $this->emailService = $emailService;
        $this->router = $router;

        $this->projectSetting = $this->request->get('project_setting');
        $this->projectUserSetting = $this->request->get('project_user_setting');
        $this->loginConfigrations = $this->projectSetting['configuration_rule']['user']['login'];
        $this->forgotPasswordConfigrations = $this->projectSetting['configuration_rule']['user']['forgot_password'];
        $this->changePasswordConfigrations = $this->projectSetting['configuration_rule']['user']['change_password'];
        $this->entityManager->getRepository('OfficeBrainUserBundle:SignUpForm')->setProjectSetting($this->projectSetting);
        $this->entityManager->getRepository('OfficeBrainUserBundle:User')->setProjectSetting($this->projectSetting);
        $this->entityManager->getRepository('OfficeBrainUserBundle:User')->setProjectUserSetting($this->projectUserSetting);
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Login
     * Function created for get settings for login
     */
    public function getLoginFormData($userType)
    {
        $loginForm = $this->entityManager->getRepository('OfficeBrainUserBundle:SignUpForm')->getSignUpForm($userType);
        return $loginForm;
    }



    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Login
     * Function created for doing ForgotPasswordProcess
     */
    public function doForgotPasswordProcess($user, $subject)
    {
	    	if ($this->forgotPasswordConfigrations['send_link_or_direct_password']=='link') {
	            $reqDate = $user->getPasswordRequestedAt();
	            $minutes = $this->forgotPasswordConfigrations['expire_time']['option']['minutes'];
	            if ($this->forgotPasswordConfigrations['expire_time']['status']==0  || $reqDate==null || strtotime($reqDate->format('Y-m-d H:i:s')) >= strtotime("+".$minutes." minutes")) {
	                $sectre_key = md5($user->getId() . '::' . time());
	
	                $user->setConfirmationToken($sectre_key);
	
	               if($this->forgotPasswordConfigrations['expire_time']['status']==1) {
	                    $user->setPasswordRequestedAt(new \DateTime());
	                } 
	
	                $this->entityManager->persist($user);
	                $this->entityManager->flush();
	                $this->sendResetPasswordLink($user, $subject);
	            } else {
	                return false;
	            }
	        } else {
	            $this->sendDirectPassword($user, $subject);
	        }
	
	        return true;
      
      
    }


    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Login
     * Function created for doing ResetPasswordProcess
     */
    public function doResetPasswordProcess($formData, $user, $subject)
    {
        $user->setConfirmationToken(null);
        $user->setPasswordRequestedAt(null);
        $user->setPassword($this->entityManager->getRepository('OfficeBrainUserBundle:User')->setUserPassword($formData['password'], $user->getSalt()));
        $this->entityManager->persist($user);
        $this->entityManager->flush();

        if ($this->forgotPasswordConfigrations['expire_time']['option']['send_email_after_reset_password']==1) {
            $this->sendResetPasswordMail($user, $subject);
        }
        return true;
    }


    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Login
     * Function created for doing ChangePasswordProcess
     */
    public function doChangePasswordProcess($formData, $user, $subject)
    {
        $user->setPassword($this->entityManager->getRepository('OfficeBrainUserBundle:User')->setUserPassword($formData['password'], $user->getSalt()));
        $this->entityManager->persist($user);
        $this->entityManager->flush();

        if ($this->changePasswordConfigrations['change_password']['option']['send_notification_email']==1) {
            $this->sendChangePasswordMail($user, $subject);
        }
        return true;
    }



    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - sendAprrovalEmail
     * Function created for send Aprroval Email
     */
    public function sendResetPasswordLink($user, $subject)
    {
        $eventKey = 'forgot_password_email'; // This is required field. For each email we have to set event with unique event key.
        $to = $user->getEmail(); // This is required field. Pass email address in array.
        $prepareResetLink = rtrim($this->projectSetting['base_url'], "/").$this->router->generate('office_brain_userbundle_login_reset_password', array('secret_key' => $user->getConfirmationToken())) ;
        $params = array( //Please provide dynamic parameters in this array where placeholder must be used as a key of array.
                'firstname' => $user->getFirstName(),
                'lastname' => $user->getLastName(),
                'email' => $user->getEmail(),
        		'resetlink' => $prepareResetLink
//                 'resetlink' => '<a href="'.$prepareResetLink.'" target="_blank"><span style="color: #131412;">'.$prepareResetLink.'</span></a>'

        );
        $languageId = $this->projectSetting['culture_id'];//This is optional field but when you call this function from admin section you have to pass languageId.
        $from =  ''; //This is optional field.
        $subject = ""; //This is optional field.
        $attachment = array(); //This is optional field. If you have any attachment please provide path in this parameter.
        $cc = array(); // This is optional field.
        $bcc = array(); //This is optional field.

        $this->emailService->sendMail($eventKey, $to, $params, $languageId, $from, $subject, $attachment, $cc, $bcc);

        return true;
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - sendEmail
     * Function created for send Welcome Email
     */
    public function sendDirectPassword($user, $subject)
    {
        $eventKey = 'direct_password_email'; // This is required field. For each email we have to set event with unique event key.
        $to = $user->getEmail(); // This is required field. Pass email address in array.
        $params = array( //Please provide dynamic parameters in this array where placeholder must be used as a key of array.
                'firstname' => $user->getFirstName(),
                'lastname' => $user->getLastName(),
                'email' => $user->getEmail(),
                'password' => $this->entityManager->getRepository('OfficeBrainUserBundle:User')->getUserPassword($user->getPassword(), $user->getSalt())

        );
        $languageId = $this->projectSetting['culture_id'];//This is optional field but when you call this function from admin section you have to pass languageId.
        $from =  ''; //This is optional field.
        $subject = ""; //This is optional field.
        $attachment = array(); //This is optional field. If you have any attachment please provide path in this parameter.
        $cc = array(); // This is optional field.
        $bcc = array(); //This is optional field.

        if (isset($this->forgotPasswordConfigrations['reset_cc_members']['option'][0])) {
            $cc = $this->forgotPasswordConfigrations['reset_cc_members']['option'];
        }
        if (isset($this->forgotPasswordConfigrations['reset_bcc_members']['option'][0])) {
            $bcc = $this->forgotPasswordConfigrations['reset_bcc_members']['option'];
        }
        $this->emailService->sendMail($eventKey, $to, $params, $languageId, $from, $subject, $attachment, $cc, $bcc);
        return true;
    }


    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - sendResetPasswordMail
     * Function created for send ResetPasswordMail
     */
    public function sendResetPasswordMail($user, $subject)
    {
        $eventKey = 'reset_password_email'; // This is required field. For each email we have to set event with unique event key.
        $to = $user->getEmail(); // This is required field. Pass email address in array.
        $params = array( //Please provide dynamic parameters in this array where placeholder must be used as a key of array.
                'firstname' => $user->getFirstName(),
                'lastname' => $user->getLastName(),
                'email' => $user->getEmail(),
                'newpassword' => $this->entityManager->getRepository('OfficeBrainUserBundle:User')->getUserPassword($user->getPassword(), $user->getSalt())

        );
        $languageId = $this->projectSetting['culture_id'];//This is optional field but when you call this function from admin section you have to pass languageId.
        $from =  ''; //This is optional field.
        $subject = ""; //This is optional field.
        $attachment = array(); //This is optional field. If you have any attachment please provide path in this parameter.
        $cc = array(); // This is optional field.
        $bcc = array(); //This is optional field.

        $this->emailService->sendMail($eventKey, $to, $params, $languageId, $from, $subject, $attachment, $cc, $bcc);
        return true;
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - sendChangePasswordMail
     * Function created for send ChangePasswordMail
     */
    public function sendChangePasswordMail($user, $subject)
    {
        $eventKey = 'password_notification_email'; // This is required field. For each email we have to set event with unique event key.
        $to = $user->getEmail(); // This is required field. Pass email address in array.
        $params = array( //Please provide dynamic parameters in this array where placeholder must be used as a key of array.
                'firstname' => $user->getFirstName(),
                'lastname' => $user->getLastName(),
                'email' => $user->getEmail(),
                'newpassword' => $this->entityManager->getRepository('OfficeBrainUserBundle:User')->getUserPassword($user->getPassword(), $user->getSalt()),
        		'password' => $this->entityManager->getRepository('OfficeBrainUserBundle:User')->getUserPassword($user->getPassword(), $user->getSalt())

        );
        $languageId = $this->projectSetting['culture_id'];//This is optional field but when you call this function from admin section you have to pass languageId.
        $from =  ''; //This is optional field.
        $subject = ""; //This is optional field.
        $attachment = array(); //This is optional field. If you have any attachment please provide path in this parameter.
        $cc = array(); // This is optional field.
        $bcc = array(); //This is optional field.


        $this->emailService->sendMail($eventKey, $to, $params, $languageId, $from, $subject, $attachment, $cc, $bcc);
        return true;
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - validateLogin
     * Function created for validate user data
     */
    public function validateLogin()
    {
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - doLogin
     * Function created for Login
     */
    public function doLogin()
    {
        return true;
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - isExistUser
     * Function created for cheking if users exists or not
     */
    private function isExistUser()
    {
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - getUserPassword
     * Function created to get User Password
     */
    private function getUserPassword($password, $salt)
    {
        $newPassword = $this->entityManager->getRepository('OfficeBrainUserBundle:User')->getUserPassword($password, $salt);
        return $newPassword;
    }
}
