<?php

namespace OfficeBrain\Bundle\RewardReferralBundle\Manager\AbstractManager;

use OfficeBrain\Bundle\RewardReferralBundle\Entity\RewardReferralConfiguration;
use OfficeBrain\Bundle\RewardReferralBundle\Form\RewardReferralConfigurationType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * @author OfficeBrain 4589 <info@officebrain.com>
 *
 * Description : Reward Referral Abstract Class
 */
abstract class RewardReferralAbstract
{
    const STATUS = "status";
    const STATUS_ERROR = "error";
    const STATUS_SUCCESS = "success";
    const STATUS_ERROR_MESSAGE = "error_message";
    const STATUS_SUCCESS_MESSAGE = "success_message";
    
    protected $entityManager;
    protected $session;
    protected $request;
    
    protected $projectSetting;
    protected $configurationRule;
    
    protected $instanceId;
    protected $instanceType;
    
    protected $cultureId;
    protected $cultureCode;
    protected $countries;
    protected $languages;
    protected $countryId;
    protected $languageId;
    protected $countryCode;
    protected $languageCode;
    
    protected $userId;
    protected $createdUid;
    protected $upatedUid;
    
    protected $paginatorService;
    protected $translatorService;
    protected $emailService;
    
    /**
    * @author Employee Id: 4589
    * Initialize the required variable on class load
    */
    public function __construct($entityManager, $request, $session, $paginatorService, $translatorService, $emailService, $countries, $languages)
    {
        $this->entityManager = $entityManager;
        $this->request = $request;
        $this->sessionManager = $session;

        $this->projectSetting = $this->request->get('project_setting');
        $this->configurationRule = $this->projectSetting['configuration_rule']['promo_discount'];

        $this->instanceId = $this->projectSetting['instance_id'];
        $this->instanceType = $this->projectSetting['instance_type'];

        $this->userId = $this->projectSetting['user_id'];
        $this->createdUid = $this->userId;
        $this->upatedUid =$this->userId;

        $this->paginatorService = $paginatorService;
        $this->translatorService = $translatorService;
        $this->emailService = $emailService;
        
        $this->cultureId = $this->projectSetting['culture_id'];
        $this->cultureCode = $this->projectSetting['culture_code'];
        
        $this->culture = $this->request->get('culture', false);
        $this->countries = $countries;
        $this->languages = $languages;
        
        //repository call
        $this->RewardReferralRepo = $this->entityManager->getRepository('OfficeBrainRewardReferralBundle:RewardReferralConfiguration');
        $this->RewardReferralRepo->setProjectSetting($this->projectSetting);
        
        $this->rewardEarnHistoryRepository = $this->entityManager->getRepository('OfficeBrainRewardReferralBundle:RewardEarnHistory');
        $this->rewardEarnHistoryRepository->setProjectSetting($this->projectSetting);
        
        $this->rewardRedeemHistoryRepository = $this->entityManager->getRepository('OfficeBrainRewardReferralBundle:RewardRedeemHistory');
        $this->rewardRedeemHistoryRepository->setProjectSetting($this->projectSetting);
        
        //$this->getCultureValue();
    }
    
    public function __destruct()
    {
        unset($this->entityManager);
        unset($this->request);
        unset($this->sessionManager);

        unset($this->projectSetting);
        unset($this->configurationRule);

        unset($this->instanceId);
        unset($this->instanceType);

        unset($this->cultureId);
        unset($this->cultureCode);
        unset($this->countries);
        unset($this->languages);
        unset($this->countryId);
        unset($this->languageId);
        unset($this->countryCode);
        unset($this->languageCode);

        unset($this->userId);
        unset($this->createdUid);
        unset($this->upatedUid);

        unset($this->paginatorService);
        unset($this->translatorService);
        unset($this->emailService);
    }
    
    /**
     * @author Employee Id: 4589
     * Description : save configuration
     *
     * @param 1 : Form $form form object
     *
     * @return : array
     *
     * @throws Exception: Null
     */
    public function setConfiguration($form)
    {
        $rewardReferralConfiguration=$form->getData();
        
        /* Create History */
        $rewardReferralConfiguration->setCreatedAt(new \DateTime());
        $rewardReferralConfiguration->setCreatedUid($this->userId);
        $rewardReferralConfiguration->setUpdatedAt(new \DateTime());
        $rewardReferralConfiguration->setUpdatedUid($this->userId);
        /* Create History */
        
        foreach ($rewardReferralConfiguration->getReferralPurchasePoint() as $referralPurchasePoint) {
            if ($referralPurchasePoint->getPurchasePointReferrer() == '') {
                $referralPurchasePoint->setPurchasePointReferrer(0);
            }
                
            $referralPurchasePoint->setRewardreferralConfigurationId($rewardReferralConfiguration);
        }
        
        $this->setdeFaultFields($rewardReferralConfiguration);
        $this->RewardReferralRepo->setData($rewardReferralConfiguration);
        $this->RewardReferralRepo->commit();
        
        return;
    }

    /**
     * @author Employee Id: 4589
     * Description : get all configuration by country
     *
     * @param 1 : Not required
     *
     * @return : array
     *
     * @throws Exception: Null
     */
    public function getConfiguration()
    {
        $countryId = $this->cultureId;
        $configuration = $this->RewardReferralRepo->findConfigurationFromInstance($countryId);
        if ($configuration && $configuration->getStatus() == 1) {
            return $configuration;
        } else {
            throw new NotFoundHttpException($this->translatorService->trans('admin.referral.not_found'));
        }
    }
    
    /**
     * @author Employee Id: 4589
     * Description : list of earn points by user
     *
     * @param 1 : int $userId user id
     *
     * @return : array
     *
     * @throws Exception: Null
     */
    public function getEarnHistory($userId)
    {
        $page = $this->request->get('page', 1);
        $recordsPerPage = $this->configurationRule['reward_referral']['option']['record_per_page']['status'];
        $earnPointHistory = $this->rewardEarnHistoryRepository->getEarnHisotry($userId);
        
        return $this->paginatorService->paginate($earnPointHistory, $page, $recordsPerPage, array(), count($earnPointHistory));
    }
    
    /**
     * @author Employee Id: 4589
     * Description : list of redeem points by user
     *
     * @param 1 : int $userId user id
     *
     * @return : array
     *
     * @throws Exception: Null
     */
    public function getRedeemHistory($userId)
    {
        $page = $this->request->get('page', 1);
        $recordsPerPage = $this->configurationRule['reward_referral']['option']['record_per_page']['status'];
        $earnPointHistory = $this->rewardRedeemHistoryRepository->getRedeemHisotry($userId);
        
        return $this->paginatorService->paginate($earnPointHistory, $page, $recordsPerPage, array(), count($earnPointHistory));
    }
    
    /**
     * @author Employee Id: 4589
     * Description : generate referral code base on email, sender id and time
     *
     * @param 1 : ReferralRecipient $referralRecipient referral recipient entity object.
     *
     * @return : string base64 encoded referral code as string.
     *
     * @throws Exception: Null
     */
    public function generateReferralCode($referralRecipient)
    {
        return base64_encode($referralRecipient->getEmail().$this->encodeSep.$this->userId.$this->encodeSep.time());
    }
    
    /**
     * @author Employee Id: 4589
     * Description : decode referral code
     *
     * @param 1 : ReferralRecipient $referralRecipient referral recipient entity object.
     *
     * @return : string base64 decoded referral code as string.
     *
     * @throws Exception: Null
     */
    public function decodeReferralCode($referralRecipient)
    {
        $code = base64_decode($referralRecipient);
        $codeArray = explode($this->encodeSep, $code);
        if (isset($codeArray[0]) && isset($codeArray[1])) {
            return array("email"=>$codeArray[0],"senderId"=>$codeArray[1]);
        } else {
            return false;
        }
    }
    
    /**
     * @author Employee Id: 4589
     * Description : get total point by user
     *
     * @param 1 : int $userId user id
     *
     * @return : int total points
     *
     * @throws Exception: Null
     */
    public function getTotalPointByUser($userId)
    {
        $configuration = $this->getConfiguration($this->cultureId);
        
        $referralPointRepo = $this->entityManager->getRepository("OfficeBrainRewardReferralBundle:ReferralPoint");
        $referralPointRepo->setProjectSetting($this->projectSetting, $configuration);
        
        $referralPoint = $referralPointRepo->getPointByUserId($userId);
        if ($referralPoint) {
            if ($referralPoint->getPoint() < 0) {
                return 0;
            } else {
                return $referralPoint->getPoint();
            }
        }
        
        return 0;
    }
    
     /**
     * @author Employee Id: 4494
     * Description : Set the default fields.
     *
     * @param1: RewardReferral Object
     *
     * @return type : NULL.
     *
     * @throws Exception: Null
     */
     public function setdeFaultFields($rewardReferralConfiguration)
     {
         $rewardReferralConfiguration->setInstanceId($this->request->get('project_setting')['instance_id']);
         $rewardReferralConfiguration->setInstanceType($this->request->get('project_setting')['instance_type']);

         return;
     }
    
    /**
     * @author Employee Id: 4835
     * Description :get form
     *
     * @param 1 : object $contrpller
     *
     * @return array
     *
     * @throws Exception : Null
     * */
    
    public function getForm(Controller $controller)
    {
        $countryId=$this->request->get('countryId', $this->cultureId);
      
        $rewardReferralObj=$this->RewardReferralRepo->findConfigurationFromInstance($countryId);
       
        if ($rewardReferralObj == null) {
            $rewardReferralObj = new RewardReferralConfiguration();
            $form = $controller->createForm(new RewardReferralConfigurationType($countryId), $rewardReferralObj);
            $form->handleRequest($this->request);
        } else {
            $form = $controller->createForm(new RewardReferralConfigurationType($countryId), $rewardReferralObj);
            $form->handleRequest($this->request);
        }
        
        
        return $form;
    }
}
