<?php 
// app/api/accounts/list
    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid","paym");
    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"];
    $paym = $_GET["paym"];
    $offset = "";
    $numofrec = "";
    $limit = "";
    $filterpaym = "";
    //Validamos la session
    isSessionValid($db, $sessionid);
    
    //Validamos el valor de $paym
    if($paym == 1){
        $filterPaym = " AND approved IS NOT NULL AND rejected IS NULL AND status = 1";
    }
    
    //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";
    }
    
    //Consultamos los datos del usuario por su ssid
    $sql = "SELECT id, usr FROM users WHERE sessionid = '".$sessionid."'";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    //Guardamos el id del usuario
    $userid = $row["id"];
    
    //Consultamos la cantidad de registros que existen
    $sql = "SELECT count(id) AS qty FROM accounts WHERE userid = ".$userid.
    "       AND paymentmethodid != -1".
    "       ".$filterPaym;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    //Retornamos el total de registros
    $row = $rs->fetch_assoc();
    $out->numofrecords = (int)$row["qty"];
    
    //Consultamos los datos requeridos
    $sql = "SELECT * FROM accounts WHERE userid = ".$userid.
    "       AND paymentmethodid != -1".
    "       ".$filterPaym.
    "       ".$limit;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
        
    while($row = $rs->fetch_assoc()){
        $record = new stdClass();
        //Guardamos el id de la cuenta
        $record->id = (int)$row["id"];
        
        //Metodo de pago
        $record->paymentmethod = new stdClass();
        $record->paymentmethod->id = (int)$row["paymentmethodid"];
        
        //Consultamos el nombre del metodo de pago
        $sql = "SELECT details1, details2, details3, details4,paymentmethods.dsc AS paymentdsc, countries.id AS countryid, countries.name AS countryname".
        "       FROM paymentmethods, countries ".
        "       WHERE paymentmethods.id = ".$row["paymentmethodid"].
        "       AND paymentmethods.countryid = countries.id";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $payment = $res->fetch_assoc();
        //Guardamos el nombre del metodo de pago
        $record->paymentmethod->dsc = $payment["paymentdsc"];
        $cant = 0;
        if($payment["details1"] != null)$cant = $cant + 1;
        if($payment["details2"] != null)$cant = $cant + 1;
        if($payment["details3"] != null)$cant = $cant + 1;
        if($payment["details4"] != null)$cant = $cant + 1;
        
        //Pais del metodo de pago
        $record->country = new stdClass();
        $record->country->id = (int)$payment["countryid"];
        $record->country->dsc = $payment["countryname"];
        
        //Moneda de la cuenta
        $record->currency = new stdClass();
        $record->currency->id = (int)$row["currencyid"];
        
        //Consultamos los datos de la moneda
        $sql = "SELECT * FROM currencies WHERE id = ".$row["currencyid"];
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $currency = $res->fetch_assoc();
        //Guardamos los detalles de la moneda
        $record->currency->dsc = $currency["name"];
        $record->currency->symbol = $currency["symbol"];
        
        $sql = "SELECT SUM(amount) as qty FROM `transactions` WHERE accountid = ".$record->id;
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $balance = $res->fetch_assoc();
        
        //Balance a partir de las transacciones
        $record->balance = (float)number_format($balance["qty"], $currency["decimals"], '.', '');
        $record->balance = $record->balance < 0 ? 0 : $record->balance;
        $record->balancedsc = numberFormatt($record->balance,$currency["decimals"]);
        
        //Datos de la cuenta
        $record->status = (int)$row["status"];
        $record->details1 = $row["details1"] == null ? "" : $row["details1"] ;
        $record->details2 = $row["details2"] == null ? "" : $row["details2"] ;
        $record->details3 = $row["details3"] == null ? "" : $row["details3"] ;
        $record->details4 = $row["details4"] == null ? "" : $row["details4"] ;
        
        $record->valid = new stdClass();
        
        if($row["rejected"] != null){
            $record->valid->id = -1;
        }else if($row["approved"] != null && $row["rejected"] == null && $cant==count(explode(",", $row["approved"]))){
            $record->valid->id = 1;
        }else{
            $record->valid->id = 0;
        }
        
        $record->valid->dsc = validateAccount($record->valid->id);
        
        if($record->valid->id != 1 && $paym == 1){
            $out->numofrecords--;
        }else{
            $records [] = $record;
        }
    }
        
    $out->records = $records;
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
    
    /*  Funcion para validar estado de la cuenta
    *   0 = Pendiente por verificar
    *   1 = Aprobada
    *   -1 = Rechazada
    */
    function validateAccount($valid){
        $strres = "";
        
        switch($valid){
            case 0:
                $strres = "Pendiente";
                break;
            case 1:
                $strres = "Activa";
                break;
            case -1:
                $strres = "Rechazada";
                break;
        }
        
        return $strres;
    }
?>
