<?php
// cms/api/cities/list

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("order","offset","numofrec","sessionid");
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    
    //Declaramos e inicializamos nuestras variables
    $out= new stdClass();
    $sessionid = mysqli_real_escape_string($db, $_GET["sessionid"]);
    $order = determinateOrder(intval(mysqli_real_escape_string($db, $_GET["order"])));
    $offset = mysqli_real_escape_string($db, $_GET["offset"]);
    $numofrec = mysqli_real_escape_string($db, $_GET["numofrec"]);
    $filter = "";
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 55))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
    
    //En caso de que el filter sea enviado, se construyes el query
    if(isset($_GET["filter"]) && $_GET["filter"] != ""){
        
        // Iniciamos la cadena del query
        $filter = " AND ( ";
        
        //Separamos el filtro por el simbolo +
        $filterEl = separateFilter(mysqli_real_escape_string($db, $_GET["filter"]));
        
        //Recorremos cada elemento
        foreach($filterEl as $index => $el){
            if($index == 0){
                $filter .= " regions.name LIKE '".$el."%' OR ".
                "           countries.name LIKE '".$el."%' OR ".
                "           cities.name LIKE '".$el."%' ";
            }else{
                $filter .= " OR regions.name LIKE '".$el."%' OR ".
                "           countries.name LIKE '".$el."%' OR ".
                "           cities.name LIKE '".$el."%' ";
            }
        }
        
        $filter .= " ) ";
    }
    
    //Contamos los resultados total del query a ejecutar
    $sql = "SELECT COUNT(cities.id) AS qty".
    "       FROM cities, regions, countries".
    "       WHERE cities.countryid = countries.id AND cities.regionid = regions.id".
    "       ".$filter;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $total = $rs->fetch_assoc();
    
    //Retornamos el total de elementos resultantes del query
    $out->numofrecords = (int)$total["qty"];
    
    //Consultamos los datos requeridos
    $sql = "SELECT cities.id AS citiesid, cities.name AS citiesname, ".
    "       cities.status AS citiesstatus, ".
    "       regions.id AS regionsid, regions.name AS regionsname, ".
    "       countries.name AS countriesname, countries.id AS countriesid".
    "       FROM cities, regions, countries".
    "       WHERE cities.countryid = countries.id AND cities.regionid = regions.id".
    "       ".$filter.
    "       ORDER BY ".$order.
    "       LIMIT ".$offset.",".$numofrec;
    if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
    
    //Ordenamos los valores
    while($row = $rs->fetch_assoc()){
        $record = new stdClass();
        $record->id = (int)$row["citiesid"];
        $record->dsc = $row["citiesname"];
        
        $record->country = new stdClass();
        $record->country->id = (int)$row["countriesid"];
        $record->country->dsc = $row["countriesname"];
        
        $record->state = new stdClass();
        $record->state->id = (int)$row["regionsid"];
        $record->state->dsc = $row["regionsname"];
        
        $record->status = new stdClass();
        $record->status->id = (int)$row["citiesstatus"];
        $record->status->dsc =  $record->status->id == 1 ? "Activo" : "Inactivo";
        
        $records [] = $record;
    }
    
    $out->records = $records;
    
    //Retornamos los privilegios del usuario actual
    $access = new stdClass;
    $access->create = tienePrivilegio($db, $sessionid, 52);
    $access->read =   tienePrivilegio($db, $sessionid, 55);
    $access->update = tienePrivilegio($db, $sessionid, 53);
    $access->delete = tienePrivilegio($db, $sessionid, 54);
    $out->privileges = $access;
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
    
    /*  Funcion para determinar el orden de los resultados, donde:
    *   1 = Nombre de la ciudad ASCENDENTE
    *   2 = Nombre de la region ASCENDENTE
    *   3 = Nombre del pais ASCENDENTE
    *   4 = Status de la ciudad ASCENDENTE
    *   -1 = Nombre de la ciudad DESCENDENTE
    *   -2 = Nombre de la region DESCENDENTE
    *   -3 = Nombre del pais DESCENDENTE
    *   -4 = Status de la ciudad DESCENDENTE
    *   Y si el order es enviado si ser algunos de estos valores,
    *   Retornara un error para avisarle al desarrollador/@
    */
    //COLOCAR EN APIARY 3/ -3 PARA STATUS
    function determinateOrder($order){
        $orderres = "";
        switch($order){
            case 0:
                $orderres = "cities.created_at DESC";
                break;
            case 1:
                $orderres = "cities.name ASC";
                break;
            case 2:
                $orderres = "regions.name ASC";
                break;
            case 3:
                $orderres = "countries.name ASC";
                break;
            case 4:
                $orderres = "cities.status ASC";
                break;
            case 5:
                $orderres = "cities.created_at ASC";
                break;
            case -1:
                $orderres = "cities.name DESC";
                break;
            case -2:
                $orderres = "regions.name DESC";
                break;
            case -3:
                $orderres = "countries.name DESC";
                break;
            case -4:
                $orderres = "cities.status DESC";
                break;
            case -5:
                $orderres = "cities.created_at DESC";
                break;
            default:
                badEnd("400", array("msg"=>"Order debe ser 1, 2, 3, 4, 5, -1, -2, -3, -4 o -5"));
                break;
        }
        
        return $orderres;
    }
?>
