<?php
// cms/api/paymentmethods/list

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid","offset","numofrec");
    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"]);
    $offset = mysqli_real_escape_string($db, $_GET["offset"]);
    $numofrec = mysqli_real_escape_string($db, $_GET["numofrec"]);
    $order = "";
    $filter = "";
    $countryfilter = "";
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 22))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
    
    //En caso de que el filter sea enviado, se construye 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 .= " paymentmethods.dsc LIKE '%".$el."%' ".
                "           OR countries.name LIKE '%".$el."%' ".
                "           OR currencies.symbol LIKE '%".$el."' ";
            }else{
                $filter .= " OR paymentmethods.dsc LIKE '%".$el."%' ".
                "           OR countries.name LIKE '%".$el."%' ".
                "           OR currencies.symbol LIKE '%".$el."' ";
            }
        }
        
        $filter .= " ) ";
    }
    
    //En caso de que el order sea enviado, se construye el query
    if(isset($_GET["order"]) && $_GET["order"] != ""){
        $order = " ORDER BY ".determinateOrder(mysqli_real_escape_string($db, $_GET["order"]));
    }
    
    //En caso de que el countryid sea enviado, se construye el query
    if(isset($_GET["countryid"]) && $_GET["countryid"] != ""){
        $countryfilter = " AND paymentmethods.countryid = '".mysqli_real_escape_string($db, $_GET["countryid"])."'";
    }
    
    //Contamos los resultados total del query a ejecutar
    $sql = "SELECT COUNT(paymentmethods.id) AS qty".
    "       FROM paymentmethods, countries, currencies ".
    "       WHERE paymentmethods.countryid = countries.id ".
    "       AND paymentmethods.currencyid = currencies.id ".
    "       AND paymentmethods.id>0 " .
    "       ".$countryfilter.
    "       ".$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 registros que necesitamos
    $sql = "SELECT paymentmethods.id AS paymentid, paymentmethods.dsc AS paymentdsc, ".
    "       paymentmethods.status AS paymentstatus, countries.name AS countryname, ".
    "       countries.id AS countryid, paymentmethods.currencies AS paymentcurrencies, ".
    "       paymentmethods.details1 AS paymentdetails1, paymentmethods.details2 AS paymentdetails2, ".
    "       paymentmethods.details3 AS paymentdetails3, paymentmethods.details4 AS paymentdetails4 ".
    "       FROM paymentmethods, countries, currencies ".
    "       WHERE paymentmethods.countryid = countries.id".
    "       AND paymentmethods.currencyid = currencies.id ".
    "       AND paymentmethods.id > 0".
    "       ".$countryfilter.
    "       ".$filter.
    "       ".$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["paymentid"];
        $record->dsc = $row["paymentdsc"];
        
        //Estado del metodo de pago
        $record->status = new stdClass();
        $record->status->id = (int)$row["paymentstatus"];
        $record->status->dsc =  $record->status->id == 1 ? "Activo" : "Inactivo";
        
        //Pais del metodo de pago
        $record->country = new stdClass();
        $record->country->id = (int)$row["countryid"];
        $record->country->dsc = $row["countryname"];
            
        $currencies = explode(",", $row["paymentcurrencies"]);
        $currenciesarr = [];
        //Traemos los detalles de cada moneda que administra
        foreach ($currencies as $curren){
            $sql = "SELECT * FROM currencies WHERE id = ".$curren;
            if (!$rescurren=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            $rowcurren = $rescurren->fetch_assoc();
            
            $currendata = new stdClass();
            $currendata->id = (int)$rowcurren["id"];
            $currendata->dsc = $rowcurren["name"];
            $currendata->symbol = $rowcurren["symbol"];
            $currendata->default = $currendata->id == $row["currencyid"] ? true : false;
            
            $currenciesarr [] = $currendata;
        }
        
        $record->currencies = $currenciesarr;
        
        $record->details1 = $row["paymentdetails1"] == null ? "" : $row["paymentdetails1"];
        $record->details2 = $row["paymentdetails2"] == null ? "" : $row["paymentdetails2"];
        $record->details3 = $row["paymentdetails3"] == null ? "" : $row["paymentdetails3"];
        $record->details4 = $row["paymentdetails4"] == null ? "" : $row["paymentdetails4"];
        
        $records [] = $record;
    }
    
    $out->records = $records;
    
    //Retornamos los privilegios del usuario en este modulo
    $access = new stdClass;
    $access->create = tienePrivilegio($db, $sessionid, 19);
    $access->read =   tienePrivilegio($db, $sessionid, 22);
    $access->update = tienePrivilegio($db, $sessionid, 20);
    $access->delete = tienePrivilegio($db, $sessionid, 21);
    $out->privileges = $access;
    
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
    
    
    /*  Funcion para determinar el orden de los resultados, donde:
    *   0 = ID del metodo DESCENDENTE (Mas reciente)
    *   1 = Nombre del Metodo ASCENDENTE
    *   2 = Status del Metodo ASCENDENTE
    *   3 = Pais del metodo ASCENDENTE
    *   4 = Moneda principal del Metodo ASCENDENTE
    *   -1 = Nombre del Metodo DESCENDENTE
    *   -2 = Status del Metodo DESCENDENTE
    *   -3 = Pais del metodo DESCENDENTE
    *   -4 = Moneda principal del Metodo DESCENDENTE
    *   Y si el order es enviado si ser algunos de estos valores,
    *   Retornara un error para avisarle al desarrollador/@
    */
    function determinateOrder($order){
        $orderres = "";
        switch($order){
            case 1:
                $orderres = "paymentmethods.dsc ASC";
                break;
            case 2:
                $orderres = "paymentmethods.status ASC";
                break;
            case 3:
                $orderres = "paymentmethods.countryid ASC";
                break;
            case 4:
                $orderres = "paymentmethods.currencyid ASC";
                break;
            case 5:
                $orderres = "paymentmethods.id ASC";
                break;
            case -1:
                $orderres = "paymentmethods.dsc DESC";
                break;
            case -2:
                $orderres = "paymentmethods.status DESC";
                break;
            case -3:
                $orderres = "paymentmethods.countryid DESC";
                break;
            case -4:
                $orderres = "paymentmethods.currencyid DESC";
                break;
            case -5:
                $orderres = "paymentmethods.id DESC";
                break;
            default:
                badEnd("400", array("msg"=>"Order debe ser 1, 2, 3, 4, 5, -1, -2, -3, -4 o -5"));
                break;
        }
        
        return $orderres;
    }
?>
