<?php
// app/api/messages/departments

    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)));
    
    
    //Definimos las variables que usaremos y las inicializamos
    $out= new stdClass();
    $sessionid = $_GET["sessionid"];
    
    //Validamos que la session del usuario sea valida para continuar
    $userid = isSessionValid($db, $sessionid);
    
    
    //Obtenemos la cantidad de departamentos
    $sql = "SELECT COUNT(id) AS qty FROM departments";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    
    $out->numofrecords = (int)$row['qty'];
        
    // Obtenemos los departamentos
    $sql = "SELECT * FROM departments".
    "       ORDER BY dsc ASC";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    while($row = $rs->fetch_assoc()){
        $record = new stdClass();
        
        $record->id = (int)$row['id'];
        $record->dsc = $row['dsc'];
        
        $records [] = $record;
    }
    
    $out->records = $records;
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
