<?php if (!defined('BASEPATH')) exit('No direct script access allowed');


class Newsletter {
    
    private $CI;
    private static $CIs; 
    
    function __construct() 
    {
        $this->CI =& get_instance();
        self::$CIs =& get_instance();
        self::$CIs->load->model('newsletter/newsletter_model');
    } 
    
    
    
    public static function clicou($key)
    {
        return self::$CIs->newsletter_model->clicou_email_campanha($key);
    }
    
    public static function addTagRelCap($id_tag, $id_captura)
    {
        self::$CIs->newsletter_model->insere_tag_historico(['id_tag'=> $id_tag, 'id_captura'=> $id_captura]);
        return self::$CIs->newsletter_model->insere_tag_captura(['id_tag'=> $id_tag, 'id_captura'=> $id_captura]);
    }
    
    public static function setTagRelCap($tag, $id_captura)
    {
        $tag = self::$CIs->newsletter_model->getTag([['tag',$tag]]);
        if($tag == null)
            return false;
        
        $id_tag = $tag->id_tag;
        self::$CIs->newsletter_model->insere_tag_historico(['id_tag'=> $id_tag, 'id_captura'=> $id_captura]);
        return self::$CIs->newsletter_model->insere_tag_captura(['id_tag'=> $id_tag, 'id_captura'=> $id_captura]);
    }
    
    
    public static function removeAllTagsCap($id_captura)
    {
        return self::$CIs->newsletter_model->delete_tag_captura([['id_captura',$id_captura]]);
    }
    
    public static function removeTagRelCap($id_tag, $id_captura)
    {
        if(is_array($id_tag))
        {
            foreach ($id_tag as $id)
                $r = self::$CIs->newsletter_model->delete_tag_captura([['id_tag',$id],['id_captura',$id_captura]]);
        
            
        }
        else{
            $r = self::$CIs->newsletter_model->delete_tag_captura([['id_tag',$id_tag],['id_captura',$id_captura]]);
        }
        
        return $r;
    }
    
    public static function nextTagRelCap($id_remove, $id_add, $id_captura)
    {
        self::removeTagRelCap($id_remove, $id_captura);
        self::addTagRelCap($id_add,$id_captura);
    }
    
    
    
    
    function envia($email, $ids, $dados = null) 
    {
        return $this->enviar_email_campanha($email, $ids, $dados);
    }
    
    //$ids 1- id_campanha, 2 - id_arquivo
    function enviar_email_campanha($email, $ids, $dados = null) 
    {
        if(is_array($ids)){
            $id_campanha = $ids[0];
            $id_arquivo = $ids[1];
        }
        else{
            $id_campanha = $ids;
            $id_arquivo = 0;
        }
        
        $this->CI->load->model('newsletter/newsletter_model');
        if($email != null)
        {
            $key_log = md5($email . $id_campanha . date('Y-m-d H:i:s'));
            if(!$this->validaEmail($email))
            {
                $dt_erro = array('notificationType' => 'INVALIDO','emailAddress' => $email,'diagnosticCode' => 'email invalido');
					$this->CI->db->insert('nwl_notifications', $dt_erro);
                    $this->enviou_email_campanha($email, $id_campanha, 0, $key_log, $id_arquivo);
                    return false;
            }
            
            $campanha = $this->CI->newsletter_model->get_campanha($id_campanha);
            if($campanha != null)
            {
                $remetente = $campanha->remetente??1;
                
                $config = $this->CI->newsletter_model->get_config_campanha($remetente);
                
                if ($campanha->view_html == "") 
                {
                    $view = 'newsletter/campanha/email_default_html';
                } 
                else
                {
                    $view = 'newsletter/campanha/'.$campanha->view_html;
                }
                
                $data = array(
                    'campanha'      => $campanha->campanha,
                    'base_url'      => base_url(),
                    'email'         => $email,
                    'key_log'       => $key_log,
                    'subject'       => $campanha->subject,
                    'link'          => $campanha->link_destino,
                    'link_cadencia' => $campanha->link_cadencia,
                    'from_email'    => $config->from_email,
                    'from_titulo'   => $config->from_titulo,
                    'mensagem'      => $campanha->mensagem,
                    'view_html'     => $view,
                    'config_smtp'   => $campanha->config_smtp,
                    'config'        => (array)$config,
                    'fechalink'     => '</a>',
                    'fechabotao'    => '</a>',
                    'linkcustom'    => '',
                    'key_captura'   => '',
                    'anexo'         => '',
                );
                
                $pos = strripos($campanha->link_destino, ',');
                if (!($pos === false)) 
                {
                    $links = explode(',',$campanha->link_destino);
                    foreach($links as $k=>$link)
                    {
                        if($k == 0){
                            $data['abrelink'] = '<a href="'.base_url().'newsletter/action/jhu68fkj4087a7d99s7s8g8f/'.$key_log.'"  target="_blank">';
                            $data['abrebotao'] = '<a href="'.base_url().'newsletter/action/jhu68fkj4087a7d99s7s8g8f/'.$key_log.'" style="border-radius: 4px;display: inline-block;font-weight: bold;text-align: center;text-decoration: none;color: #fff;background-color: #2b90d9;font-family: &quot;cabin&quot; , &quot;avenir&quot; , sans-serif;font-size: 20px;height: 40px;line-height: 40px;padding: 0 65px;" target="_blank">';
                            $data['link'] = base_url().'newsletter/action/jhu68fkj4087a7d99s7s8g8f/'.$key_log;
                        }
                        $key_link = 'link_'.($k+1);
                        $key_l = 'abrelink_'.($k+1);
                        $key_b = 'abrebotao_'.($k+1);
                        $data[$key_l] = '<a href="'.base_url().'newsletter/action/jhu68fkj4087a7d99s7s8g8f/'.$key_log.'/'.$k.'"  target="_blank">';
                        $data[$key_b] = '<a href="'.base_url().'newsletter/action/jhu68fkj4087a7d99s7s8g8f/'.$key_log.'/'.$k.'" style="border-radius: 4px;display: inline-block;font-weight: bold;text-align: center;text-decoration: none;color: #fff;background-color: #2b90d9;font-family: &quot;cabin&quot; , &quot;avenir&quot; , sans-serif;font-size: 20px;height: 40px;line-height: 40px;padding: 0 65px;" target="_blank">';
                        
                        $data[$key_link] = base_url().'newsletter/action/jhu68fkj4087a7d99s7s8g8f/'.$key_log.'/'.$k;
                        
                        
                    }
                }
                else
                {
                    $data['abrelink'] = '<a href="'.base_url().'newsletter/action/jhu68fkj4087a7d99s7s8g8f/'.$key_log.'"  target="_blank">';
                    $data['abrebotao'] = '<a href="'.base_url().'newsletter/action/jhu68fkj4087a7d99s7s8g8f/'.$key_log.'" style="border-radius: 4px;display: inline-block;font-weight: bold;text-align: center;text-decoration: none;color: #fff;background-color: #2b90d9;font-family: &quot;cabin&quot; , &quot;avenir&quot; , sans-serif;font-size: 20px;height: 40px;line-height: 40px;padding: 0 65px;" target="_blank">';
                    $data['link'] = base_url().'newsletter/action/jhu68fkj4087a7d99s7s8g8f/'.$key_log;
                }
                
                if($dados != null)
                {
                    $data = array_merge($data, $dados);
                    $linkcustom      = $data['linkcustom'];
                    $link_cadencia   = $data['link_cadencia'];
                    $key_captura     = $data['key_captura'];
                    
                    //$data['linkcustom'] = '<a href="'.$linkcustom.'/'.$key_log.'"  target="_blank">';
                    $data['linkcustom'] = $linkcustom.'/'.$key_log;
                    $data['botaocustom'] = '<a href="'.$linkcustom.'/'.$key_log.'" style="border-radius: 4px;display: inline-block;font-weight: bold;text-align: center;text-decoration: none;color: #fff;background-color: #2b90d9;font-family: &quot;cabin&quot; , &quot;avenir&quot; , sans-serif;font-size: 20px;height: 40px;line-height: 40px;padding: 0 65px;" target="_blank">';
                    
                    $data['linkcadencia'] = '<a href="'.base_url().$link_cadencia.'/'.$key_captura.'/'.$key_log.'"  target="_blank">';
                    $data['botaocadencia'] = '<a href="'.base_url().$link_cadencia.'/'.$key_captura.'/'.$key_log.'" style="border-radius: 4px;display: inline-block;font-weight: bold;text-align: center;text-decoration: none;color: #fff;background-color: #2b90d9;font-family: &quot;cabin&quot; , &quot;avenir&quot; , sans-serif;font-size: 20px;height: 40px;line-height: 40px;padding: 0 65px;" target="_blank">';
                }
                
                $rst_email = $this->_envia_email_campanha($data);
                if ($rst_email === true) 
                {
                    $this->enviou_email_campanha($email, $id_campanha, 1, $key_log, $id_arquivo);
                    return true;
                } 
                else
                {
                    $dt_erro = array('notificationType' => 'ERRO','emailAddress' => $email,'diagnosticCode' => $rst_email);
					$this->CI->db->insert('nwl_notifications', $dt_erro);
                    $this->enviou_email_campanha($email, $id_campanha, 0, $key_log, $id_arquivo);
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
        
    }
    
    public function _envia_email_campanha($data) 
    {
        $this->CI->load->library('parser');
        $this->CI->load->library('email');
        
        
        
        
        if($data['config_smtp'] == 1)
        {
            $config['protocol'] = 'smtp';
            $config['mailpath'] = '/usr/sbin/sendmail';
            $config['charset'] = 'utf-8';
            $config['mailtype'] = 'html';
            $config['wordwrap'] = TRUE;
            $config['smtp_host'] = $data['config']['smtp_host'];//'email-smtp.us-west-2.amazonaws.com';
            $config['smtp_user'] = $data['config']['smtp_user'];//'AKIAJQFMVPSXBQWOUQ3Q';
            $config['smtp_pass'] = $data['config']['smtp_pass'];//'Asvbq6GWZOeMalQyww05H5bfjvn/ewOUMRhX7HwNlewv';
            $config['smtp_port'] = $data['config']['smtp_port'];//'587';
            $config['validate'] = TRUE;
            $config['smtp_crypto'] = 'tls';
            $config['smtp_timeout'] = 60;
            $config['priority'] = 1;
            $config['crlf']  = "\r\n";
            $config['newline']  = "\r\n"; 
        }
        else
        {
            $config['protocol'] = 'mail';
            $config['mailpath'] = '/usr/sbin/sendmail';
            $config['charset'] = 'utf-8';
            $config['wordwrap'] = TRUE;
            $config['validate'] = TRUE;
        }
        
        $this->CI->email->clear(true);
        
        $this->CI->email->initialize($config);
        
        if(is_array($data['anexo']))
        {
            foreach ($data['anexo'] as $anexo)
                if ($data['anexo'] != '')
                    $this->CI->email->attach($anexo);
                    
                    
        }elseif ($data['anexo'] != '') {
            $this->CI->email->attach($data['anexo']);
        }
        
        $this->CI->email->from($data['from_email'], $data['from_titulo']);
        $this->CI->email->to($data['email']);
        $this->CI->email->subject($data['subject']);
         
        $this->CI->email->message($this->CI->parser->parse($data['view_html'], $data, TRUE));
        
        if ($this->CI->email->send() === true) 
        {
            //var_dump($data);
            //echo "foi";
            return true;
        } 
        else
        {
            //echo $this->CI->email->print_debugger();
            return $this->CI->email->print_debugger();
        }
    }
    
    function enviou_email_campanha($email, $id_campanha, $st, $key_log, $id_arquivo = 0) 
    {
        $this->CI->load->model('newsletter/newsletter_model');
        
        $insert = array(
            'email' => $email,
            'id_arquivo' => $id_arquivo,
            'id_campanha' => $id_campanha,
            'key_log' => $key_log,
            'enviado' => $st,
            'enviado_em' => date('Y-m-d H:i:s'),
        );
        $this->CI->newsletter_model->insere_log($insert);
        if ($st == 1) 
        {
            $this->CI->newsletter_model->enviou_campanha($id_campanha);
        } 
        else
        {
            $this->CI->newsletter_model->falhou_campanha($id_campanha);
        }
    }
    
    private function validaEmail($email) 
    {
        $verifica = $this->CI->newsletter_model->verifica_desinscricao($email);
        if($verifica)
            return false;
        
        $array_invalidos = array(
            '@mailinator.com',
            '@harakirimail.com',
            '@teste'
            );
        $syntaxe = '#^[\w.-]+@[\w.-]+\.[a-zA-Z]{1,6}$#';
        if (preg_match($syntaxe, $email))
        {
            foreach($array_invalidos as $invalido)
            {
                $result = strrpos($email, $invalido); //Resultado: 8
                if($result != null)
                {
                   return false;
                }
            }
                    
              return true;
        }
        else 
        {
            return false;
        }
    }
    
    function getCampanhaUUID($UUID)
    {
        return $this->CI->newsletter_model->get_campanha_uuid($UUID);
    }
    
    
//####################################################################################################################
    /*function enviar_email_campanha_id_user($id_user, $id_campanha) 
    {
        $this->CI->load->model('newsletter/newsletter_model');
        
        //$r_log = $this->CI->newsletter_model->verifica_log_email($id_user, $id_campanha);
        $r_log = false;
        if ($r_log === false) 
        {
            $email = $this->CI->newsletter_model->get_email($id_user);
            if($email != null)
            {
                $campanha = $this->CI->newsletter_model->get_campanha($id_campanha);
                
                if ($campanha->view_html == "") 
                {
                    $view = 'newsletter/campanha/email_default_html';
                } 
                else
                {
                    $view = $campanha->view_html;
                }
                $key_log = md5($id_user . $id_campanha . date('Y-m-d H:i:s'));
                $data = array(
                    'campanha' => $campanha->campanha,
                    'base_url' => base_url(),
                    'email' => $email->email,
                    'key_log' =>  $key_log,
                    'subject' => $campanha->subject,
                    'link' => $campanha->link_destino,
                    'from_email' => $campanha->from_email,
                    'from_titulo' => $campanha->from_titulo,
                    'mensagem' => $campanha->mensagem,
                    'view_html' => $view,
                );
                $rst_email = $this->_envia_email_campanha($data);
                if ($rst_email === true) 
                {
                    $this->enviou_email_campanha($id_user, $id_campanha, 1, $key_log);
                    return true;
                } 
                else
                {
                    $this->enviou_email_campanha($id_user, $id_campanha, 0, $key_log);
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        return false;
    }*/
    
    
    
    
   
}


class Envia extends Newsletter
{
    static protected $Newsletter = null;
    
    static function iniNewsletter()
    {
        if(self::$Newsletter == null)
            self::$Newsletter = new Newsletter(); 
    }
    
    static function newsletter()
    {
        self::iniNewsletter();
        return self::$Newsletter; 
    }
    
    
    static function email($email, $UUIDs, $dados = null)
    {
        
        if(is_array($UUIDs)){
            $id_arquivo = $UUIDs[1];
            $UUIDs = $UUIDs[0];
        }
        else{
            $id_arquivo = 0;
        }
        
        $camp = self::newsletter()->getCampanhaUUID($UUIDs);
        if($camp == null)
            throw new Exception("UUID $UUID não encontrado");
                
        return self::newsletter()->enviar_email_campanha($email, [$camp->id_campanha, $id_arquivo], $dados);
    }
    
    
    
    
}