<?php

namespace OfficeBrain\Bundle\EmailBundle\Manager\Extended;

use OfficeBrain\Bundle\EmailBundle\Manager\AbstractManager\EmailTemplateAbstract;
use OfficeBrain\Bundle\EmailBundle\Entity\EmailTemplateLanguage;

/**
 * @author OfficeBrain 4795 <info@officebrain.com>
 *
 * Description: All custom and overrided methods
 */
class EmailTemplateExtended extends EmailTemplateAbstract
{
    public $imagePath;
    
    public function __construct($container, $request)
    {
        parent::__construct($container, $request);
        $this->imagePath = $container->getParameter('base_url');
   
    }
    
    public function __destruct()
    {
        parent::__destruct();
    }
    
    /** Start of template methods **/
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Set template data and store on DB
     *
     * @param 1 : EmailTemplate Object.
     *
     * @return type : EmailTemplate Object.
     *
     * @throws Exception: Null
     */
    public function setTemplate($emailTemplate)
    {
        if ($emailTemplate->getIsDefault() == 1) {
            $this->templateRepo->updateDefaultTemplate();
        }
        $emailTemplate->setCreatedUid($this->createdUid);
        $emailTemplate->setInstanceId($this->instanceId);
        $emailTemplate->setInstanceType($this->instanceType);
        $emailTemplate->setCreatedAt(new \DateTime());
        $template = $this->commit($emailTemplate);
        $contentdata = $emailTemplate->getContent()->toArray();
        foreach ($contentdata as $key=>$value) {
            $contentObj = $value;
            $contentObj->setTemplateId($emailTemplate);
            $this->commit($contentObj);
        }
        return $template;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Get all template list
     *
     * @param 1 : Null
     *
     * @return type : EmailTemplate List.
     *
     * @throws Exception: Null
     */
    public function getTemplateList()
    {
        return $this->templateRepo->findAll();
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Get all template list by language
     *
     * @param 1 : Language Id
     *
     * @return type : EmailTemplate List.
     *
     * @throws Exception: Null
     */
    public function getTemplateListByLanguage($language)
    {
        return $this->templateRepo->findAllByLanguage($language);
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Get single template object of requested ID
     *
     * @param 1 : EmailTemplate Id
     *
     * @return type : EmailTemplate object
     *
     * @throws Exception: Null
     */
    public function getTemplate($id)
    {
        return $this->templateRepo->find($id);
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Get predefined template
     *
     * @param 1 : EmailTemplate Id
     *
     * @return type : EmailTemplate object
     *
     * @throws Exception: Null
     */
    public function getPredefinedTemplate($id)
    {
        return $this->em->getRepository('OfficeBrainEmailBundle:EmailPredefinedTemplate')->find($id);
    }
        
    /**
     * @author Employee Id: 4795
     *
     * Description : Update template data of requested object
     *
     * @param 1 : EmailTemplate object
     *
     * @return type : EmailTemplate object.
     *
     * @throws Exception: Null
     */
    public function updateTemplate($emailTemplate)
    {
        $this->templateRepo->updateDefaultTemplate();
        $emailTemplate->setUpdatedUid($this->updatedUid);
        $emailTemplate->setInstanceId($this->instanceId);
        $emailTemplate->setInstanceType($this->instanceType);
        $emailTemplate->setUpdatedAt(new \DateTime());
        $template = $this->commit($emailTemplate);
        
        //unset variable
        unset($emailTemplate);
        
        return $template;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Search template by keyword
     *
     * @param 1 : Language id
     * @param 2 : Search keyword array
     *
     * @return type : EmailTemplate list.
     *
     * @throws Exception: Null
     */
    public function searchTemplate($language, $keyword)
    {
        return $this->templateRepo->searchTemplate($language, $keyword);
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Get default template object
     *
     * @param 1 : Null
     *
     * @return type : EmailTemplate list.
     *
     * @throws Exception: Null
     */
    public function getDefaultTemplate()
    {
        return $this->templateRepo->findDefault();
    }
        
    /**
     * @author Employee Id: 4795
     *
     * Description : Soft delete requested template
     *
     * @param 1 : EmailTemplate id
     *
     * @return type : EmailTemplate object.
     *
     * @throws Exception: Null
     */
    public function deleteTemplate($id)
    {
        $template = "";
        $templateObj = null;
        $isBinded = $this->eventRepo->hasChildEvent($id);
        if (count($isBinded) > 0) {
            $this->session->getFlashBag()->add('error_message', $this->translator->trans('email.template.message.delete_error'));
        } else {
            $templateObj = $this->templateRepo->find($id);
            $templateObj->setDeletedAt(new \DateTime());
            $template = $this->commit($templateObj);
            $this->session->getFlashBag()->add('success_message', $this->translator->trans('email.template.message.delete_success'));
        }
        
        //unset variable
        unset($isBinded);
        unset($templateObj);
        
        return $template;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Return template content for perticular language
     *
     * @param 1 : EmailTemplate id
     * @param 2 : Language Id
     *
     * @return type : EmailTemplate object.
     *
     * @throws Exception: Null
     */
    public function getTemplateContentByLanguage($templateId, $languageId)
    {
        return $this->templateLangRepo->findTemplateContentByLanguage($templateId, $languageId);
    }
    
     /**
     * @author Employee Id: 4835
     *
     * Description : change status of particular template
     *
     * @param 1 : EmailTemplate id
     
     * @return type : EmailTemplate object.
     *
     * @throws Exception: Null
     */
    public function changeTemplateStatus($id)
    {
    	return $this->templateRepo->changeTemplateStatus($id);
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Check headers in template content
     *
     * @param 1 : Email content
     *
     * @return type : Null or string
     *
     * @throws Exception: Null
     */
    public function checkHeaders($content)
    {
        foreach ($content as $key=>$val) {
            preg_match_all("/\[\[(.*?)\]/", $val->getTemplateContent(), $matches);
             
            foreach ($matches[1] as $val) {
                $header = $this->headerRepo->findHeaderByShortKey($val);
                if (count($header) <= 0) {
                    return "Please create heasder with '$val' as header short key.";
                }
            }
        }
        
        return;
    }
    
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Return content for preview template
     *
     * @param 1 : EmailTemplate Id
     * @param 2 : Language Id
     *
     * @return type : html content
     *
     * @throws Exception: Null
     */
    public function previewTemplate($id, $language)
    {
        $html = $this->getEmailTemplateStructure();
        $template = $this->templateRepo->find($id);
        if(is_object($template->getHeader())){
        $header = $template->getHeader()->getContent();
        foreach ($header as $key=>$val) {
            if ($language == $val->getLanguageId()) {
                //$headerContent = preg_replace('/images/', $this->imagePath.'/images',$val->getHeaderContent());
            	$headerContent = $val->getHeaderContent();
                $html = str_replace("[[header]]",$headerContent, $html);
            }
        }
        }else{
              $html = str_replace("[[header]]",'', $html);
        }
        foreach ($template->getContent() as $key=>$val) {
            if ($language == $val->getLanguageId()) {
                $html = str_replace("[[template_body]]", $val->getTemplateContent(), $html);
            }
        }
        
        //unset variable
        unset($header);
        unset($template);
        
        return $html;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Get Preview template data
     *
     * @param 1 : Email content
     * @param 2 : Language Id
     * @param 2 : Header id
     *
     * @return type : html content
     *
     * @throws Exception: Null
     */
    public function getPreviewTemplateData($content, $languageId, $headerId)
    {
          
        $html = $this->getEmailTemplateStructure();
        if (isset($headerId) && $headerId != "") {
            $header_content = $this->headerLangRepo->findHeaderContentByLanguage($headerId, $languageId);
            $headerContent = $header_content['headerContent']; //preg_replace('/images/', $this->imagePath.'/images',$header_content['headerContent']);
            $html = str_replace("[[header]]", $headerContent, $html);
        } else {
            $html = str_replace("[[header]]", "", $html);
        }
      
        $html = str_replace("[[template_body]]", $content, $html);
       
        return $html;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : get email template structure
     *
     * @param 1 : Null
     *
     * @return type : html content
     *
     * @throws Exception: Null
     */
    public function getEmailTemplateStructure()
    {
        $structure = "";
        $structure.= '<table width="100%" border="0" cellspacing="0" cellpadding="0" style="font-family:Arial, Helvetica, sans-serif">';
        
        $structure.= '<tr><td align="center" valign="top">[[header]]</td></tr>';
        $structure.= '<tr><td align="center" valign="top">[[template_body]]</td></tr>';
        
        $structure.= '</table>';
        
        return $structure;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Generate duplicate template of requested template
     *
     * @param 1 : Template Id
     * @param 2 : Template Object
     *
     * @return type : Template id
     *
     * @throws Exception: Null
     */
    public function duplicateTemplate($id, $templateObj)
    {
        $template = $this->templateRepo->find($id);
        
        $templateObj->setName($template->getName()." - Copy");
        $templateObj->setDescription($template->getDescription());
        $templateObj->setHeader($template->getHeader());
        $templateObj->setStatus(0);
        $templateObj->setCreatedUid($this->createdUid);
        $templateObj->setInstanceId($this->instanceId);
        $templateObj->setInstanceType($this->instanceType);
        $templateObj->setCreatedAt(new \DateTime());
        $contentdata = $template->getContent();
        $template = $this->commit($templateObj);
        foreach ($contentdata as $key=>$value) {
            $templateLangObj = new EmailTemplateLanguage();
            $templateLangObj->setTemplateId($template);
            $templateLangObj->setLanguageId($value->getLanguageId());
            $templateLangObj->setTemplateContent($value->getTemplateContent());
            $templateLang = $this->commit($templateLangObj);
        }
        
        return $template->getId();
    }
    
    /** End of template methods **/
    
    /** Start of Header methods **/
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Set and store template header data to DB
     *
     * @param 1 : Header object
     *
     * @return type : Null
     *
     * @throws Exception: Null
     */
    public function setHeader($emailTemplateHeader)
    {
        $emailTemplateHeader->setCreatedUid($this->createdUid);
        $emailTemplateHeader->setInstanceId($this->instanceId);
        $emailTemplateHeader->setInstanceType($this->instanceType);
        $emailTemplateHeader->setCreatedAt(new \DateTime());
    
        $header = $this->commit($emailTemplateHeader);
    
        $contentdata = $emailTemplateHeader->getContent()->toArray();
        foreach ($contentdata as $key=>$value) {
            $contentObj = $value;
            $contentObj->setHeaderId($emailTemplateHeader);
            $this->commit($contentObj);
        }
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Get all template header list
     *
     * @param 1 : Null
     *
     * @return type : Header list
     *
     * @throws Exception: Null
     */
    public function getHeaderList($language,$dataArr)
    {
        return $this->headerRepo->findsearchHeaders($language,$dataArr);
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Get single header object of requested ID
     *
     * @param 1 : Header Id
     *
     * @return type : Header list
     *
     * @throws Exception: Null
     */
    public function getHeader($id)
    {
        return $this->headerRepo->find($id);
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Get predefined header
     *
     * @param 1 : Header Id
     *
     * @return type : Header object
     *
     * @throws Exception: Null
     */
    public function getPredefinedHeader($id)
    {
        return $this->em->getRepository('OfficeBrainEmailBundle:EmailPredefinedHeader')->find($id);
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Update header data of rquested object
     *
     * @param 1 : Header object
     *
     * @return type : Header object
     *
     * @throws Exception: Null
     */
    public function updateHeader($emailTemplateHeader)
    {
        $emailTemplateHeader->setUpdatedUid($this->updatedUid);
        $emailTemplateHeader->setInstanceId($this->instanceId);
        $emailTemplateHeader->setInstanceType($this->instanceType);
        $emailTemplateHeader->setUpdatedAt(new \DateTime());
        $header = $this->commit($emailTemplateHeader);
        return $header;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Soft delete header of requested ID
     *
     * @param 1 : Header id
     *
     * @return type : Success message array
     *
     * @throws Exception: Null
     */
    public function deleteHeader($id)
    {
        $isBinded = $this->templateRepo->hasAssignedtoTemplate($id);
        if ($isBinded > 0)
        {
            $this->session->getFlashBag()->add('error_message', $this->translator->trans('email.header.message.delete_error'));
        } 
        else 
        {
        $currentDateTime = new \DateTime();
        $headerObj = $this->headerRepo->find($id);
        $headerObj->setDeletedAt($currentDateTime);
        $headerObj->setName($headerObj->getName()."_".$currentDateTime->format('mdyhms'));
        $this->commit($headerObj);
        $this->session->getFlashBag()->add('success_message', $this->translator->trans('email.header.message.delete_success'));
        
        //unset variable
        unset($headerObj);
        unset($currentDateTime);
        
        }
        unset($isBinded);
        return;
    }
   
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Get Preview header data
     *
     * @param 1 : Html Content
     * @param 1 : Language Id
     *
     * @return type : Success message array
     *
     * @throws Exception: Null
     */
    public function getPreviewHeaderData($content, $languageId)
    {
         
        /*$content = $this->getContentWithHeaders($content,$languageId);
    	 
    	$params = array('fname'=>'Haresh','lname'=>'Chaudhari','designation'=>'Software Developer','products'=>array('name'=>'iPhone'));
    	//$content = $this->sendMail("hchaudhari@officebrain.com","","test",'1',$params);
    	$content = $this->replaceDynamicParams($content,$params);*/
         
        return $content;
    }
    
    /**
     * @author Employee Id: 4835
     *
     * Description : 
     *
     * @param 1 : Html Content
     * @param 1 : Language Id
     *
     * @return type : Success message array
     *
     * @throws Exception: Null
     */
    public function isDuplicateHeaderOrNot($name,$id)
    {
      return $this->headerRepo->findDuplicateHeader($name,$id);
    }        
    /** End of header methods **/
}
