<?php
// app/api/messages/validate

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    require '../../hooks/PHPMailer5/PHPMailerAutoload.php';
    date_default_timezone_set('Etc/UTC');
    
    //Definimos las variables que usaremos y las inicializamos
    $out= new stdClass();
    
    // Consultamos todos los mensajes que no han sido enviados
    $sql = "SELECT comunications.ref AS ref, ".
    "       comunications.id AS id, ".
    "       GROUP_CONCAT(comunications.userid SEPARATOR '|') AS userid, ".
    "       GROUP_CONCAT((SELECT users.usr FROM users WHERE users.id = comunications.userid) SEPARATOR ';') AS usr, ".
    "       comunications.message AS message, ".
    "       IF(comunications.email IS NULL, comunications.email, GROUP_CONCAT(comunications.email SEPARATOR ';')) AS email, ".
    "       IF(comunications.sms IS NULL, comunications.sms, GROUP_CONCAT(comunications.sms SEPARATOR ';')) AS sms, ".
    "       comunications.date AS date, ".
    "       comunications.type AS type, ".
    //"       NOW() as nowtime, ".
    "       comunications.createddate AS createddate ".
    "       FROM comunications ".
    "       WHERE comunications.sentdate IS NULL ".
    "       AND comunications.date <= NOW()".
    "       GROUP BY ref, createddate ".
    "       ORDER by id ASC";
    if (!$rs=$db->query($sql)){
        badEnd("500", array("msg"=>determinateDBError($db)));
    }
    
    while($row = $rs->fetch_assoc()){
        
        // Si se tiene que enviar por correo armamos todo
        if($row['email'] != null && $row['email'] != ''){
            // Obtenemos los correos de los usuarios
            $emailArr = explode(';',strtolower($row['email']));
            
            // Enviamos el correo
            //$subject = "Ticket de soporte #".$row['id'];
            
            if($row['type'] == 2){
                $subject = "".$shortname." Notificación";
            }else{
                $subject = "Ticket #".$row['id']." : ".$row['usr'];
                
                // Obtenemos el nombre del usuario
                $sql = "SELECT users.usr AS email, IF(userpersons.fname IS NULL, usercompanies.name, CONCAT(userpersons.fname,' ',userpersons.flastname)) AS name, ".
                "       users.level AS level, users.lang AS lang ".
                "       FROM users ".
                "       LEFT JOIN userpersons ON userpersons.usrid = users.id ".
                "       LEFT JOIN usercompanies ON usercompanies.usrid = users.id ".
                "       WHERE id = ".$row['userid'];
                if (!$resName=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                $userdata = $resName->fetch_assoc();
    
            }
            
            $subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
            $body = "<div class='emailBox'>".
            "           <img class='afxLogo' src='".$homeurl."./settings/img/logo-email.png'/>".
            "           <div class='mainBox'>".
            "               <p class='msgEmail'>".
            "                   ".($row['type'] == 2 ? '' : "El usuario ".$userdata['name']." / ".$row['usr']." envió el siguiente mensaje:<br><br>").
            "                   ".$row['message'].
            "               </p>".
            "           </div>".
            "           <p class='copy'>".$footerEmails."</p>".
            "       </div>";
            
            $body = templateEmail($body, $STANDAR_STYLE_EMAIL);
            
            // Obtenemos si es uno o varios correos
            if(count($emailArr) == 1){
                $emailArr = $row['email'];
            }
            
            enviarCorreo2($fromeMail, $emailArr, $subject, $body);
        }
        
        if($row['sms'] != null && $row['sms'] != ''){
            
            // Validamos si es desde el CMS el mensaje
            if($row['type'] == 2){
                // Buscamos el telefono de cada usuario por su id
                $phoneArr = explode(';',$row['sms']);
                
                // Consultamos los datos del usuario
                foreach($phoneArr as $phone){
                    
                    $msg = $row['message'];
    
                    // Obtenemos el telefono del usuario
                    enviarSMS($phone, $msg);
                }
                
            }else{
                // Enviamos el mensaje a los telefonos del departamento
                $phoneArr = explode(';',$row['sms']);
                
                // Consultamos los datos del usuario
                foreach($phoneArr as $phone){
                    
                    $msg = $row['usr']." envio un mensaje a ".$row['ref'].". Para atender la solicitud visite ".$cmslink."";
                    $phone = "58 ".preg_replace('([^0-9])', '', $phone);
                    // Obtenemos el telefono del usuario
                    enviarSMS($phone, $msg);
                }
            }
        }
        
        if($row['type'] == 1){
            // Actualizamos el mensaje
            $sql = "UPDATE comunications SET ".
            "       sentdate = NOW() ".
            "       WHERE ref = '".$row['ref']."' ".
            "       AND createddate = '".$row['createddate']."' ";
            if (!$db->query($sql)){
                badEnd("500", array("msg"=>determinateDBError($db)));
            }
        
        }else{
            
            // Obtenemos el ref del departamento para colocar la DSC
            $sql = "SELECT * FROM departments WHERE id = ".$row['ref'];
            if (!$resDep = $db->query($sql)){
                badEnd("500", array("msg"=>determinateDBError($db)));
            }
            
            $rowDep = $resDep->fetch_assoc();
        
            // Actualizamos el mensaje
            $sql = "UPDATE comunications SET ".
            "       sentdate = NOW(), ".
            "       ref = '".$rowDep['dsc']."' ".
            "       WHERE ref = '".$row['ref']."' ".
            "       AND createddate = '".$row['createddate']."' ";
            if (!$db->query($sql)){
                badEnd("500", array("msg"=>determinateDBError($db)));
            }
        
        }
    }
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
