<?php
// cms/api/alerts/entry
    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array('sessionid', 'alertid');
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    
    //Declaramos e inicializamos nuestras variables
    $out= new stdClass();
    $sessionid = $_GET["sessionid"];
    $alertid = $_GET['alertid'];
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 87))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
    
    $sql = "SELECT alerts.id AS alertid, ".
    "       usr.id AS userid, ".
    "       usr.usr AS usr, ".
    "       usr.risklevel AS risklevel, ".
    "       IF(usr.type = 1, ".
    "           CONCAT(usrperson.fname,IF(".
    "               usrperson.sname IS NOT NULL, CONCAT(' ',usrperson.sname), '')), ".
    "           usrcompany.name) AS name, ".
    "       IF(usr.type = 1, ".
    "           CONCAT(usrperson.flastname,IF(".
    "               usrperson.slastname IS NOT NULL, CONCAT(' ',usrperson.slastname), '')), ".
    "           usrcompany.comercialname) AS secondname, ".
    "       IF(usr.type = 1, usrperson.politicallyexposed, usrcompany.politicallyexposed) AS pep,".
    "       IF(usr.type = 1, usrperson.doctype , 1) AS doctype, ".
    "       IF(usr.type = 1, usrperson.doc, usrcompany.doc) AS doc,".
    "       alertsupdates.status AS alertstatus, ".
    "       alerts.type AS alerttype, ".
    "       alerts.dsc AS alertdsc, ".
    "       alerts.lastupdate AS lastupdate, ".
    "       alerts.createddate AS createddate".
    "       FROM alerts  ".
    "       LEFT JOIN (".
    "           SELECT alertsupdates.date AS date,".
    "           alertsupdates.alertid AS alertid,".
    "           alertsupdates.status AS status".
    "           FROM alertsupdates".
    "           INNER JOIN (SELECT MAX(id) AS id FROM alertsupdates GROUP BY alertid) max " .
    "           ON alertsupdates.id = max.id " .
    "           GROUP BY alertsupdates.alertid".
    "       ) AS alertsupdates ON alertsupdates.alertid = alerts.id".
    "       LEFT JOIN users usr ON usr.id = alerts.userid ".
    "       LEFT JOIN userpersons usrperson ON alerts.userid = usrperson.usrid ".
    "       LEFT JOIN usercompanies usrcompany ON alerts.userid = usrcompany.usrid ".
    "       WHERE alerts.id = ".$alertid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    $out->entry = new stdClass();
        
    $out->entry->id = (int)$row['alertid'];
    
    $out->entry->user = new stdClass();
    $out->entry->user->id = (int)$row['userid'];
    $out->entry->user->email = $row['usr'];
    $out->entry->user->fullname = $row['name']." ".$row['secondname'];
    
    $out->entry->user->risklevel = new stdClass();
    $out->entry->user->risklevel->id = (int)$row['risklevel'];
    $out->entry->user->risklevel->dsc = "Nivel ".$out->entry->user->risklevel->id;
    
    $out->entry->user->doc = new stdClass();
    $out->entry->user->doc->type = validateDoc($row['doctype']);
    $out->entry->user->doc->dsc = $row['doc'];
    
    $out->entry->user->pep = (int)$row['pep'];
    
    $out->entry->status = new stdClass();
    $out->entry->status->id = (int)$row['alertstatus'];
    $out->entry->status->dsc = alertStatus($out->entry->status->id);
    
    $out->entry->alert = $row['alerttype'];
    $out->entry->dsc = $row['alertdsc'];
    
    $out->entry->datecreated = new stdClass();
    $out->entry->datecreated->date = date('Y-m-d H:i:s', strtotime($row['createddate']));
    $out->entry->datecreated->formatted = date('d/m/Y - h:i A', strtotime($row['createddate']));
    
    $out->entry->lastupdate = new stdClass();
    $out->entry->lastupdate->date = date('Y-m-d H:i:s', strtotime($row['lastupdate']));
    $out->entry->lastupdate->formatted = date('d/m/Y - h:i A', strtotime($row['lastupdate']));
    
    // Obtenemos los cambios de la alerta
    $sql = "SELECT  ".
    "       alertsupdates.status AS status, ".
    "       alertsupdates.createddate AS createddate, ".
    "       alertsupdates.comment AS dsc,".
    "       cms.id AS userid, ".
    "       cms.usr AS usr, ".
    "       cms.name AS name ".
    "       FROM alertsupdates ".
    "       LEFT JOIN cmsusers cms ON cms.id = alertsupdates.userid ".
    "       WHERE alertid = ".$out->entry->id.
    "       ORDER BY alertsupdates.createddate DESC";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $count = 1;
    while($row = $rs->fetch_assoc()){
        $update = new stdClass();
        $update->id = $count;
        
        $update->user = new stdClass();
        if ($row['userid'] == null) {
            $update->user->id = -1;
            $update->user->email = '';
            $update->user->fullname = 'Sistema AFX ';
        } else {
            $update->user->id = (int)$row['userid'];
            $update->user->email = $row['usr'];
            $update->user->fullname = $row['name'];
        }
        
        $update->status = new stdClass();
        $update->status->id = (int)$row['status'];
        $update->status->dsc = alertStatus($update->status->id);
        
        $update->comment = $row['dsc'];
        
        $update->datecreated = new stdClass();
        $update->datecreated->date = date('Y-m-d H:i:s', strtotime($row['createddate']));
        $update->datecreated->formatted = date('d/m/Y - h:i A', strtotime($row['createddate']));
        
        $count++;
        
        $updates [] = $update;
    }
    
    $out->entry->updates = $updates;
    
    $out->privileges = new stdClass();
    $out->privileges->read = tienePrivilegio($db, $sessionid, 87);
    $out->privileges->update = tienePrivilegio($db, $sessionid, 88);
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
    
    /* Funcion para determnar el status 
    *   1 = Verificado
    *   0 = Por Verificar
    *   -1 = Moderado
    *   -2 = Alto
    */
    function alertStatus($statusid) {
        $str = '';
        
        switch(intval($statusid)){
            case 1:
                $str = 'Verificado';
                break;
            case 0:
                $str = 'Por Verificar';
                break;
            case -1:
                $str = 'Moderado';
                break;
            case -2:
                $str = 'Alto';
                break;
            default:
                $str = 'Status no definido';
        }
        
        return $str;
    }
    
    /* Funcion para validar el tipo de documento que fue ingresado, donde:
    * 1 = CI
    * 2 = Passport
    * 3 = Driver license
    * el parametro typeid es el id del tipo de documento
    */
    function validateDoc($typeid){
        $str = '';
        
        if($typeid == 1){
            $str = "Cédula";
        }else if($typeid == 2){
            $str = "Pasaporte";
        }else if($typeid == 3){
            $str = "Licencia de conducir";
        }else if($typeid == 0){
            $str = null;
        }
        
        return $str;
    }
?>