<?php
// app/api/demographics/regions

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid","countryid");
    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"];
    $countryid = $_GET["countryid"];
    
    //Validamos la session
    isSessionValid($db, $sessionid);
    
    //Buscamos todos los estados del countryid recibido
    $sql = "SELECT id, name FROM regions".
    "       WHERE countryid = ".$countryid.
    "       ORDER BY name";
    if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
    //Inicializamos el contador para conocer la cantidad de records
    $count = 0;
    $records = array();
    while($regionsarr = $rs->fetch_assoc()){
        $record = new stdClass();
        $record->id = (int)$regionsarr["id"];
        $record->dsc = $regionsarr["name"];
        $records[] = $record;
        $count++;
    }
    
    //Retornamos la cantidad de records y cada record a detalle
    $out->numofrecords = $count;
    $out->records = $records;
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
