<?php

class Email extends Model {

    /******************************************************************

    /*******  VARIABLES

    /******************************************************************/

    var $table = 'emails';

    var $config = array();

    var $debugInfo = array('debug'=>EMAIL_DEBUG_SEND,'emailDebug'=>EMAIL_DEBUG); //0: send emails, 1: send Email only to Debug Email, 2:Off 

    var $variables = array();

    var $lenguaje = '';
    protected $emailContent = '';
    /******************************************************************

    /*******  CONSTRUCTOR

    /******************************************************************/

    function __construct($config = array('smtpServer'=>EMAIL_SERVER_HOST, 'smtpUser'=>EMAIL_SERVER_USER, 'smtpPassword'=>EMAIL_SERVER_PASS, 'appDomainRoot'=>DOMAIN_ROOT, 'skeletonFile'=>'', 'emailEngine'=>EMAIL_ENGINE, 'transGroupID'=>EMAIL_TRANSACTIONAL_GROUP_ID), $debugInfo=array('debug'=>EMAIL_DEBUG_SEND, 'emailDebug'=>EMAIL_DEBUG)){

       

        foreach($config as $key=>$value){

            $this->config[$key] = $value;

        }

        $this->config['skeletonFile'] = (!$this->config['skeletonFile'])?  APPROOT.'lib/common/email_skeleton.php' : $this->config['skeletonFile'];  

        $this->debugInfo['debug'] = $debugInfo['debug'];

        $this->debugInfo['emailDebug'] = $debugInfo['emailDebug'];

    }

    /******************************************************************

    /*******  FUNCIONES

    /******************************************************************/

    /**

     * Asigna un valor al array llamado variables

     * @param $name

     * @param $value

     */

    function setVariable($name, $value) {

        $this->variables[$name] = $value;

    }

    /**

     * Limpia el arraya llamado variables

     */

    function clearVariables(){

        $this->variables = array();

    }

    /**

     * funcion para manejar los parametros del servidor y el envio

     * @param  $from

     * @param  $to

     * @param  $emailTemplateCode

     * @param  $languageId

     * @param  $attachment

     */



    function send($from=array('name'=>'John', 'email'=>'jdoe@sample.com'), $to=array(), $emailTemplateCode, $languageId, $attachment = null, $id_broker='', $id_user='', $id_order='', $titulo ='', $modulo) {

        $this->lenguaje = $languageId;

        if(!is_array($to)){

            $to = array($to);

        }

        $resultEmail = array();

        

        $message=array('html'=>'','text'=>'');

        $this->classEmailTemplate=$this->classEmailTemplate?:new EmailTemplate();

        $template = $this->classEmailTemplate;

        $skeleton ="";

        if($this->config['skeletonFile']!=null){

            $skeleton = $template->loadTemplateSkeleton($this->config['skeletonFile'],$this->config['appDomainRoot']);

        }

        $templateData =  $template->find(array('code'=>$emailTemplateCode,'language_id'=>$languageId));

		if (empty($templateData)&& $languageId!='eng'){ 

            $templateData =  $template->find(array('code'=>$emailTemplateCode,'language_id'=>'eng'));

        }

        /*-----------------------------------------------*/

		if (empty($templateData)){ 

			$file = fopen("../admin/xlog_correos.txt", "a+");

			fwrite($file, "templateData: ".serialize($templateData)." | emailTemplateCode: $emailTemplateCode | languageId: $languageId".PHP_EOL.' '.PHP_EOL);

		    fclose($file); 

     	}

	    /*-----------------------------------------------*/

        if($templateData){

            if($skeleton!=''){

                $contentHtml = str_replace('%body_html%',$templateData[0]['body_html'],$skeleton);

            }else{

                $contentHtml = $templateData[0]['body_html'];

            }

			if(!empty($titulo)){

                $subject = $titulo;

            }else{

                $subject = utf8_decode($templateData[0]['subject']);

            }

            $message=array('html'=>$contentHtml,'text'=>$templateData[0]['body_text']);

        }

        if($this->debugInfo['debug']!=0)$subject1="" . $subject;



        $this->variables['#server_path#'] = DOMAIN_ROOT;

        $this->variables['#system_name#'] = SYSTEM_NAME;

        $this->variables['#email_from#'] = EMAIL_FROM;

        $this->variables['#email_from_name#'] = EMAIL_FROM_NAME;

        $message = str_ireplace("src=\"images","src=\"".DOMAIN_ROOT."images",$message);

        $message = str_ireplace("background=\"images","background=\"".DOMAIN_ROOT."images",$message);

        foreach($this->variables as $name=>$value){

            $message = str_replace($name,stripslashes($value),$message);

            $subject = str_replace($name,stripslashes($value),$subject);

        }

        switch(strtolower($this->config['emailEngine'])){

            case 'jango':

                $result=$this->sendJango($from, $to, $subject, $message, $templateData, $attachment, $id_broker, $id_user, $id_order, $emailTemplateCode);


                break;

            default:

                $result=$this->sendLocal($from, $to, $subject, $message, $templateData, $attachment, $id_broker, $id_user, $id_order, $emailTemplateCode);

                break;

        }

    return $result;

	}

    /**

     * Funcion para realizar el envio de los correos con rutinas locales

     * @param $from

     * @param $to

     * @param $subject

     * @param $message

     * @param $templateData

     * @param $attachment

     */

    function sendLocal($from, $to, $subject, $message, $templateData, $attachment, $id_broker='', $id_user='', $id_order='', $emailTemplateCode){

        //documentation: http://phpmailer.worxware.com/index.php?pg=methods

        $mail = new PHPMailer();

        $mail->IsSMTP();



        $mail->From     = $from['email'];

        $mail->FromName = $from['name'];

        $mail->Host     = $this->config['smtpServer'];



        if($this->config['useSmtp']){

                $mail->SMTPAuth = true;     						// turn on SMTP authentication

                $mail->Username = $this->config['smtpUser'];  		// SMTP username

                $mail->Password = $this->config['smtpPassword']; 	// SMTP password

        }

        $mail->WordWrap = 80;	// set word wrap

        $mail->IsHTML(true);	// send as HTML



        switch($this->debugInfo['debug']){

            case 0: //send email to recipients

                foreach($to as $recipient)

                    $mail->AddAddress($recipient);

                break;

            case 1: //send email to debug account

                $emailList = split(",",$this->debugInfo['emailDebug']);

                if(count($emailList)>0){

                    foreach($emailList as $mailD){

                        $mail->AddAddress($mailD);

                    }

                }else{

                    $mail->AddAddress($this->debugInfo['emailDebug']);

                }

                break;

        }

        $mail->Subject  =  $subject;

        $mail->Body     =  $message['html'];

        $mail->AltBody  =  $message['text'];

        if(!empty($attachment))	$mail->AddAttachment($attachment);

        $status = $mail->Send();

        $errorInfo =$mail->ErrorInfo;

        $resultEmail['email_sender'] = $from['email'];

        $resultEmail['email_recipient'] = implode(',',$to);

        $resultEmail['email_template_id'] = ($templateData)? $templateData[0]['id']: 0;

        $resultEmail['status'] = intVal($status);

        $resultEmail['status_message'] = $errorInfo;

        $resultEmail['id_broker'] = is_numeric($id_broker)?$id_broker:0;

        $resultEmail['id_user'] = is_numeric($id_user)?$id_user:0;

        $resultEmail['id_order'] = is_numeric($id_order)?$id_order:0;



        $this->save($resultEmail);

        $this->id =null;

        $this->clearVariables();



        $mail->ClearAllRecipients();

        $mail->ClearAttachments();

    }

    /**

     * Funcion para realizar el envio de los correos mediante el web services de JANGO SMTP

     * @param $from

     * @param $to

     * @param $subject

     * @param $message

     * @param $templateData

     * @param $attachment

     */

    function sendJango($from, $to, $subject, $message, $templateData, $attachment, $id_broker='', $id_user='', $id_order='', $emailTemplateCode){

      

	    switch($this->debugInfo['debug']){ 

            case 0: //send email to recipients

               foreach($to as $recipient){

                        $result=$this->sendTransactionalEmail('', $from, $recipient, $subject, $message, $templateData, $attachment, $id_broker, $id_user, $id_order, $emailTemplateCode);

                }

                break;

            case 1: //send email to debug account

                $emailList = preg_split(",",$this->debugInfo['emailDebug']);

                if(count($emailList)>0){

                    foreach($emailList as $mailD){

                           $result=$this->sendTransactionalEmail('', $from, $mailD, $subject, $message, $templateData, $attachment, $id_broker, $id_user, $id_order, $emailTemplateCode);

                    }

                } else {

                   $result=$this->sendTransactionalEmail('', $from, $this->debugInfo['emailDebug'], $subject, $message, $templateData, $attachment, $id_broker, $id_user, $id_order, $emailTemplateCode);

                }

                break;

        }

		return $result;

    }

    /**

     * Realiza el envio final del correo por el web services y guarda en la tabla emails el numero de la transaccion

     * @param $client

     * @param $from

     * @param $recipient

     * @param $subject

     * @param $message

     * @param $templateData

     * @param $attachment

     */

     function sendTransactionalEmail($client, $from, $recipient, $subject, $message, $templateData, $attachment, $id_broker='', $id_user='', $id_order=''){

        $headers = [
            'Content-Type: application/json',
            'Authorization: Basic ' . base64_encode($this->config['smtpUser'] . ':' . $this->config['smtpPassword'])
        ];
        $data = [
            "from" => [
                "name"  => $from['name'],
                "email" => trim($from['email'])
            ],
            "to"=>[
                [
                    //"name"  => $to['name'],
                    "email" =>trim($recipient)
                ]
            ],
            "subject"       => utf8_encode($subject),
            "html_content"  => $message['html'],    
            "text_content"  =>  $message['text'],                    
            "transactional_group_id" => (int)EMAIL_TRANSACTIONAL_GROUP_ID,
            "tracking" => [
                "click_track_text" => true,
                "click_track_html" => false,
                "track_opens" => true
            ],
            "return_receipts" => true,
        ];

        if(!empty($attachment)){
            
           
            $data['attachments'] = [];
            foreach ($attachment as $file) {
                if ($attachment = $this->setAttachmentToSend($file['url'], $file['file_name'])) {
                    $data['attachments'][] = $attachment;
                }
            }
        
        } 
     
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api-v2.jangomail.com/transactional/send');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $result = curl_exec($ch);

        $arrResult = json_decode($result, true);

        curl_close($ch);
        $resultEmail['email_sender'] = $from['email'];
        $resultEmail['email_recipient'] = $recipient;
        $resultEmail['email_template_id'] = ($templateData)? $templateData[0]['id']: 0;
        $resultEmail['status'] = intVal(empty($arrResult["status"]) ? 1 : $arrResult["status"]);
        $resultEmail['status_message'] = addslashes(!empty($arrResult["status"])? $arrResult["title"].' '.$arrResult["detail"]:'SUCCESS');
        $resultEmail['transactional_id'] = $arrResult["id"];
		$resultEmail['message'] =  addslashes($message['html']);
		
		$resultEmail['id_broker'] = is_numeric($id_broker)?$id_broker:0;	       
	        $resultEmail['id_user'] = $id_user?$id_user:0;		        
	        $resultEmail['id_order'] = $id_order?$id_order:0;
				
        $this->save($resultEmail);
        $this->id =null;
        $this->clearVariables();
		$resultado=$resultEmail['status'];
        

   return $resultado;
    }

	function Get_Email($email_recipient = '', $email_template_id = '', $desde = '', $hasta = '',$status = '', $min = '', $max = '', $language_id = '', $id = '') {

        $query = "SELECT

					emails.id,

					emails.`status`,

					emails.status_message,

					emails.transactional_id,

					emails.created,

					emails.email_sender,

					emails.email_recipient,

					emails.email_template_id,

					emails.message,

					email_templates.description,

					languages.`name`

                FROM emails

					LEFT JOIN email_templates ON emails.email_template_id = email_templates.id

					LEFT JOIN languages ON languages.lg_id = email_templates.language_id

                WHERE 1 ";

		if (!empty($id))

					$query.=" AND emails.id =$id";

        if (!empty($email_recipient))

            $query.=" AND emails.email_recipient like '%$email_recipient%'";

        if (!empty($email_template_id))

            $query.=" AND email_templates.code='$email_template_id'";

        if (!empty($desde))

            $query.=" AND CAST(emails.created AS DATE) >='$desde'";

        if (!empty($hasta))

            $query.=" AND CAST(emails.created AS DATE) <='$hasta'";	

        if (!empty($status)){ 

            $status = str_replace('2', '0', $status);

            $query.=" AND emails.status='$status'"; 

        }

        if (!empty($language_id)){  

            $query.="AND email_templates.language_id = '$language_id'"; 

        }

        $query.=" ORDER BY emails.created  DESC";   

        if (!empty($max)) {

            $query .= " LIMIT $min,$max ";

        }

        return $this->_SQL_tool($this->SELECT, __METHOD__, $query);

    }

	function Get_Email_Template($language_id = '') {

        $query = "SELECT 

            email_templates.id,

            email_templates.`code`,

            email_templates.description

        FROM `email_templates`

        WHERE

            email_templates.active = 1 AND

            email_templates.language_id = '$language_id'

            GROUP BY email_templates.`code`";

        return $this->_SQL_tool($this->SELECT, __METHOD__, $query);

    }

	function Notif_Error_Email($id_user='', $idbroker=''){

        if(!empty($id_user) AND empty($idbroker) AND is_numeric($id_user)){

		    $query = "SELECT

            users.id,

            broker.id_broker,

            broker.broker,

            contact.first_name AS nombre_contacto,

            contact.last_name AS apellido_contacto,

            contact.email,

            contact.email2,

            contact.notif_error_email

        FROM contact

            INNER JOIN relacion_contact ON relacion_contact.id_contact = contact.id_contact

            INNER JOIN broker ON broker.id_broker = relacion_contact.id_relacion

            INNER JOIN user_associate ON user_associate.id_associate = broker.id_broker

            INNER JOIN users ON users.id = user_associate.id_user

        WHERE users.id = '{$id_user}'";

            $result = $this->_SQL_tool($this->SELECT, __METHOD__, $query); 

        }

        if(empty($id_user) AND !empty($idbroker) AND is_numeric($idbroker)){

            $query = "SELECT

                broker.id_broker,

                broker.broker,

                contact.first_name AS nombre_contacto,

                contact.last_name AS apellido_contacto,

                contact.email,

                contact.email2,

                contact.notif_error_email

            FROM contact

                INNER JOIN relacion_contact ON relacion_contact.id_contact = contact.id_contact

                INNER JOIN broker ON broker.id_broker = relacion_contact.id_relacion

            WHERE broker.id_broker = '{$idbroker}'";

            $result = $this->_SQL_tool($this->SELECT, __METHOD__, $query); 

        }

        if(!empty($id_user) AND !empty($idbroker) AND is_numeric($id_user)){

            $query = "SELECT

            users.id,

            broker.id_broker,

            broker.broker,

            contact.first_name AS nombre_contacto,

            contact.last_name AS apellido_contacto,

            contact.email,

            contact.email2,

            contact.notif_error_email

        FROM contact

            INNER JOIN relacion_contact ON relacion_contact.id_contact = contact.id_contact

            INNER JOIN broker ON broker.id_broker = relacion_contact.id_relacion

            INNER JOIN user_associate ON user_associate.id_associate = broker.id_broker

            INNER JOIN users ON users.id = user_associate.id_user

        WHERE users.id = '{$id_user}'";

            $result = $this->_SQL_tool($this->SELECT, __METHOD__, $query);

        }

        $sql = "SELECT email FROM list_webservice";

        $email = $this->_SQL_tool($this->SELECT, __METHOD__, $sql);

        for($i = 0; $i < count($email); $i++){

            $result[$i]['email_contact'] = $email[$i]['email'];

        }

        return $result; 

    }

	function Get_Email_Template_Id($code, $language_id) {

        $query = "SELECT 

            email_templates.id,

            email_templates.`code`,

            email_templates.description,

            email_templates.`subject`,

            email_templates.language_id

        FROM email_templates 

        WHERE 

            email_templates.active = 1 AND 

            email_templates.language_id = '{$language_id}' AND 

            email_templates.code = '{$code}'";

        return $this->_SQL_tool($this->SELECT, __METHOD__, $query);

    }

    public function setAttachmentToSend($file, $name)
    {
      
        if (filter_var($file, FILTER_VALIDATE_URL)) {
         
            $curl = curl_init($file);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            $attachment = curl_exec($curl);
            $name = $name ?: basename($file);
            return [
                'base64_content' => base64_encode($attachment),
                'content_type'  => 'pdf',
                'file_name'     => $name,
            ];
        }
        return false;
    }
    public function setContent($content = [])
    {
        $this->emailContent =  strtr($this->emailContent, $content);
        $this->subject = strtr($this->subject, $content);
        return $this;
    }
    public static function callApiJango($endPoint, $data = [], $method = 'POST', $contentType = 'application/json')
    {

        $endPoint = trim($endPoint, '/');
        $headers = [
            'Content-Type: ' . $contentType,            
            'Authorization: Basic ' . base64_encode(EMAIL_SERVER_USER . ':' . EMAIL_SERVER_PASS)
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api-v2.jangomail.com/' . $endPoint);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


        if ($method == 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        } else {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
            if (!empty($data)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            }
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $result = curl_exec($ch);
        $err = curl_error($ch);
        curl_close($ch);
        return $result ? (json_decode($result, true) ?: $result) : $err;
    }

}
?>
