<?php
// cms/api/messages/entry

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array('id',"sessionid");
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    
    
    //Definimos las variables que usaremos y las inicializamos
    $out= new stdClass();
    $id = mysqli_real_escape_string($db, $_GET['id']);
    $sessionid = mysqli_real_escape_string($db, $_GET["sessionid"]);
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 72))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
        
    // Obtenenmos la fecha y el ref del mensaje
    $sql = "SELECT * FROM comunications WHERE id = ".$id;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
        
    // Obtenemos los detalles de los mensajes
    $sql = "SELECT comunications.id AS id, ".
    "       comunications.message AS message, ".
    "       comunications.tags AS tags, ".
    "       GROUP_CONCAT(comunications.userid SEPARATOR '|') AS userid, ".
    "       GROUP_CONCAT(IF(userpersons.fname IS NULL, ".
    "           CONCAT(usercompanies.name, ".
    "               IF(usercompanies.comercialname IS NULL, '', CONCAT('/',usercompanies.comercialname))), ".
    "           CONCAT(userpersons.fname,IF(userpersons.sname IS NULL, '', CONCAT(' ',userpersons.sname)),' ',userpersons.flastname, IF(userpersons.slastname IS NULL, '', CONCAT(' ',userpersons.slastname)) )".
    "       ) SEPARATOR '|') AS name, ".
    "       GROUP_CONCAT((SELECT users.usr FROM users WHERE users.id = comunications.userid) SEPARATOR ';') AS usr, ".
    "       comunications.ref AS ref, ".
    "       comunications.type AS type, ".
    "       GROUP_CONCAT(comunications.email  SEPARATOR ',') AS email, ".
    "       GROUP_CONCAT(comunications.sms SEPARATOR ',') AS sms, ".
    "       comunications.createddate AS datecreated, ".
    "       comunications.date AS date, ".
    "       comunications.sentdate AS sentdate, ".
    "       GROUP_CONCAT(IF(comunications.readed IS NULL, 'NULL', comunications.readed) SEPARATOR ',') AS readed ".
    "       FROM comunications ".
    "       LEFT JOIN usercompanies ON usercompanies.usrid = comunications.userid ".
    "       LEFT JOIN userpersons ON userpersons.usrid = comunications.userid ".
    "       WHERE comunications.createddate = '".$row['createddate']."' ".
    "       AND comunications.ref = '".$row['ref']."' ".
    "       GROUP BY ref, createddate";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    
    $out->entry= new stdClass();
        
    $out->entry->id = (int)$row['id'];
    //$out->entry->row= $row;
    
    $out->entry->users = [];
    
    // Obtenemos los usuarios
    $usrArr = explode(';',$row['usr']);
    $useridArr = explode('|',$row['userid']);
    $nameArr = explode('|',$row['name']);
    $readedArr = explode(',',$row['readed']);
    
    foreach($usrArr as $index => $usr){
        $user = new stdClass();
        
        $user->id = (int)$useridArr[$index];
        $user->fullname = $nameArr[$index];
        $user->user = $usrArr[$index];
        
        if($readedArr[$index] == NULL || $readedArr[$index] == 'NULL'){
            $user->readed = null;
        }else{
            $user->readed = new stdClass();
            $user->readed->date = $readedArr[$index];
            $user->readed->formatted = date('d/m/Y - h:i a',strtotime($readedArr[$index]));
        }
        
        $user->email = $row['email'];
        $user->sms = $row['phone'];
    
        $out->entry->users [] = $user;
    }
    
    $out->entry->message = $row['message'];
    
    $out->entry->ref = new stdClass();
    $out->entry->ref->dsc = $row['ref'];
    
    $out->entry->type = (int)$row['type'];
    
    $out->entry->tags = $row['tags'];
    
    $out->entry->datecreated = new stdClass();
    $out->entry->datecreated->date = $row['datecreated'];
    $out->entry->datecreated->formatted = date('d/m/Y - h:i a',strtotime($row['datecreated']));
    
    $out->entry->date = new stdClass();
    $out->entry->date->date = $row['date'];
    $out->entry->date->formatted = date('d/m/Y - h:i a',strtotime($row['date']));
    
    $out->entry->sentdate = new stdClass();
    $out->entry->sentdate->date = $row['sentdate'];
    $out->entry->sentdate->formatted = date('d/m/Y - h:i a',strtotime($row['sentdate']));
    
    $privileges = new stdClass();
    $privileges->read = tienePrivilegio($db, $sessionid, 72);
    $privileges->update = tienePrivilegio($db, $sessionid, 73);
    
    $out->privileges = $privileges;
    
    
    // SI EL USRID ES -1 Y READED IS NULL LO MARCAMOS
    if($out->entry->users[0]->id != -1 && $out->entry->users[0]->readed == null && $row['type'] == 1){
        $sql = "UPDATE comunications SET ".
        "       readed = NOW() ".
        "       WHERE ref = '".$out->entry->ref->dsc."' ".
        "       AND createddate = '".$out->entry->datecreated->date."'";
        if (!$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
    }
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
