<?php
// app/api/notifications/update

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid",'categoryid','email','sms');
    if (!parametrosValidos($_GET, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(",", $parmsob)));
    }
    
    //Definicion de variables y almacenamiento de valores enviados por GET
    $out = new stdClass();
    $sessionid = $_GET["sessionid"];
    $categoryid = $_GET['categoryid'];
    $email = $_GET['email'];
    $sms = $_GET['sms'];
    
    //Validamos la session
    $userid = isSessionValid($db, $sessionid);
    
    // Validamos si el usuario tiene algo insertado
    $sql = "SELECT COUNT(*) AS qty ".
    "       FROM usermessages ".
    "       WHERE categoryid = ".$categoryid.
    "       AND usrid = ".$userid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    
    // Si es 0, insertamos la preferencia
    if($row['qty'] == 0){
        
        $sql = "INSERT INTO usermessages(categoryid, usrid, email, sms, system)".
        "       VALUES(".$categoryid.", ".$userid.", ".$email.", ".$sms.", 1)";
        if (!$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
    }else{
        
        // Actualizamos la preferencia
        $sql = "UPDATE usermessages SET ".
        "       email = ".$email.", ".
        "       sms = ".$sms." ".
        "       WHERE usrid = ".$userid.
        "       AND categoryid = ".$categoryid;
        if (!$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
    }
    
    $out->id = (int)$categoryid;
    
    // 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 ".
    "       FROM users ".
    "       LEFT JOIN userpersons ON userpersons.usrid = users.id ".
    "       LEFT JOIN usercompanies ON usercompanies.usrid = users.id ".
    "       WHERE id = ".$userid;
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $userdataaudit = $res->fetch_assoc();
    
    setAudit($db, "MENSAJERÍA", $sessionid, "APP", "El usuario ".$userdataaudit['name']." actualizó sus preferencias de notificaciones");
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
