<?php

namespace OfficeBrain\Bundle\EmailBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use OfficeBrain\Bundle\EmailBundle\Entity\EmailTemplateHeaderMaster;
use OfficeBrain\Bundle\EmailBundle\Entity\EmailTemplateHeaderLanguage;
use OfficeBrain\Bundle\EmailBundle\Form\EmailTemplateHeaderMasterType;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * @author OfficeBrain 4795 <info@officebrain.com>
 *
 * Decription: Manage template headers
 *
 * @Route("/admin/{_locale}")
 */
class EmailTemplateHeaderAdminController extends Controller
{
    /**
     * @author Employee Id: 4795
     *
     * Description : Set variables
     *
     * @param 1 : Null
     *
     * @return type : Null
     *
     * @throws Exception: Null
     **/
    public function __construct()
    {
        $this->responseArray = array();
        $this->request = null;
        $this->emailTemplateManager = null;
        $this->projectSetting = array();
        $this->accessRules = array();
        $this->translator = null;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Unset variables
     *
     * @param 1 : Null
     *
     * @return type : Null
     *
     * @throws Exception: Null
     **/
    public function __destruct()
    {
        unset($this->responseArray);
        unset($this->request);
        unset($this->emailTemplateManager);
        unset($this->projectSetting);
        unset($this->accessRules);
        unset($this->translator);
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Set request and service
     *
     * @param 1 : Null
     *
     * @return type : Null
     *
     * @throws Exception: Null
     **/
    public function initAction()
    {
        $this->request = $this->getRequest();
        $this->projectSettings = $this->request->get('project_setting');
        $this->accessRules = $this->projectSettings['access_rule'];
        $this->emailTemplateManager = $this->get('office_brain_email_template_manager');
        $this->translator = $this->get('translator');
        $this->imagePath = $this->getParameter('base_url');
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Return all headers
     *
     * @param 1 : Null
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/list-header",
     * name="office_brain_emailbundle_emailtemplateheaderadmin_listheader")
     *
     * @Method("GET")
     *
     * @Template("OfficeBrainEmailBundle:EmailTemplateHeaderAdmin:listHeader.html.twig")
     */
    public function listHeaderAction()
    {
       	$this->initAction();
       	$culture=$this->request->get('_locale');
       	$language=explode('_',$culture);
       	$this->responseArray['page']  = $this->request->get('page', '1');
       	$this->responseArray['keyword'] = $this->request->get('keyword','');
       	$this->responseArray['singlelanguage']= $language[0];
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4835
     *
     * Description : Return all headers through ajax response
     *
     * @param 1 : Null
     *
     * @return type : ajax Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/list-header",
     * name="office_brain_emailbundle_emailtemplateheaderadmin_listheaderajax")
     *
     * @Template("OfficeBrainEmailBundle:EmailTemplateHeaderAdmin:listHeaderAjax.html.twig")
     */
    public function listHeaderAjaxAction()
    {
        $this->initAction();
        $page  = $this->request->get('page', '1');
        $language = $this->request->get('language');
        $dataArr['keyword'] = $this->request->get('keyword');
        $recordsPerPage = $this->projectSettings['configuration_rule']['site_management']['option']['email']['option']['email_record_per_page']['status'];
        $headers = $this->emailTemplateManager->getHeaderList( $language,$dataArr);
        
        $paginator  = $this->get('knp_paginator');
        $this->responseArray['pagination'] = $paginator->paginate($headers, $page, $recordsPerPage, array(), count($headers));
        $this->responseArray['language'] = $language;
        
        //unset variable
        unset($page);
        unset($language);
        unset($recordsPerPage);
        unset($headers);
        unset($paginator);
        
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Generate header form
     *
     * @param 1 : Null
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/add-header", name="office_brain_emailbundle_emailtemplateheaderadmin_addheader")
     *
     * @Method("GET")
     *
     * @Template("OfficeBrainEmailBundle:EmailTemplateHeaderAdmin:addHeader.html.twig")
     */
    public function addHeaderAction()
    {
        $this->responseArray['form'] = $this->getForm()->createView();
        
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Store header data to database
     *
     * @param 1 : Null
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/add-header", name="office_brain_emailbundle_emailtemplateheaderadmin_addheadersubmit")
     *
     * @Method("POST")
     *
     * @Template("OfficeBrainEmailBundle:EmailTemplateHeaderAdmin:addHeader.html.twig")
     */
    public function addHeaderSubmitAction()
    {
        $this->initAction();
        
        $form = $this->getForm();
        $form->handleRequest($this->request);
         
        if ($form->isValid()) {
            $this->emailTemplateManager->setHeader($form->getData());
            $this->get('session')->getFlashBag()->add('success_message', $this->translator->trans('email.header.message.add_success'));
            
            return $this->redirect($this->generateUrl('office_brain_emailbundle_emailtemplateheaderadmin_listheader'));
        }
        
        $this->get('session')->getFlashBag()->add('error_message', $this->translator->trans('email.header.message.generic_error'));
        
        $this->responseArray['form'] = $form->createView();
        
        //unset variable
        unset($form);
        
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Generate edit header form
     *
     * @param 1 : Header Id
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/edit-header/{id}", name="office_brain_emailbundle_emailtemplateheaderadmin_editheader")
     *
     * @Method("GET")
     *
     * @Template("OfficeBrainEmailBundle:EmailTemplateHeaderAdmin:editHeader.html.twig")
     */
    public function editHeaderAction($id)
    {
        $this->initAction();
        
        $this->responseArray['form'] = $this->getEditForm($id)->createView();
        
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Update header data
     *
     * @param 1 : Header Id
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/edit-header/{id}", name="office_brain_emailbundle_emailtemplateheaderadmin_editheadersubmit")
     *
     * @Method("POST")
     *
     * @Template("OfficeBrainEmailBundle:EmailTemplateHeaderAdmin:editHeader.html.twig")
     */
    public function editHeaderSubmitAction($id)
    {
        $this->initAction();
        
        $form = $this->getEditForm($id);
        $form->handleRequest($this->request);
        
        if ($form->isValid()) {
            
            $this->emailTemplateManager->updateHeader($form->getData());
            $this->get('session')->getFlashBag()->add('success_message', $this->translator->trans('email.header.message.edit_success'));
            
            return $this->redirect($this->generateUrl('office_brain_emailbundle_emailtemplateheaderadmin_listheader'));
        }
        
        $this->get('session')->getFlashBag()->add('error_message', $this->translator->trans('email.header.message.generic_error'));
        
        $this->responseArray['form'] = $form->createView();
        
        //unset variable
        unset($form);
        
        return $this->responseArray;
    }
    
    
    /**
     * @author Employee Id: 4795
     *
     * Description : View header
     *
     * @param 1 : Header Id
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/view-header/{id}", name="office_brain_emailbundle_emailtemplateheaderadmin_viewheader")
     *
     * @Method("GET")
     *
     * @Template("OfficeBrainEmailBundle:EmailTemplateHeaderAdmin:viewHeader.html.twig")
     */
    public function viewHeaderAction($id)
    {
        $this->initAction();
        
        $this->responseArray['header'] = $this->emailTemplateManager->getHeader($id);
        
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Soft delete header from database
     *
     * @param 1 : Header Id
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/delete-header/{id}", name="office_brain_emailbundle_emailtemplateheaderadmin_deleteheader")
     *
     * @Method("GET")
     */
    public function deleteHeaderAction($id)
    {
        $this->initAction();
        
        $this->emailTemplateManager->deleteHeader($id);
        
        //unset variable
        unset($data);
        
        return $this->redirect($this->generateUrl('office_brain_emailbundle_emailtemplateheaderadmin_listheader'));
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Get Header Content
     *
     * @param 1 : Null
     *
     * @return type : Json Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/get-predefined-header", name="office_brain_emailbundle_emailheaderadmin_getheader")
     *
     * @Template("OfficeBrainEmailBundle:EmailTemplateHeaderAdmin:contentHeader.html.twig")
     *
     * @Method("POST")
     */
    public function getPredefinedHeaderContentAction()
    {
        $this->initAction();
        
        $id = $this->request->get('id');
        if($id != ''){
        $header = $this->emailTemplateManager->getPredefinedHeader($id);
        $this->responseArray['header_content'] =  preg_replace('/images/', $this->imagePath.'/images', $header->getContent());
        
        //unset variable
        unset($id);
        unset($header);
        
        if ($this->request->isXmlHttpRequest()) {
            return new JsonResponse($this->responseArray['header_content']);
        }
        }else{
             $this->responseArray['header_content'] =  '';
        }
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Get Header Content
     *
     * @param 1 : Null
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/get-header", name="office_brain_emailbundle_emailheaderadmin_getheadercontent")
     *
     * @Template("OfficeBrainEmailBundle:EmailTemplateHeaderAdmin:contentHeader.html.twig")
     *
     * @Method("POST")
     */
    public function getHeaderContentAction()
    {
        $this->initAction();
        
        $id = $this->request->get('id');
        if($id != ''){
        $language = $this->request->get('language');
        $content = null;
        
        $header = $this->emailTemplateManager->getHeader($id);
        
        foreach ($header->getContent() as $val) {
            if ($val->getLanguageId() == $language) {
                $content = $val->getHeaderContent();
                break;
            }
        }
        $this->responseArray['header_content'] = $content;
        unset($header);
        unset($content);
        }else{
           $this->responseArray['header_content'] = '';  
        }
        //unset variable
        unset($id);
        
        if ($this->request->isXmlHttpRequest()) {
            return new JsonResponse(array('header_content' => $this->responseArray['header_content']));
        } else {
            return $this->responseArray;
        }
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Preview Header
     *
     * @param 1 : Null
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/preview-header", name="office_brain_emailbundle_emailheaderadmin_previewheader")
     *
     * @Method("POST")
     *
     * @Template("OfficeBrainEmailBundle:EmailTemplateHeaderAdmin:previewHeader.html.twig")
     */
    public function previewHeaderAction()
    {
        $this->initAction();
        
        $content = $this->request->get('content');
        $culture = $this->request->get('culture');
          
        $header = $this->emailTemplateManager->getPreviewHeaderData($content, $culture);
         
        $this->responseArray['html'] = $header;
        
        //unset variable
        unset($header);
        unset($content);
        unset($culture);
        
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Create edit form
     *
     * @param 1 : Header Id
     *
     * @return type : Form
     *
     * @throws Exception: Null
     */
    public function getEditForm($id)
    {
        $language = $this->getParameter('language');
        
        $header_master = $this->emailTemplateManager->getHeader($id);
        $lang_data = $header_master->getContent();
        
        foreach ($lang_data as $key=>$value) {
            $header_master->getContent()[$value->getLanguageId()] = $value;
        }
        if (is_object($header_master->getContent()[0])) {
            unset($header_master->getContent()[0]);
        }
        foreach ($language as $val) {
            if (!array_key_exists($val['id'], $header_master->getContent()->toArray())) {
                $header_lang = new EmailTemplateHeaderLanguage();
                $header_lang->setLanguageId($val['id']);
                $header_master->getContent()[$val['id']] = $header_lang;
            }
        }
        
        $emailTemplateHeaderMasterObj = new EmailTemplateHeaderMasterType();
        $form = $this->createForm($emailTemplateHeaderMasterObj, $header_master);
        $emailTemplateHeaderMasterObj->setEmailTemplateManager($this->emailTemplateManager);
        $emailTemplateHeaderMasterObj->setForm($form);
        //unset variable
        unset($language);
        unset($header_master);
        unset($lang_data);
        
        return $form;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Create add form of header
     *
     * @param 1 : Null
     *
     * @return type : Form
     *
     * @throws Exception: Null
     */
    public function getForm()
    {
        $language = $this->getParameter('language');
        $header_master = new EmailTemplateHeaderMaster();

        foreach ($language as $value) {
            $header_lang = new EmailTemplateHeaderLanguage();
            $header_lang->setLanguageId($value['id']);
            $header_master->getContent()[$value['id']] = $header_lang;
        }

        $emailTemplateHeaderMasterObj = new EmailTemplateHeaderMasterType();
        $form = $this->createForm($emailTemplateHeaderMasterObj, $header_master);
        $emailTemplateHeaderMasterObj->setEmailTemplateManager($this->emailTemplateManager);
        $emailTemplateHeaderMasterObj->setForm($form);
        
        //unset variable
        unset($language);
        unset($header_master);

        return $form;
    }
}
