<?php
// app/api/messages/send

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid",'msg','departmentid');
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    
    
    //Definimos las variables que usaremos y las inicializamos
    $out= new stdClass();
    $sessionid = $_GET["sessionid"];
    $msg = $_GET['msg'];
    $departmentid = $_GET['departmentid'];
    
    //Validamos que la session del usuario sea valida para continuar
    $userid = isSessionValid($db, $sessionid);
    
    // Obtenemos los detalles del departmento
    $sql = "SELECT * FROM departments WHERE id = ".$departmentid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $department = $rs->fetch_assoc();
    
    //Arreglo con telefonos
    $smss = '';
    
    if($department['phone1'] != '' && $department['phone1'] != '0' && $department['phone1'] != NULL){
        $smss = $department['phone1'];
    }
    
    if($department['phone2'] != '' && $department['phone2'] != '0' && $department['phone2'] != NULL){
        
        $smss .= $smss == "" ?  $department['phone2'] : ";".$department['phone2'];
    }
    
    if($department['phone3'] != '' && $department['phone3'] != '0' && $department['phone3'] != NULL){
        
        $smss .= $smss == "" ?  $department['phone3'] : ";".$department['phone3'];
    }
        
    //Insertamos el mensaje
    $sql = "INSERT INTO comunications(userid, type, message, sentdate, date, createddate, readed, email, sms, ref)".
    "       VALUES(".$userid.", 1, '".$msg."', NULL, NOW(), NOW(), NULL, '".$department['email']."', '".$smss."', '".$department['dsc']."')";
    if (!$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    $out->id = $db->insert_id;
    
    // 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 sessionid = '".$sessionid."'";
    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']." envió un correo al departamento ".$department['dsc']);
    
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
