<?php
// cms/api/menu/list.php
    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid");
    if (!parametrosValidos($_GET, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    }
    
    $out = new stdClass();
    $sessionid = mysqli_real_escape_string($db, $_GET["sessionid"]);
    
    isSessionValidCMS($db, $sessionid);
    
    $sql = "SELECT COUNT(*) AS qty FROM ( SELECT ".
    "       GROUP_CONCAT((SELECT users.usr FROM users WHERE users.id = comunications.userid) SEPARATOR ';') AS usr, ".
    "       comunications.message AS message, ".
    "       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, ".
    "       comunications.createddate AS datecreated, ".
    "       COUNT(comunications.id) AS qty ".
    "       FROM comunications ".
    "       LEFT JOIN usercompanies ON usercompanies.usrid = comunications.userid ".
    "       LEFT JOIN userpersons ON userpersons.usrid = comunications.userid ".
    "       WHERE (comunications.sentdate IS NOT NULL AND comunications.type=1 AND comunications.readed IS NULL) " .
    "       GROUP BY ref, createddate".
    "       ) suma ";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $out->notifications = 0;
    while($row = $rs->fetch_assoc()){
        $out->notifications += (int)$row['qty'];
    }
    
    $out->options = getMenu($db);

    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>