<?php
// cms/api/accounts/list

    header("Content-Type:application/json");
    include("../dbconn.php");
    include("../utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid");
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    
    //Declaramos e inicializamos nuestras variables
    $out= new stdClass;
    $sessionid = $_GET["sessionid"];
    $offset = "";
    $numofrec = "";
    $limit = "";
    $filter = "";
    $order = determinateOrder($_GET["order"]);
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 26))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
    
    //En caso de que el offset sea enviado, se construye el query
    if(isset($_GET["offset"]) && $_GET["offset"] != ""){
        $offset = $_GET["offset"];
    }else{
        $offset = "0";
    }
    
    //En caso de que el numofrec sea enviado, se construye el query
    if(isset($_GET["numofrec"]) && $_GET["numofrec"] != ""){
        $numofrec = $_GET["numofrec"];
    }
    
    if($offset != 0 && $numofrec == ""){
        $limit = " LIMIT ".$offset.", 18446744073709551615";
    }else if($offset != 0 && $numofrec != ""){
        $limit = " LIMIT ".$offset.", ".$numofrec;
    }else if($offset == 0 && $numofrec != ""){
        $limit = " LIMIT ".$numofrec;
    }else{
        $limit = " LIMIT ".$offset.", 18446744073709551615";
    }
    
    //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($_GET["filter"]);
        
        //Recorremos cada elemento
        foreach($filterEl as $index => $el){
            if($index == 0){
                $filter .= " countries.name LIKE '".$el."%' OR ".
                "           paymentmethods.dsc LIKE '".$el."%' OR ".
                "           currencies.name LIKE '".$el."%' OR ".
                "           currencies.symbol LIKE '".$el."' OR ".
                "           accounts.details1 LIKE '".$el."' ";
            }else{
                $filter .= " OR countries.name LIKE '".$el."%' OR ".
                "           paymentmethods.dsc LIKE '".$el."%' OR ".
                "           currencies.name LIKE '".$el."%' OR ".
                "           currencies.symbol LIKE '".$el."' OR ".
                "           accounts.details1 LIKE '".$el."' ";
            }
        }
        
        $filter .= " ) ";
    }
    
    //Consultamos el total de resultados
    $sql = "SELECT count(accounts.id) AS qty ".
    "       FROM accounts, paymentmethods, currencies, countries ".
    "       WHERE accounts.paymentmethodid = paymentmethods.id AND ".
    "       paymentmethods.countryid = countries.id AND ".
    "       accounts.currencyid = currencies.id AND ".
    "       paymentmethods.id > 0 AND ".
    "       accounts.userid = -1 ".
    "       ".$filter.
    "       ".$order;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $row = $rs->fetch_assoc();
    
    $out->numofrecords = (int)$row["qty"];
    
    $sql = "SELECT accounts.id AS accountid, accounts.paymentmethodid AS paymentmethodid, ".
    "       paymentmethods.dsc AS paymentmethodname, paymentmethods.countryid AS countryid, ".
    "       countries.name AS countryname, accounts.currencyid AS currencyid, ".
    "       currencies.name AS currencyname, accounts.status AS accountstatus, ".
    "       accounts.details1 AS accountdetail1, accounts.details2 AS accountdetail2,".
    "       accounts.details3 AS accountdetail3, accounts.details4 AS accountdetail4, ".
    "       currencies.symbol AS currencysymbol ".
    "       FROM accounts, paymentmethods, currencies, countries ".
    "       WHERE accounts.paymentmethodid = paymentmethods.id AND ".
    "       paymentmethods.countryid = countries.id AND ".
    "       accounts.currencyid = currencies.id AND ".
    "       paymentmethods.id > 0 AND ".
    "       accounts.userid = -1 ".
    "       ".$filter.
    "       ".$order.
    "       ".$limit;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
    
    //Ordenamos los datos
    while($row = $rs->fetch_assoc()){
        $record = new stdClass();
        //Guardamos el id de la cuenta
        $record->id = (int)$row["accountid"];
        
        //Metodo de pago
        $record->paymentmethod = new stdClass();
        $record->paymentmethod->id = (int)$row["paymentmethodid"];
        $record->paymentmethod->dsc = $row["paymentmethodname"];
        
        //Pais del metodo de pago
        $record->country = new stdClass();
        $record->country->id = (int)$row["countryid"];
        $record->country->dsc = $row["countryname"];
        
        //Moneda principal de la cuenta
        $record->currency = new stdClass();
        $record->currency->id = (int)$row["currencyid"];
        $record->currency->dsc = $row["currencyname"];
        $record->currency->symbol = $row["currencysymbol"];
        
        //Consultamos el balance total de la cuenta
        $sql = "SELECT SUM(amount) as qty FROM `transactions` WHERE accountid = ".$record->id;
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
        
        $balance = $res->fetch_assoc();
        
        //Balance a partir de las transacciones
        $record->balance = (float)$balance["qty"];
        $record->balancedsc = number_format($record->balance,2,",",".");
        
        //Detalles de la cuenta
        $record->status = (int)$row["accountstatus"];
        $record->details1 = $row["accountdetail1"] == null ? "" : $row["accountdetail1"];
        $record->details2 = $row["accountdetail2"] == null ? "" : $row["accountdetail2"];
        $record->details3 = $row["accountdetail3"] == null ? "" : $row["accountdetail3"];
        $record->details4 = $row["accountdetail4"] == null ? "" : $row["accountdetail4"];
        
        $records [] = $record;
    }
    
    $out->records = $records;
    //Preguntar a javier si se requieren otros privilegios
    //Retornamos los privilegios del usuario en este modulo
    $access = new stdClass;
    $access->create = tienePrivilegio($db, $sessionid, 23);
    $access->read =   tienePrivilegio($db, $sessionid, 26);
    $access->update = tienePrivilegio($db, $sessionid, 24);
    $access->delete = tienePrivilegio($db, $sessionid, 25);
    $out->privileges = $access;
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
    
    /*  Funcion para determinar el orden de los resultados, donde:
    *   0 = ID de la cuenta DESCENDENTE (mas reciente)
    *   1 = Nombre del pais ASCENDENTE
    *   2 = Forma de pago ASCENDENTE
    *   3 = Status ASCENDENTE
    *   4 = Moneda ASCENDENTE
    *   -1 = Nombre del pais DESCENDENTE
    *   -2 = Forma de pago DESCENDENTE
    *   -3 = Status DESCENDENTE
    *   -4 = Moneda DESCENDENTE
    *   Y si el order es enviado si ser algunos de estos valores,
    *   Retornara un error para avisarle al desarrollador/@
    *   Siempre debe ordenar por el id de las cuentas
    */
    //COLOCAR EN APIARY 3/ -3 PARA STATUS
    function determinateOrder($order){
        $orderres = "";
        switch($order){
            case 1:
                $orderres = "ORDER BY countries.name ASC, accounts.id DESC";
                break;
            case 2:
                $orderres = "ORDER BY paymentmethods.dsc ASC, accounts.id DESC";
                break;
            case 3:
                $orderres = "ORDER BY accounts.status ASC, accounts.id DESC";
                break;
            case 4:
                $orderres = "ORDER BY currencies.name ASC, accounts.id DESC";
                break;
            case 5:
                $orderres = "ORDER BY accounts.id ASC";
                break;
            case -1:
                $orderres = "ORDER BY countries.name DESC, accounts.id DESC";
                break;
            case -2:
                $orderres = "ORDER BY paymentmethods.dsc DESC, accounts.id DESC";
                break;
            case -3:
                $orderres = "ORDER BY accounts.status DESC, accounts.id DESC";
                break;
            case -4:
                $orderres = "ORDER BY currencies.name DESC, accounts.id DESC";
                break;
            case 5:
                $orderres = "ORDER BY accounts.id DESC";
                break;
            default:
                $orderres = "ORDER BY accounts.id DESC";
                break;
        }
        
        return $orderres;
    }
?>
