<?php
if(!defined('sugarEntry'))define('sugarEntry', true);
require_once('config.php');

//require_once('include/connectors/turbo_send_email_code/sendapi_script.php');
//require_once('include/connectors/turbo_send_email_code/lib/TurboApiClient.php');
require_once('include/connectors/johnsyslab/connEmail.php');
require_once('include/connectors/johnsyslab/connSMS.php');
require_once('include/connectors/johnsyslab/connWhatsapp.php');

$GLOBALS['installing'] = true;
require_once('include/entryPoint.php');
$GLOBALS['log'] = LoggerManager :: getLogger('SugarCRM');
function main(){
    // instance db
    $db = DBManagerFactory::getInstance();
    // sacamos todas las campanias pendientes por ejecutar q se hallan pasado de time
    $sql = "SELECT *
            FROM comm1_communications 
            WHERE 
                deleted = 0 AND
                status = 'PENDIENTE' AND
                datetime_execute <= NOW()
        ";
    $result = $db->query($sql);
    // recorremos los resultados
    $fechaM = @date('Y-m-d H:i:s');
    if(isset($result->num_rows) && $result->num_rows>0){
        while($row = $db->fetchByAssoc($result) ){
            echo $row['tipo_campania'];
            // dividimos por el tipo de campania
            switch($row['tipo_campania']){
                case "EMAIL":
                    fnProcessEmail($row,$fechaM);
                    break;
                case "SMS":
                    fnProcessSms($row,$fechaM);
                    break;
                case "WHATSAPP":
                    fnProcessWhatsapp($row,$fechaM);
                    break;
            }
        }
    }else{
        echo "No hay datos para enviar";
    }
}

function fnGetDatosPendientes($row,$db){
    // consultamos los registros pendientes por enviar
    $sql = "SELECT 
                clicom.*,
                cont.first_name,
                cont.last_name,
                IFNULL(cont.phone_mobile,'-1') phone_mobile,
                IFNULL(addr.email_address,'-1')email_address,				
                cstm.cedula_nit_c,
                cont.do_not_call,
                cont.id as contact_id
            FROM 
                comm1_clientes_communications clicom
                    
                INNER JOIN contacts cont ON  cont.id = clicom.contact_id_c               
                INNER JOIN email_addr_bean_rel bean ON (bean.bean_id = cont.id AND bean.deleted = 0)				
                 LEFT JOIN email_addresses addr ON (bean.email_address_id = addr.id AND
                                                                                       bean.primary_address = 1)               
               
                 INNER JOIN contacts_cstm cstm ON   cstm.id_c = cont.id 
            WHERE 
                clicom.deleted = 0 AND
                clicom.status = 'PENDIENTE' AND
                clicom.datetime_send IS NULL AND
                clicom.comm1_communications_id_c = '".$row['id']."' AND
                cont.do_not_call = 0
        ";
    return $db->query($sql);
    
}

/**
 * procesa action send email
 * 
 * @author john jairo cortes garcia <john.cortes@syslab.so>
 * @param type $row
 */
function fnProcessEmail($row,$fechaM){
    // instance db
    $db = DBManagerFactory::getInstance();
    $result = fnGetDatosPendientes($row,$db);
    
    if(isset($result->num_rows) && $result->num_rows>0){
        while($row2 = $db->fetchByAssoc($result)){
            // validamos si no se le puede enviarr mas
            if($row2['do_not_call'] == 1){
                continue;
            }
			if($row2['email_address'] == "-1"){
				continue;
			}
            // set email
            $objEmail = new connEmail();
            // set asunto personalizado
            $asunto = strReplaceColumnsTxt($row['name'],$row2);
            // reemplazamos las pal claves
            $objEmail->setAsunto(ucwords(strtolower($asunto)));
            if (filter_var($row2['email_address'], FILTER_VALIDATE_EMAIL)) {
                // verificamos si hay q reemplazar
                if($row['crossing_fields'] == "S"){
                    $row['msj_text'] = strReplaceColumnsTxt($row['msj_text'],$row2);
                }
                echo "enviar email::".$row2["first_name"]."->".$row2["last_name"]."<br/>";
                $objEmail->setDestinatario($row2['email_address']);
                // creamos el archivo temporal y set header
                $objEmail->setHeader(createFileTmpViewMail($row2['contact_id'],$row2['id'],html_entity_decode($row['msj_text'])));
                // set footer
                $objEmail->setFooter(fnFooterDarDeBajaContacto($row2['contact_id']));
                //
                $objEmail->sendEmail(html_entity_decode($row['msj_text']));
                // actualizamos el estado
   //fnUpdateEstadoSend($row2['id'],$row2['email_address'],$fechaM); ///*aqui se apaga*/
            }
        }
        // verificamos para actualizar la principal
        //fnUpdateEstadoGeneneral($row,$fechaM); ///*aqui se apaga*/
    }else{
        echo "No hay datos de EMAIL para enviar<br/>";
    }
}

/**
 * envia los sms
 * 
 * @author john jairo cortes garcia <john.cortes@syslab.so>
 * @param type $row
 */
function fnProcessSms($row,$fechaM){
    // instance db
    $db = DBManagerFactory::getInstance();
    $result = fnGetDatosPendientes($row,$db);
    
    if(isset($result->num_rows) && $result->num_rows>0){
        $objConnSms = new connSMS();
        while($row2 = $db->fetchByAssoc($result)){
            // verificamos consistencia del numero
            if(isset($row2['phone_mobile']) && $row2['phone_mobile']!=""){
                if(strlen($row2['phone_mobile']) == 10 && substr($row2['phone_mobile'],0,1) == 3){
                    // verificamos si hay q reemplazar
                    if($row['crossing_fields'] == "S"){
                        $row['msj_text'] = strReplaceColumnsTxt($row['msj_text'],$row2);
                    }
                    echo "enviar sms::".$row2["first_name"]."->".$row2["last_name"]."<br/>";
                    $objConnSms->sendSmsAvisel($row2['phone_mobile'], $row['msj_text']);
                    // actualizamos el estado
                    fnUpdateEstadoSend($row2['id'],$row2['phone_mobile'],$fechaM);
                }
            }
        }
        // verificamos para actualizar la principal
        fnUpdateEstadoGeneneral($row,$fechaM);
    }else{
        echo "No hay datos de SMS para enviar<br/>";
    }
}

function fnProcessWhatsapp($row,$fechaM){
    // instance db
    $db = DBManagerFactory::getInstance();
    $result = fnGetDatosPendientes($row,$db);
    
    if(isset($result->num_rows) && $result->num_rows>0){
        $objConnWhatsapp = new connWhatsapp();
        while($row2 = $db->fetchByAssoc($result)){
            if(strlen($row2['phone_mobile']) == 10 && substr($row2['phone_mobile'],0,1) == 3){
                echo "enviar whatsapp::".$row2["first_name"]."->".$row2["last_name"]."<br/>";
                // enviamos la imagen
                if($row['image1'] != "" && $row['image1']!=null){
                    $pathI = dirname(__FILE__)."/tmpimagenes/img_whatsapp/".$row['image1'];
                    $objConnWhatsapp->sendMsgImage($row2['phone_mobile'],$pathI);
                }
                // enviamos el texto
                if($row['msj_text'] != "" && $row['msj_text']!=null){
                    // verificamos si hay q reemplazar
                    if($row['crossing_fields'] == "S"){
                        $row['msj_text'] = strReplaceColumnsTxt($row['msj_text'],$row2);
                    }
                    $objConnWhatsapp->sendMsgText($row2['phone_mobile'],$row['msj_text']);
                }
                // actualizamos el estado
                fnUpdateEstadoSend($row2['id'],$row2['phone_mobile'],$fechaM);
            }
        }
        // verificamos para actualizar la principal
        fnUpdateEstadoGeneneral($row,$fechaM);
    }else{
        echo "No hay datos de WHATSAPP para enviar<br/>";
    }
}

/**
 * actualiza el estado general de la campania
 * 
 * @author john jairo cortes garcia <john.cortes@syslab.so>
 * @param type $row
 * @param type $fechaM
 * @return boolean
 * @throws Exception
 */
function fnUpdateEstadoGeneneral($row,$fechaM){
    try{
        $db = DBManagerFactory::getInstance();
        // verificamos si aun hay pendientes por enviar
        $result = fnGetDatosPendientes($row,$db);
        if(isset($result->num_rows) && $result->num_rows==0){
            $sql = "
                UPDATE
                    comm1_communications
                SET
                    status = 'EJECUTADA',
                    date_modified = '".$fechaM."'
                WHERE
                    id = '".$row['id']."'
                ";
        }
        $db->query($sql);
        
        return true;
    } catch (Exception $ex) {
        throw $ex;
    }
}

function fnUpdateEstadoSend($id,$sendT,$fechaM){
    try{
        $db = DBManagerFactory::getInstance();
        
        $sql = "
            UPDATE
                comm1_clientes_communications
            SET
                status = 'EJECUTADA',
                date_modified = '".$fechaM."',
                datetime_send = '".$fechaM."',
                send_target = '".$sendT."'
            WHERE
                id = '".$id."'
                 ";
        $db->query($sql);
        
        return true;
    } catch (Exception $ex) {
        throw $ex;
    }
}

/**
 * reemplaza las palabras reservadas
 * 
 * @authot john jairo cortes garcia <john.cortes@syslab.so>
 * @param type $strTxt
 * @param type $row2
 * @return type
 * @throws Exception
 */
function strReplaceColumnsTxt($strTxt,$row2){
    try{
        $strTxt = str_replace("[first_name]",$row2['first_name'],$strTxt);
        $strTxt = str_replace("[last_name]",$row2['last_name'],$strTxt);
        $strTxt = str_replace("[phone_mobile]",$row2['phone_mobile'],$strTxt);
        $strTxt = str_replace("[cedula_nit_c]",$row2['first_name'],$strTxt);
        
        return $strTxt;
    } catch (Exception $ex) {
        throw $ex;
    }
}


/**
 * 
 * @author john jairo cortes garcia <john.cortes@syslab.so>
 * @param type $idcliente
 * @param type $idcamparowcli
 * @param type $htmlcliente
 * @return boolean
 * @throws Exception
 */
function createFileTmpViewMail($idcliente,$idcamparowcli,$htmlcliente){
    try{
        $namefile = $idcliente."_".$idcamparowcli;
        $pathApp = dirname(__FILE__);
        $daynow = @date('Ymd');
        if(!is_dir($pathApp."/tmpimagenes/filescampanias/".$daynow)){
            // creamos el directorio en la carpeta control //
            mkdir($pathApp."/tmpimagenes/filescampanias/".$daynow, 0755);
        }
        
        /**creamos el archivo html**/
        if (file_exists($pathApp."/tmpimagenes/filescampanias/".$daynow."/" . $namefile . '.html'))
            unlink($pathApp."/tmpimagenes/filescampanias/".$daynow."/" . $namefile . '.html');
        /* abrimos un archivo*/
        @chmod($namefile, 0777);
        $fp = fopen($pathApp."/tmpimagenes/filescampanias/".$daynow."/" . $namefile . '.html', "w");
        /* escribimos en el archivo */
        fwrite($fp,$htmlcliente);
        fclose($fp);
        // return
        $strH = "<div style='font-style:verdana;font-size:9pt;'>Si no visualiza correctamente este mensaje pulse <a href='http://".$_SERVER['SERVER_NAME']."/studioenero19/tmpimagenes/filescampanias/".$daynow."/" . $namefile . ".html'>aquí</a></div>";
        return $strH;
    } catch (Exception $ex) {
        throw $ex;
    }
}

/**
 * 
 * @param type $idcontacto
 * @throws Exception
 */
function fnFooterDarDeBajaContacto($idcontacto){
    try{        
        $strH = "<div style='font-style:verdana;font-size:9pt;'>Si no desea recibir mas estos boletines pulse <a href='http://".$_SERVER['SERVER_NAME']."/studioenero19/do_not_call.php?record=".$idcontacto."'>aqui</a></div>";
        return $strH;
    } catch (Exception $ex) {
        throw $ex;
    }
}

// execute script
main();