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

/**
 *
 * @author Employee Id: 4273
 * OB eCommerce Product - User
 * UserAbstract Class Add to define the common function and logic for sign up process
 */

abstract class UserAbstract
{
    protected $entityManager;
    protected $session;
    protected $request;

    /**
     * @author Employee Id: 4273
     * Initialize the required variable on class load
     *
     */
    public function __construct($entityManager, $request, $session,$paginatorManager,$userApiManager,$serviceGroupManager,$jmsSerializer,$coreManager, $emailService, $router)
    {
        $this->entityManager = $entityManager;
        $this->session = $session;
        $this->request = $request;
        $this->paginatorManager = $paginatorManager;
        $this->userApi = $userApiManager;
        $this->serviceGroupManager = $serviceGroupManager;
        $this->jmsSerializer = $jmsSerializer;     
        $this->coreManager = $coreManager;
        $this->projectSetting = $this->request->get('project_setting');
        $this->projectUserSetting = $this->request->get('project_user_setting');
        $this->user = $this->projectUserSetting['user_data'];
        $this->userId = $this->projectSetting['user_id'];
        $this->userConfigrations = $this->projectSetting['configuration_rule']['user']['user'];
        $this->signUpConfigrations = $this->projectSetting['configuration_rule']['user']['sign_up'];
        $this->companyRepositoryManager  = $this->entityManager->getRepository('OfficeBrainCompanyBundle:Company');
        $this->userRepositoryManager = $this->entityManager->getRepository('OfficeBrainUserBundle:User');
        $this->signUpRepositoryManager = $this->entityManager->getRepository('OfficeBrainUserBundle:SignUpForm');
        $this->signUpRepositoryManager->setProjectSetting($this->projectSetting);        
        $this->userRepositoryManager->setProjectSetting($this->projectSetting);
        $this->userRepositoryManager->setProjectUserSetting($this->projectUserSetting);
        $this->userRepositoryManager->setPaginatorService($this->paginatorManager);
        $this->userRepositoryManager->setUserApi($this->userApi);
        $this->userRepositoryManager->setServiceGroupService($this->serviceGroupManager);
        $this->userRepositoryManager->setCoreManager($this->coreManager);        
        $this->userRepositoryManager->setJmsSerializer($this->jmsSerializer);
        
        //EMP4464: Start
        $this->emailService = $emailService;
        $this->router = $router;
        //EMP4464: End
    }


    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Add USer
     * Function created for add user data to records
     */

    public function addUser($form, $userType, $companyId='',$fromerp=0)
    {
        if ($form->isValid()) {
        	$userId = $this->projectSetting['user_id'];
            $userStatus = $this->userRepositoryManager->addUser($form, $userType, $userId,$fromerp);
            return $userStatus;
        } else {
            return false;
        }
    }
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Add Guest USer
     * Function created for add user data to records
     */
    
    public function addGuestUser($form)
    {
    	$userStatus = $this->userRepositoryManager->addGuestUser($form);
    	if ($userStatus) {
    		return array('status'=>'SUCCESS','data'=>$userStatus);
    	}
    	return array('status'=>'FAIL');    	
    }
    

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Edit USer
     * Function created for edit user data to records
     */
    public function editUser($form)
    {
        if ($form->isValid()) {
            $userStatus = $this->userRepositoryManager->editUser($form);
            return $userStatus;
        } else {
            return false;
        }
    }


    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - getUserById
     * Function created to get User By Id
     */
    public function getUserById($id)
    {
        $user = $this->userRepositoryManager->getUserById($id);
        return $user;
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - getUserByUsername
     * Function created to get User By Username
     */
    public function getUserByUsername($username)
    {
        $user = $this->userRepositoryManager->getUserByUsername($username);
        return $user;
    }
    
    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - getUserByEmail
     * Function created to get User By Email
     */
    public function getUserByEmail($email)
    {
        $user = $this->userRepositoryManager->getUserByEmail($email);
        return $user;
    }


    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - getUserByConfirmationToken
     * Function created to get User By ConfirmationToken
     */
    public function getUserByConfirmationToken($token)
    {
        $user = $this->userRepositoryManager->getUserByConfirmationToken($token);
        return $user;
    }

    /**
     * @author Employee Id: 4464
     * OB eCommerce Product - getUserIdByName
     * Function created to get User Id by name
     */
    public function getUserIdByName($searchName)
    {
        $user = $this->userRepositoryManager->getUserIdByName($searchName);
        return $user;
    }

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - getAdminAllUsers
     * Function created to get AllUsers
     */
    public function getAdminAllUsers($userId,$requestUserStatusTab,$page,$recordsPerPage, $searchParameterArray='',$usertype='',$status='')
    {
    	$this->paginatorRecordSet = $this->userRepositoryManager->getAdminAllUsers($userId,$requestUserStatusTab,$page,$recordsPerPage,$searchParameterArray,$usertype,$status);
        return $this->paginatorRecordSet;
    }

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - getAdminAllUsersCount
     * Function created to get AllUsers Count
     */
    public function getAdminAllUsersCount($userId,$mappedWithCompany,$userCountFlag,$page,$recordsPerPage, $searchParameterArray='',$usertype='',$status='')
    {
    	$this->paginatorRecordSet = $this->userRepositoryManager->getAdminAllUsers($userId,$mappedWithCompany,$page,$recordsPerPage,$searchParameterArray,$usertype,$status,$userCountFlag);
    	return $this->paginatorRecordSet;
    }


    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - getEmployee List
     * Function created to get Company Employee List
     */

    public function getCompanyEmployee($companyId,$countFlag,$searchParameterArray,$page,$recordsPerPage,$status)
    {
        $resultarray = $this->userRepositoryManager->getCompanyEmployee($companyId,$countFlag,$searchParameterArray,$page,$recordsPerPage,$status);
        return $resultarray;
    }


    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - delete User
     * Delete user by id
     */
    public function deleteUser($userId)
    {
        $resultarray = $this->userRepositoryManager->deleteUser($userId);
        return $resultarray;
    }


    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - delete User
     * Delete user by id
     */
    public function updateUserStatus($userId, $status,$ObCustomerIdConfirm='')
    {
        $resultarray = $this->userRepositoryManager->updateUserStatus($userId, $status,$ObCustomerIdConfirm);
        return $resultarray;
    }


    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - check Email Exists
     * Function created to check Email Exists
     */
    public function checkUserExists($form)
    {	
        $status = $this->userRepositoryManager->checkUserExists($form);
        return $status;
    }


    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - get security token
     * Function created to get User By Id
     */
    public function getSecurityToken($lenght = 22)
    {
        return $this->userRepositoryManager->getUserConfirmationToken($lenght);

    }



    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - getSuppliers
     * Function created to get Suppliers List (for flyer)
     */
    public function getAllSuppliers($country='')
    {
    	return $this->entityManager->getRepository('OfficeBrainUserBundle:User')->getAllSuppliers($country);
    }
    
    /**
     * @author Employee Id: 4571
     * OB eCommerce Product - getDistributors
     * Function created to get Distributors List 
     */
    public function getAllDistributors($searchVal='', $searchBy='', $country='', $state='')
    {	
    	$temp = array();
    	return $this->entityManager->getRepository('OfficeBrainUserBundle:User')->getAllDistributors($temp, $searchVal, $searchBy, $country, $state);
    }
    
    

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - edit user photo
     * Function created to edit user photo
     */
    public function editUserPhoto($user)
    {
        $userPhoto=$user->getPhoto()->getClientOriginalName();
        $user->setPhoto($userPhoto);
        $this->entityManager->persist($user);
        $this->entityManager->flush();
        return $userPhoto;
    }
    
    
    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - edit Locate Distributor
     * Function created to edit locate Distributor
     */
    public function editLocateDistributor($user)
    {
    	$locateDistributor = $user->getLocatedDistributorId();
    	$user->setLocatedDistributorId($locateDistributor);
    	$this->entityManager->persist($user);
    	$this->entityManager->flush();
    	return $locateDistributor;
    }
    
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - User
     * Function created for Assign Service group to user
     */
    public function assignAccessGroup($serviceGroupId, $user)
    {
    	$user->setServiceGroup($this->entityManager->getRepository('OfficeBrainServiceGroupBundle:ServiceGroup')->find($serviceGroupId));    	
    	$this->entityManager->persist($user);
    	$this->entityManager->flush();
    	    	
    	return true;
    }
    
    /**
     * @author Employee Id: 4589
     * OB eCommerce Product - User
     * Function created for Assign Default Service group to user before remove service group
     */
    public function assignDefaultAccessGroup($serviceGroup)
    {
    	//get default service group
    	$defaultServiceGroup = $this->serviceGroupManager->getServiceDefaultGroup($serviceGroup->getCountryId());
    	
    	$this->userRepositoryManager->updateUserServiceGroup($serviceGroup,$defaultServiceGroup);
    
    	return true;
    }
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - supplierIdByObCustomerId
     * Function created to get supplier Id By OBCustomer Id (From client User Table)
     */
    public function supplierIdByObCustomerId($obCustomerId)
    {
    	return $this->entityManager->getRepository('OfficeBrainUserBundle:User')->supplierIdByObCustomerId($obCustomerId);
    }
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - findObCustomerIdFromApi
     * Function created to get OBCustomer Id List (From APi)
     */
    public function findObCustomerIdFromApi($userId)
    {
    	$user = $this->getUserById($userId);
    	return $this->entityManager->getRepository('OfficeBrainUserBundle:User')->findObCustomerIdByUserFromApi($user->getEmail());
    }
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - createNewObCustomerIdFromApi
     * Function created to create new OBCustomer Id List (From APi)
     */
    public function createNewObCustomerIdFromApi($userId)
    {
    	$user = $this->getUserById($userId);
    	return $this->entityManager->getRepository('OfficeBrainUserBundle:User')->createNewObCustomerIdFromApi($user);
    }
        
    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - check Email Exists For Guest user
     * Function created to check Email Exists
     */
    public function checkGuestUserExists($form)
    {
    	$status = $this->userRepositoryManager->checkGuestUserExists($form);
    	return $status;
    }
    
    /**
     * @author Employee Id: 4203
     * OB eCommerce Product - update or add locate distributor from product detail page
     * Function created to edit locate Distributor
     */
    public function updateLocateDistributor($user,$distId)
    {
    	$user->setLocatedDistributorId($distId);
    	$this->entityManager->persist($user);
    	$this->entityManager->flush();
    	return 'success';
    }
    
    /**
     * @author Employee Id: 4464
     * OB eCommerce Product - sendStatusChangeEmailToUser
     * @param 1: $userId
     * Description: Function created to send approval / denial email to User
     */
    public function sendStatusChangeEmailToUser($userId)
    {
        $user = $this->getUserById($userId);
        $signUpFormFields = $this->signUpRepositoryManager->getSignUpForm($user->getUserType());
        $approvalConfigurations = $signUpFormFields['approval_configuration'];
        
        if((strtolower($user->getStatus()) == 'approve' || strtolower($user->getStatus()) == 'active') && ($approvalConfigurations['admin_send_user_approval_mail']->status == 1)){
            $this->sendApprovalMail($userId);
        }elseif((strtolower($user->getStatus()) == 'unapprove' || strtolower($user->getStatus()) == 'inactive') && ($approvalConfigurations['admin_send_user_denial_mail']->status == 1)){
            $this->sendDenialMail($userId);
        }
        return true;///admin/en_us/email/release-emails
    }
    
    /**
     * @author Employee Id: 4464
     * OB eCommerce Product - sendApprovalMail
     * @param 1: $userId
     * Description: Function created to send approval email to User
     */
    public function sendApprovalMail($userId){
        $user = $this->getUserById($userId);
        $eventKey = 'approval_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.
        $password = $this->entityManager->getRepository('OfficeBrainUserBundle:User')->getUserPassword($user->getPassword(),$user->getSalt());
        $link = '';
        if($user->getConfirmationToken()!=null || $user->getConfirmationToken()!=''){
        	$link = rtrim($this->projectSetting['base_url'], "/").$this->router->generate('office_brain_userbundle_sign_up_approve_register', array('confirmation_token' => $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(),
            'username' => $user->getLoginUsername(),
            'password' => $password,
            'link' => $link,
        );
        $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.
        
        $this->emailService->sendMail($eventKey, $to, $params, $languageId, $from);
    }
    
    /**
     * @author Employee Id: 4464
     * OB eCommerce Product - sendDenialMail
     * @param 1: $userId
     * Description: Function created to send approval email to User
     */
    public function sendDenialMail($userId){
        $user = $this->getUserById($userId);
        $eventKey = 'denial_mail'; // 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.
        $password = $this->entityManager->getRepository('OfficeBrainUserBundle:User')->getUserPassword($user->getPassword(),$user->getSalt());
        $link = '';
        if($user->getConfirmationToken()!=null || $user->getConfirmationToken()!=''){
        	$link = rtrim($this->projectSetting['base_url'], "/").$this->router->generate('office_brain_userbundle_sign_up_approve_register', array('confirmation_token' => $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(),
            'username' => $user->getLoginUsername(),
            'password' => $password,
            'link' =>  $link,
        );
        
        $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.
        
        $this->emailService->sendMail($eventKey, $to, $params, $languageId, $from);
    }
    
}
