<?php

namespace OfficeBrain\Bundle\EmailBundle\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 OfficeBrain\Bundle\EmailBundle\Entity\EmailTemplateMaster;
use OfficeBrain\Bundle\EmailBundle\Entity\EmailTemplateLanguage;
use OfficeBrain\Bundle\EmailBundle\Form\EmailTemplateMasterType;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * @author OfficeBrain 4795 <info@officebrain.com>
 *
 * Description: Manage templates of email
 *
 * @Route("/admin/{_locale}")
 */
class EmailTemplateAdminController 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;
        $this->language = array();
    }
    
    /**
     * @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);
        unset($this->language);
    }
    
    /**
     * @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->language = $this->container->getParameter('language');
        $this->imagePath = $this->getParameter('base_url');
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Get all templates
     *
     * @param 1 : Null
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/list-template/",
     * name="office_brain_emailbundle_emailtemplateadmin_listtemplate")
     *
     * @Method("GET")
     *
     * @Template("OfficeBrainEmailBundle:EmailTemplateAdmin:listTemplate.html.twig")
     */
    public function listTemplateAction()
    {
        $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: 4795
     *
     * Description : Get all templates
     *
     * @param 1 : Null
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/list-template/",
     * name="office_brain_emailbundle_emailtemplateadmin_listtemplateajax")
     *
     * @Method("POST")
     *
     * @Template("OfficeBrainEmailBundle:EmailTemplateAdmin:listTemplateAjax.html.twig")
     */
    public function listTemplateAjaxAction()
    {
        $this->initAction();
        
        $page  = $this->request->get('page', '1');
        $language = $this->request->get('language');
        $keyword = $this->request->get('keyword');
        $recordsPerPage = $this->projectSettings['configuration_rule']['site_management']['option']['email']['option']['email_record_per_page']['status'];
        
        $templates = $this->emailTemplateManager->searchTemplate($language, $keyword);
    
        $paginator  = $this->get('knp_paginator');
        
        $this->responseArray['pagination'] = $paginator->paginate($templates, $page, $recordsPerPage, array(), count($templates));
        $this->responseArray['language'] = $language;
        
        //unset variable
        unset($page);
        unset($language);
        unset($recordsPerPage);
        unset($templates);
        unset($paginator);
        
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Generate for for add template
     *
     * @param 1 : Null
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/add-template", name="office_brain_emailbundle_emailtemplateadmin_addtemplate")
     *
     * @Method("GET")
     *
     * @Template("OfficeBrainEmailBundle:EmailTemplateAdmin:addTemplate.html.twig")
     */
    public function addTemplateAction()
    {
    	$this->initAction();

        $this->responseArray['form'] = $this->getForm()->createView();
        
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Store template data to database
     *
     * @param 1 : Null
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/add-template", name="office_brain_emailbundle_emailtemplateadmin_addtemplatesubmit")
     *
     * @Method("POST")
     *
     * @Template("OfficeBrainEmailBundle:EmailTemplateAdmin:addTemplate.html.twig")
     */
    public function addTemplateSubmitAction()
    {
        $this->initAction();
        $form = $this->getForm();
         
        $form->handleRequest($this->request);
        
        if ($form->isValid()) {
            if (is_object($this->emailTemplateManager->setTemplate($form->getData()))) {
                $this->get('session')->getFlashBag()->add('success_message', $this->translator->trans('email.template.message.add_success'));
                
                return $this->redirect($this->generateUrl('office_brain_emailbundle_emailtemplateadmin_listtemplate'));
            }
            
            $this->get('session')->getFlashBag()->add('error_message', $this->translator->trans('email.template.message.add_error'));
        }
        
        $this->get('session')->getFlashBag()->add('error_message', $this->translator->trans('email.template.message.generic_error'));
        
        $this->responseArray['form'] = $form->createView();
        
        //unset variable
        unset($form);
        
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Generate form for edit template
     *
     * @param 1 : Template Id
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/edit-template/{id}", name="office_brain_emailbundle_emailtemplateadmin_edittemplate")
     *
     * @Method("GET")
     *
     * @Template("OfficeBrainEmailBundle:EmailTemplateAdmin:editTemplate.html.twig")
     */
    public function editTemplateAction($id)
    {
        $this->initAction();
        
        $this->responseArray['form'] = $this->getEditForm($id)->createView();
        
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Update template data
     *
     * @param 1 : Template Id
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/edit-template/{id}", name="office_brain_emailbundle_emailtemplateadmin_edittemplatesubmit")
     *
     * @Method("POST")
     *
     * @Template("OfficeBrainEmailBundle:EmailTemplateAdmin:editTemplate.html.twig")
     */
    public function editTemplateSubmitAction($id)
    {
        $this->initAction();
        
        $form = $this->getEditForm($id);
        $form->handleRequest($this->request);
         
        if ($form->isValid()) {
            if (is_object($this->emailTemplateManager->updateTemplate($form->getData()))) {
                $this->get('session')->getFlashBag()->add('success_message', $this->translator->trans('email.template.message.edit_success'));
                
                return $this->redirect($this->generateUrl('office_brain_emailbundle_emailtemplateadmin_listtemplate'));
            }
            
            $this->get('session')->getFlashBag()->add('error_message', $this->translator->trans('email.template.message.edit_error'));
        }
        
        $this->get('session')->getFlashBag()->add('error_message', $this->translator->trans('email.template.message.generic_error'));
        
        $this->responseArray['form'] = $form->createView();
        
        //unset variable
        unset($form);
        
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Search template by keyword
     *
     * @param 1 : Null
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/search-template/",
     * name="office_brain_emailbundle_emailtemplateadmin_searchtemplateajax")
     *
     * @Method({"GET", "POST"})
     *
     * @Template("OfficeBrainEmailBundle:EmailTemplateAdmin:listTemplateAjax.html.twig")
     */
    public function searchTemplateAjaxAction()
    {
        $this->initAction();
        
        $page  = $this->request->get('page', '1');
        $language  = $this->request->get('language');
        $keyword = $this->request->get('keyword');
        $recordsPerPage = $this->projectSettings['configuration_rule']['site_management']['option']['email']['option']['email_record_per_page']['status'];
        
        $templates = $this->emailTemplateManager->searchTemplate($language, $keyword);
    
        $paginator  = $this->get('knp_paginator');
        
        $this->responseArray['pagination'] = $paginator->paginate($templates, $page, $recordsPerPage, array(), count($templates));
        $this->responseArray['language'] = $language;
        
        //unset variable
        unset($page);
        unset($language);
        unset($keyword);
        unset($recordsPerPage);
        unset($templates);
        unset($paginator);
        
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Get Template Content
     *
     * @param 1 : Null
     *
     * @return type : Json Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/get-template", name="office_brain_emailbundle_emailtemplateadmin_gettemplate")
     *
     * @Method("POST")
     */
    public function getTemplateContentAction()
    {
        $this->initAction();
        
        $id = $this->request->get('id');
        if($id != ''){
        $template = $this->emailTemplateManager->getPredefinedTemplate($id);
        $content = preg_replace('/images/', $this->imagePath.'/images', $template->getContent());
        }else{
         $content = '';   
        }
        if ($this->request->isXmlHttpRequest()) {
            return new JsonResponse($content);
        }
        
        return $content;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Preview Template
     *
     * @param 1 : Template Id
     * @param 2 : Language Id
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/preview-template/{id}/{language}", name="office_brain_emailbundle_emailtemplateadmin_previewtemplate")
     *
     * @Method("GET")
     *
     * @Template("OfficeBrainEmailBundle:EmailTemplateAdmin:previewTemplate.html.twig")
     */
    public function previewTemplateAction($id, $language)
    {
        $this->initAction();
        $languageId=$this->getlanguageField($language);
        $this->responseArray['html'] = $this->emailTemplateManager->previewTemplate($id, $languageId);
        
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Preview Template
     *
     * @param 1 : Null
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/preview-template", name="office_brain_emailbundle_emailtemplateadmin_previewtemplatedata")
     *
     * @Method("POST")
     *
     * @Template("OfficeBrainEmailBundle:EmailTemplateAdmin:previewTemplate.html.twig")
     */
    public function previewTemplateDataAction()
    {
        $this->initAction();
        
        $content = $this->request->get('content');
        $culture = $this->request->get('culture');
        $headerId = $this->request->get('header');
        
        $this->responseArray['html'] = $this->emailTemplateManager->getPreviewTemplateData($content, $culture, $headerId);
        
        //unset variable
        unset($content);
        unset($culture);
        unset($headerId);
        
        return $this->responseArray;
    }
     /**
     *
     * @author Employee Id: 4835
     *
     * Description : Change Status template.
     *
     * @param 1 : Template Id
     *
     * @return type : JsonResponse object
     *
     * @throws Exception: No exception
     *
     * @Route("/email/change-status/{instance_id}", name="office_brain_emailbundle_emailtemplateadmin_change_status",
     * requirements={"instance_id"="\d+"},
     * defaults={"instance_id"="0"},
     * options={"expose"=true}
     * )
     *
     * @Method({"POST"})
     *
     * @Template()
     *
     */
    public function changeStatusAction()
    {
    	$this->initAction();
    
    	$id = $this->request->get('id');
        if ($id) {
    		$status = $this->emailTemplateManager->changeTemplateStatus($id);
    		if ($status) {
    			return new JsonResponse(array('status' => 'success', 'status_message' => $this->translator->trans('email.template.message.status_success')));
    		}
    	}
    
    	return new JsonResponse(array('status' => 'fail', 'status_message' => $this->translator->trans('email.template.message.status_error')));
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Delete Template
     *
     * @param 1 : Template Id
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/delete-template/{id}", name="office_brain_emailbundle_emailtemplateadmin_deletetemplate")
     *
     * @Method("GET")
     */
    public function deleteTemplateAction($id)
    {
        $this->initAction();
        
        $this->emailTemplateManager->deleteTemplate($id);
        
        return $this->redirect($this->generateUrl('office_brain_emailbundle_emailtemplateadmin_listtemplate'));
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Generate duplicate template
     *
     * @param 1 : Template Id
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/duplicate-template/{id}", name="office_brain_emailbundle_emailtemplateadmin_duplicatetemplate")
     *
     * @Method("GET")
     */
    public function duplicateTemplateAction($id)
    {
        $this->initAction();
        
        $templateObj = new EmailTemplateMaster();
        $templateLangObj = new EmailTemplateLanguage();
        
        $duplicateId = $this->emailTemplateManager->duplicateTemplate($id, $templateObj, $templateLangObj);
        
        //unset variable
        unset($templateObj);
        unset($templateLangObj);
        
        return $this->redirect($this->generateUrl('office_brain_emailbundle_emailtemplateadmin_edittemplate', array('id'=>$duplicateId)));
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Get Default Template Content
     *
     * @param 1 : Null
     *
     * @return type : Json Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/get-default-template", name="office_brain_emailbundle_emailtemplateadmin_getdefaulttemplate")
     *
     * @Method("GET")
     */
    public function getDefaultTemplateContentAction()
    {
        $this->initAction();
        
        $template = $this->emailTemplateManager->getDefaultTemplate();
        $contentArr = array();
        
        foreach ($template->getContent() as  $val) {
            $contentArr[$val->getLanguageId()] = $val->getTemplateContent();
        }
        
        //unset variable
        unset($template);
        
        if ($this->request->isXmlHttpRequest()) {
            return new JsonResponse($contentArr);
        }
        
        return $contentArr;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Create edit form
     *
     * @param 1 : Template Id
     *
     * @return type : Form
     *
     * @throws Exception: Null
     */
    public function getEditForm($id)
    {
        $language = $this->getParameter('language');
        $template_master = $this->emailTemplateManager->getTemplate($id);
        
        foreach ($template_master->getContent() as $value) {
            $template_master->getContent()[$value->getLanguageId()] = $value;
        }
        
        if (is_object($template_master->getContent()[0])) {
            unset($template_master->getContent()[0]);
        }
        
        foreach ($language as $val) {
            if (!array_key_exists($val['id'], $template_master->getContent()->toArray())) {
                $template_lang = new EmailTemplateLanguage();
                $template_lang->languageId = $val['id'];
                $template_master->getContent()[$val['id']] = $template_lang;
            }
        }
        
        $form = $this->createForm(new EmailTemplateMasterType($this->projectSettings), $template_master);
        
        //unset variable
        unset($language);
        unset($template_master);
        
        return $form;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Create add form of template
     *
     * @param 1 : Null
     *
     * @return type : Form
     *
     * @throws Exception: Null
     */
    public function getForm()
    {
        $language = $this->getParameter('language');
        $template_master = new EmailTemplateMaster();
         
        foreach ($language as $key=>$value) {
            $template_lang = new EmailTemplateLanguage();
            $template_lang->languageId = $value['id'];
            $template_master->getContent()[$value['id']] = ($template_lang);
        }

        $form = $this->createForm(new EmailTemplateMasterType($this->projectSettings), $template_master);
        
        //unset variable
        unset($language);
        unset($template_master);
        
        return $form;
    }
    
    /**
     * @author Employee Id: 4835
     * Description : get country filed
     *
     * @param 1 : array  $languageid
     *
     * @return: data
     *
     * @throws Exception : Null
     * */
    public function getlanguageField($langcode)
    {
        $languages = $this->language;
        foreach ($languages as $key => $lang) {
            if ($key == $langcode) {
              return $lang['id'];
            }
        }
    }
    
   
}
