<?php

namespace OfficeBrain\Bundle\RewardReferralBundle\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\JsonResponse;

/**
 * @author OfficeBrain 4589 <info@officebrain.com>
 *
 * Description : Refer a friend and get some points
 *
 * @Route("/{_locale}")
 **/
class ReferralController extends Controller
{
    protected $request;
    protected $userId;
    protected $refererUrl;
    protected $responseArray;
    protected $projectSetting;
    protected $rewardReferralManager;


    public function __construct()
    {
        $this->request = null;
        $this->userId = null;
        $this->refererUrl = null;
        $this->responseArray = array();
        $this->projectSetting = null;
        $this->rewardReferralManager = null;
    }

    public function __destruct()
    {
        unset($this->request);
        unset($this->userId);
        unset($this->refererUrl);
        unset($this->responseArray);
        unset($this->projectSetting);
        unset($this->rewardReferralManager);
    }
    
    public function initAction()
    {
        $this->request = $this->getRequest();
        $this->projectSetting = $this->request->get('project_setting');

        $this->page = $this->request->get('page', 1);
        $this->userId = $this->projectSetting['user_id'];
        $this->responseArray['status'] = 'error';

        $this->rewardReferralManager = $this->get('office_brain_reward_referral_manager');
        $this->commonLibrary = $this->get('office_brain_common_library');
    }
        
    /**
     * @author Employee Id: 4589
     * Description : render invitation to friend form
     *
     * @param 1 : NULL
     *
     * @return : array data
     *
     * @throws Exception: Null
     *
     * @Route("/refer-a-friend",
     * 	name="office_brain_rewardreferralbundle_referral_referafriend",
     *  options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainRewardReferralBundle:Referral:add.html.twig")
     */
    public function ReferAFriendAction()
    {
        $this->initAction();
        
        if ($this->userId > 0) {
            $configuration = $this->rewardReferralManager->getConfiguration();
            $singleAttemptMaxLimit = $configuration->getMaxReferralSingleAttemptLimit();

            $form = $this->rewardReferralManager->createForm($this);

            $this->responseArray['form'] = $form->createView();
            $this->responseArray['single_attempt_max_limit'] = $singleAttemptMaxLimit;
        } else {
            //TODO : redirect to login page
        }
        
        return $this->responseArray;
    }
            

    /**
     * @author Employee Id: 4589
     * Description : send invitation to friend
     *
     * @param 1 : NULL
     *
     * @return : array data
     *
     * @throws Exception: Null
     *
     * @Route("/refer-a-friend",
     * 	name="office_brain_rewardreferralbundle_referral_processreferafriend",
     *  options={"expose"=true}
     * )
     * @Method({"POST"})
     * @Template("OfficeBrainRewardReferralBundle:Referral:add.html.twig")
     */
    public function processReferAFriendAction()
    {
        $this->initAction();
        
        if ($this->userId > 0) {
            $form = $this->rewardReferralManager->createForm($this);

            if ($this->rewardReferralManager->setReferAFriend($form) === true) {
                $this->get('session')->getFlashBag()->add('success_message', $this->get('translator')->trans("referral.form.success"));
                return $this->redirect($this->generateUrl('office_brain_rewardreferralbundle_referral_referafriend'));
            }

            $this->responseArray['form'] = $form->createView();
        } else {
            //TODO : redirect to login page
        }
        
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4589
     * Description : check email already registered or send invitation
     *
     * @param 1 : NULL
     *
     * @return : string json encoded string
     *
     * @throws Exception: Null
     *
     * @Route("/check-email",
     * 	name="office_brain_rewardreferralbundle_referral_isemailexistsajax",
     *  options={"expose"=true}
     * )
     * @Method({"POST"})
     */
    public function isEmailExistsAjaxAction()
    {
        $this->initAction();
        
        //check is request duplicate
        $email = $this->request->get('email', '');
        if (!$this->rewardReferralManager->isRequestSent($email)) {
            $this->responseArray['status'] = "success";
        } else {
            $this->responseArray['status'] = "error";
            $this->responseArray['error_message'] = $this->get('translator')->trans("referral.form.error.duplicate_email_request");
        }
        
        //TODO : Check email already registered in our system
        //$this->responseArray['error_message'] = $this->get('translator')->trans('referral.form.error.duplicate_email');
        
        return new JsonResponse($this->responseArray);
    }
    
    /**
     * @author Employee Id: 4589
     * Description : Reward point earn and redeem history
     *
     * @param 1 : NULL
     *
     * @return : array data
     *
     * @throws Exception: Null
     *
     * @Route("/my-account/reward-point",
     * 	name="office_brain_rewardreferralbundle_referral_rewardpoint",
     *  options={"expose"=true}
     * )
     * @Method({"GET","POST"})
     * @Template("OfficeBrainRewardReferralBundle:Referral:list.html.twig")
     */
    public function rewardPointAction()
    {
        $this->initAction();
        
        if ($this->userId > 0) {
            $this->responseArray['total_reward_point'] = $this->rewardReferralManager->getTotalPointByUser($this->userId);
            $this->responseArray['pagination']['earn_history'] = $this->rewardReferralManager->getEarnHistory($this->userId);
            $this->responseArray['pagination']['redeem_history'] = $this->rewardReferralManager->getRedeemHistory($this->userId);
        } else {
            //TODO : redirect to login page
        }
        
        return $this->responseArray;
    }
}
