<?php
// app/api/demographics/countries

    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)));
    }
    
    //Definicion de variables y almacenamiento de valores enviados por GET
    $out = new stdClass;
    $sessionid = $_GET["sessionid"];
    
    //Validamos la session
    isSessionValid($db, $sessionid);
    
    //Contamos los valores totales
    if(isset($_GET["paymentmethods"]) && $_GET["paymentmethods"] != "" && $_GET["paymentmethods"] == 1){
        $sql = "SELECT count(countries.id) AS qty FROM countries".
        "       WHERE EXISTS(".
        "           SELECT * FROM paymentmethods".
        "           WHERE countries.id=paymentmethods.countryid)";
    }else{
        $sql = "SELECT count(countries.id) AS qty FROM countries WHERE countries.id > 0";
    }
    if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
    $row = $rs->fetch_assoc();
    $out->numofrecords = (int)$row["qty"];
    
    //En caso de que el paymentmethods sea enviado obtenemos solo los paises con metodos de pago
    if(isset($_GET["paymentmethods"]) && $_GET["paymentmethods"] != "" && $_GET["paymentmethods"] == 1){
        $sql = "SELECT countries.id AS countryid, countries.name AS countryname, ".
        "       countries.phone_prefix AS countryprefix FROM countries".
        "       WHERE EXISTS(".
        "           SELECT * FROM paymentmethods".
        "           WHERE countries.id=paymentmethods.countryid)".
        "       ORDER BY countries.name ASC, countries.id ASC";
    }else{
        //Buscamos todos los paises ordenandolos por su nombre
        $sql = "SELECT countries.id AS countryid, countries.name AS countryname, ".
        "       countries.phone_prefix AS countryprefix FROM countries".
        "       WHERE countries.id > 0".
        "       ORDER BY countries.name ASC, countries.id ASC";
    }
    if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
    
    //Ordenamos los datos
    while($countriesarr = $rs->fetch_assoc()){
        $record = new stdClass();
        $record->id = (int)$countriesarr["countryid"];
        $record->dsc = $countriesarr["countryname"];
        $record->areacode = $countriesarr["countryprefix"];
        $records[] = $record;
        $count++;
    }
    
    //Retornamos cada record a detalle
    $out->records = $records;
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
