<?php
// app/api/transactions/movements

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid","accountid","time");
    if (!parametrosValidos($_GET, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    }
    
    //Declaracion de variables
    $out = new stdClass();
    $sessionid = $_GET["sessionid"];
    $time = "";
    $accountid = $_GET["accountid"];
    $filter = "";
    
    //Validamos la session
    isSessionValid($db, $sessionid);
    
    //Obtenemos el lenguaje del usuario
    $lang = updateLang($db,$sessionid);
    
    //Consultamos la cuenta para validar que exista
    $sql = "SELECT count(id) AS qty FROM accounts WHERE accounts.entityusrid = -1 AND id = ".$accountid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    //Retornamos 404 si no existe
    if($row["qty"] == 0){
        badEnd("404",array("msg"=>determinateMsgFail(array(
            "esp"=>"Registro no encontrado",
            "eng"=>"Record not found"), $lang, "Registro no encontrado")));
    }
    
    //En caso de que el search sea enviado, se construye el query
    if(isset($_GET["search"]) && $_GET["search"] != ""){
        $filter = "AND t.dsc LIKE '".$_GET["search"]."%'";
    }
    
    //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";
    }
    
    $sqlDeposits =  "SELECT         t.id, t.dsc, ".
                    "               IF(d.valid IS NOT NULL, 1, " . //Si es valido, si no validamos el rechazado
                    "               IF(d.rejected IS NOT NULL, -1, 0)) AS status, " . //Si tampoco est�� rechazado pendiente
                    "               t.accountorigin, t.accountdestination, " .
                    "               IF(t.amount = 0, t.amountghost, t.amount) AS amount, ".
                    "               DATE_FORMAT(t.datecreated, '%Y-%m-%d %H:%i') AS datecreated, ".
                    "               t.amountghost AS amountghost,  ".
                	"		        t.accountid, ".
                	"               IF(t.id <> t.txid, 'Comisi&oacuten', 'Dep&oacutesito') AS typedsc, ".
                    "               IF(t.id <> t.txid, 'FEE', 'DEP') AS type, ".
                    "               '2' AS 'group' " .
                    "FROM           transactions t ".
                    "INNER JOIN     deposits d ON d.transactionid = t.txid ".
                    "INNER JOIN     accounts a " .
                    "ON             t.accountid = a.id " .
                    "               AND a.id = " . $accountid . " " .
                    "               AND a.paymentmethodid = -1 " .
                    "               AND a.entityusrid = -1 ";
    
    $sqlWithdraw =  "SELECT         t.id, t.dsc, ".
                    "               IF(d.valid IS NOT NULL, 1, " . //Si es valido, si no validamos el rechazado
                    "               IF(d.rejected IS NOT NULL, -1, 0)) AS status, " . //Si tampoco est�� rechazado pendiente
                    "               t.accountorigin, t.accountdestination, " .
                    "               IF(t.amount = 0, t.amountghost, t.amount) AS amount, ".
                    "               DATE_FORMAT(t.datecreated, '%Y-%m-%d %H:%i') AS datecreated, ".
                    "               t.amountghost AS amountghost,  ".
                	"		        t.accountid, ".
                	"               IF(t.id <> t.txid, 'Comisi&oacuten', 'Retiro') AS typedsc, ".
                    "               IF(t.id <> t.txid, 'FEE', 'WITH') AS type, ".
                    "               '2' AS 'group' " .
                    "FROM           transactions t ".
                    "INNER JOIN     withdrawals d ON d.transactionid = t.txid ".
                    "INNER JOIN     accounts a " .
                    "ON             t.accountid = a.id " .
                    "               AND a.id = " . $accountid .
                    "               AND a.paymentmethodid = -1 " .
                    "               AND a.entityusrid = -1 ";
                    
    $sqlXch     =   "SELECT         t.id, t.dsc, ".
                    "               '1' AS status, " .
                    "               t.accountorigin, t.accountdestination, " .
                    "               IF(t.amount = 0, t.amountghost, t.amount) AS amount, ".
                    "               DATE_FORMAT(t.datecreated, '%Y-%m-%d %H:%i') AS datecreated, ".
                    "               t.amountghost AS amountghost,  ".
                	"		        t.accountid, ".
                	"               IF(adest.paymentmethodid<>-1, 'Comisi&oacuten', 'Intercambio') AS typedsc, ".
                    "               IF(adest.paymentmethodid<>-1, 'FEE', 'XCH') AS type, ".
		            "               '3' AS 'group' " .
                    "FROM           transactions t " . 
                    "INNER JOIN     orders o ON o.id = t.orderid " .
                    "INNER JOIN     accounts a " .
                    "ON             t.accountid = a.id " .
                    "               AND a.id = ". $accountid . 
                    "               AND a.paymentmethodid = -1 " .
                    "               AND a.entityusrid = -1 " .
                	"LEFT JOIN      accounts adest ON adest.id = t.accountdestination ";
                	
                	
    $sqlXfer     =  "SELECT         t.id, t.dsc, ".
                    "               IF(t.paypending = 1, 0, 1) AS status, " .
                    "               t.accountorigin, t.accountdestination, " .
                    "               IF(t.amount = 0, t.amountghost, t.amount) AS amount, ".
                    "               DATE_FORMAT(t.datecreated, '%Y-%m-%d %H:%i') AS datecreated, ".
                    "               t.amountghost AS amountghost,  ".
                	"		        t.accountid, ".
                	"               IF(adest.paymentmethodid<>-1, 'Comisi&oacuten', 'Transferencia') AS typedsc, ".
                    "               IF(adest.paymentmethodid<>-1, 'FEE', 'XFER') AS type, ".
		            "               '3' AS 'group' " .
                    "FROM           transactions t " . 
                	"LEFT JOIN 	    deposits d ON d.transactionid = t.txid " .
                    "LEFT JOIN 	    withdrawals w ON w.transactionid = t.txid " .
                    "LEFT JOIN 	    pagomovildetails pm ON pm.transactionid = t.txid ".
                    "LEFT JOIN 	    paytxdetails ptx ON ptx.transactionid = t.txid ".
                	"INNER JOIN 	accounts a  ".
                	"ON    	   	    a.id = t.accountid  ".
                	"               AND a.entityusrid = -1 ".
                	"               AND a.paymentmethodid = -1 ".
                	"               AND a.id = ". $accountid ." " .//quitar para traer todos
                	"LEFT JOIN      accounts adest ON adest.id = t.accountdestination " .
                	"WHERE 		    d.transactionid IS NULL ". 
                	"               AND w.transactionid IS NULL ".
                    "               AND ptx.transactionid IS NULL ".
                    "               AND pm.transactionid IS NULL ".
                	"               AND t.orderid IS NULL ".
                	"               AND t.accountorigin IS NOT NULL ";
                	
    $sqlPaytx =     "SELECT         t.id, t.dsc, ".
                    "               IF(t.paypending = 1, 0, 1) AS status, " .
                    "               t.accountorigin, t.accountdestination, " .
                    "               IF(t.amount = 0, t.amountghost, t.amount) AS amount, ".
                    "               DATE_FORMAT(t.datecreated, '%Y-%m-%d %H:%i') AS datecreated, ".
                    "               t.amountghost AS amountghost,  ".
                	"		        t.accountid, ".
                	"               IF(adest.paymentmethodid <> -1, 'Comisi&oacuten', 'Pagos AFX Pay') AS typedsc, ".
                    "               IF(adest.paymentmethodid <> -1, 'FEE', 'PAYTX') AS type, " .
                    "               '3' AS 'group' " .
                    "FROM           transactions t ".
                    "INNER JOIN     paytxdetails pd ON pd.transactionid = t.txid ".
                    "INNER JOIN     accounts a " .
                    "ON             t.accountid = a.id " .
                    "               AND a.id = ". $accountid .//quitar para traer todos
                    "               AND a.paymentmethodid = -1 " .
                    "               AND a.entityusrid = -1 " .
                    "LEFT JOIN      accounts adest ON adest.id = t.accountdestination";
                    
        //Movimientos de movil sin sumar las comisiones
        $sqlPM =        "       SELECT  	    t.id, t.txid, t.dsc, pd.ref AS ref, " .        
                        "                       IF(pd.ref IS NOT NULL, 1, 0) AS status, " .
                        "                       t.accountorigin, t.accountdestination, " .
                        "                       IF(t.amount = 0, t.amountghost, t.amount) AS amount, " .
                        "                       DATE_FORMAT(t.datecreated, '%Y-%m-%d %H:%i') AS datecreated,  ". 
                        "                       t.amountghost AS amountghost, " .    			        
    			        "                       t.accountid, t.paypending AS paypending, t.validator AS validator, " .
    			        "                       IF(adest.paymentmethodid <> -7, 'Comisi&oacuten', 'Cripto Pago') AS typedsc, ".
    			        "                       IF(adest.paymentmethodid <> -7, 'FEE', 'PMPAY') AS type " .
    			        "       FROM            transactions t " .
        		        "       INNER JOIN      accounts a ON t.accountid = a.id AND a.paymentmethodid = -1 ".
        		        "                       AND a.id = " . $accountid . " " .
        		        "       INNER JOIN      pagomovildetails pd ON pd.transactionid = t.txid ".
    			        "       LEFT JOIN       accounts adest ON adest.id = t.accountdestination" .
    			        "       ORDER BY        t.id ";

        $sqlPMThird =    "       SELECT  	    t.id, t.txid, t.dsc, pp.ref AS ref, " . 
                        "                       IF(pp.status = 4, -1, IF(pp.ref IS NOT NULL AND pp.status = 3, 1, 0)) AS status, " .
                        "                       t.accountorigin, t.accountdestination, " .
                        "                       IF(t.amount = 0, t.amountghost, t.amount) AS amount, " .
                        "                       DATE_FORMAT(t.datecreated, '%Y-%m-%d %H:%i') AS datecreated,  ". 
                        "                       t.amountghost AS amountghost, " .    			        
    			        "                       t.accountid, t.paypending AS paypending, t.validator AS validator, " .
    			        "                       IF(adest.paymentmethodid <> -7, 'Comisi&oacuten', 'Cripto Pago') AS typedsc, ".
    			        "                       IF(adest.paymentmethodid <> -7, 'FEE', 'PMPAY') AS type " .
    			        "       FROM            transactions t " .
        		        "       INNER JOIN      accounts a ON t.accountid = a.id AND a.paymentmethodid = -1 ".
        		        "                       AND a.id = " . $accountid . " " .
                        "       INNER JOIN      payments_pagomovil pp ON pp.txid = t.txid AND pp.status != 3".
    			        "       LEFT JOIN       accounts adest ON adest.id = t.accountdestination" .
    			        "       ORDER BY        t.id ";
    
    $sqlPMGroup =   "SELECT         MIN(PM.id), PM.dsc, PM.status, ".
                    "               MAX(PM.accountorigin) AS accountorigin, MAX(PM.accountdestination)  AS accountdestination, " .
                    "               IF(SUM(PM.amount) = 0, SUM(PM.amountghost), SUM(PM.amount)) AS amount, ".
                    "               DATE_FORMAT(PM.datecreated, '%Y-%m-%d %H:%i') AS datecreated, ".
                    "               PM.amountghost AS amountghost,  ".
                	"		        PM.accountid, ".
                	"               PM.typedsc AS typedsc, " .
                    "               PM.type AS type, " .
                    "               '3' AS 'group' " .
                    "FROM            ( (" . $sqlPM . ") UNION ".
                    "               (".$sqlPMThird."))  PM " .                    
                    "WHERE          PM.paypending = 0 AND PM.validator IS NULL " . //Filtro los que si se confirmaron con código
			        "GROUP BY PM.txid, PM.type";

                    
   // die($sqlPMGroup);
                
    $sqlAjustes =   "SELECT         t.id, t.dsc, ".
                    "               '1' AS status, " .
                    "               t.accountorigin, t.accountdestination, " .
                    "               IF(t.amount = 0, t.amountghost, t.amount) AS amount, ".
                    "               DATE_FORMAT(t.datecreated, '%Y-%m-%d %H:%i') AS datecreated, ".
                    "               t.amountghost AS amountghost,  ".
                	"		        t.accountid, ".
                	"               'Ajuste' AS typedsc, " .
                    "               'AJT' AS type, " .
                    "               '3' AS 'group' " .
                    "FROM           transactions t " .
                    "INNER JOIN     accounts a " .
                    "               ON  t.accountid = a.id " .
                    "               AND a.id = " . $accountid . " " .
                    "               AND a.paymentmethodid = -1 " .
                    "               AND a.entityusrid = -1 " .
                    "LEFT JOIN (" . $sqlDeposits . " UNION " .
                    "           " . $sqlWithdraw . " UNION " .
                    "           " . $sqlXch .      " UNION " .
                    "           " . $sqlXfer .     " UNION " .
                    "           " . $sqlPaytx .    ") AL ON AL.id = t.id " .
                    "LEFT JOIN (" . $sqlPM . ") PM ON PM.id = t.id " .
                    "LEFT JOIN (" . $sqlPMThird . ") PMT ON PMT.id = t.id " .
                    "WHERE          AL.id IS NULL " . //Que no sea un movimiento de pago movil NI ningún anterior          	
                	"               AND PM.id IS NULL".
                    "               AND PMT.id IS NULL";
                    
    
                    
    $ordersFill=    "   SELECT O.id orderid, " .
                    "   SUM(ABS(T.amount)) filled ".
                    "   FROM        transactions T ".
                    "   INNER JOIN  accounts A ON T.accountid = A.id ".
                    "   INNER JOIN  orders O " .
                    "   ON          O.id = T.orderid ".
                    "   AND         (".
                    "                   T.accountid = O.accountid ".
                    "                   OR  (T.accountid = O.paymentid AND T.amount > 0) " .
                    "               ) " .
                    "   INNER JOIN  pairs P ON P.id = O.pairid AND A.currencyid = P.refcurrencyid ".
                    "   WHERE    T.id ".
                    "   IN ( ".
                    "       SELECT      T.id ".
                    "       FROM        transactions T ".
                    "       INNER JOIN  orders O ON ".
                    "                   T.orderid = O.id ".  
                    "       GROUP BY    O.id ".
                    "   ) GROUP BY O.id";
                
    $sqlOrders =    "SELECT     O.id, ".
                    "           CONCAT('Orden de ',(IF(O.side = 1,'Venta','Compra'))) AS dsc, " .
                    "           '0' AS status, " .
                    "           NULL AS accountorigin, NULL AS accountdestination, " .
                    "           IF(O.side = 1,(O.quantity-IFNULL(F.filled,0)),((O.quantity-IFNULL(F.filled,0))*O.price)) AS amount, ".
                    "           DATE_FORMAT(o.date, '%Y-%m-%d %H:%i') AS datecreated, ".
                    "           0 AS amountghost,  ".
                	"		    O.accountid, ".
                	"           CONCAT('Orden de ',(IF(O.side = 1,'Venta','Compra'))) AS typedsc, " .
                    "           'ORD' AS type, " .
                    "           '3' AS 'group' " .
                    "FROM 		pairs P ".
                    "INNER JOIN orders O " .                   
                    "ON         O.pairid = P.id ".
                    "AND        O.canceled IS NULL ".   
                    "LEFT JOIN  (".$ordersFill .") F ".
                    "ON         F.orderid = O.id " .
                    "WHERE 		P.status = 1 AND (O.quantity-IFNULL(F.filled,0))>0 " . //Filtro por par, status del par activo y ordenes no completadas
                    "AND        O.accountid = " . $accountid . " ";

    $sqlMovs =      "SELECT     A.*, " .
                    "           currencies.id AS currid, " .
                    "           currencies.name AS currname, " .
                    "           currencies.symbol AS currsymbol, " .
                    "           currencies.decimals AS decimals, " .
                    "           currencies.icon AS icon, " .
                    "           currencies.interface AS interface, " .
                    "           accounts.id AS accid, " .
                    "           accounts.details1 AS accdetails1, " .
                    "           IF(depos.filetype IS NOT NULL, 1, " .
                    "           IF(withd.paymentaccountid IS NOT NULL, 1, 0) " . 
                    "           ) AS view, " .
                    "           IF(depos.transactionid IS NOT NULL, IFNULL(depos.paymentref, depos.ref), " .
                    "           IF(withd.transactionid IS NOT NULL, IFNULL(withd.paymentref, withd.ref), A.id) " . 
                    "           ) AS ref " .
                    "FROM       accounts " .
                    "INNER  JOIN ( " . $sqlDeposits . " UNION " .
                    "       " . $sqlWithdraw . " UNION " .
                    "       " . $sqlXch .      " UNION " .
                    "       " . $sqlXfer .     " UNION " .
                    "       " . $sqlPaytx .    " UNION " .
                    "       " . $sqlPMGroup .  " UNION " .
                    "       " . $sqlOrders .   " UNION " .
                    "       " . $sqlAjustes . "  ) A " .
                    "       ON A.accountid = accounts.id " .
                    "INNER JOIN currencies ON accounts.currencyid = currencies.id " .
                    "LEFT JOIN  deposits depos ON depos.transactionid = A.id " .
                    "LEFT JOIN  withdrawals withd ON withd.transactionid = A.id " .
                    "ORDER BY A.datecreated DESC, A.id ASC ";
    
    $sqlCnt = "SELECT COUNT(*) AS qty FROM (".$sqlMovs.") A";           
    if (!$rs=$db->query($sqlCnt))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    //Retornamos el total
    $out->numofrecords = (int)$row['qty'];
    
    if (!$rs=$db->query($sqlMovs.$limit))//OJO AQUÍ SE AÑADE EL LIMIT
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    $records = [];//La declaramos vacía primero
    
    while($row = $rs->fetch_assoc()){
        $record = new stdClass();
        $record->id = (int)$row["id"];
        $record->dsc = $row["dsc"];
        $record->status = $row["status"];
        $record->type = $row['group'];
        
        $record->optype = $row['type'];

        $record->imageview = (boolean)(($row['view']==1)?true:false);
        
        $record->date = new stdClass();
        $record->date->canonical = $row["datecreated"];
        $record->date->formatted = getRangeDateString($row["datecreated"])." - ".date("h:i a", strtotime($row["datecreated"]));
        
        $record->amount = new stdClass();
        $record->amount->number = $row["amount"] == 0 ? (float)number_format($row["amountghost"],$row["decimals"],'.','') : (float)number_format($row["amount"],$row["decimals"],'.','');
        $record->amount->formatted = numberFormatt($record->amount->number,$row["decimals"]);
        
        $record->txid = $row['ref'];
        
        $records [] = $record;
    }
    
    $out->records = $records;

    $out->account = new stdClass();
    // Consultamos de la vista ya creada con el balance
    $sql =  "SELECT     accountbalances.*, ".
            "           currencies.id AS currid, " .
            "           currencies.name AS currname, " .
            "           currencies.symbol AS currsymbol, " .
            "           currencies.decimals AS decimals, " .
            "           currencies.icon AS icon, " .
            "           currencies.interface AS interface " .                  
            "FROM       accountbalances ".
            "INNER JOIN accounts    ON  accounts.id = accountbalances.accountid " .
            "INNER JOIN currencies  ON  accounts.currencyid = currencies.id " .
            "WHERE      accountbalances.accountid = ".$accountid;
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    $balancetx = $res->fetch_assoc();            
            
    //Ordenamos los datos de la cuenta
    $out->account->id = (int)$balancetx["accid"];
    $out->account->ref = $balancetx["accdetails1"];
    
    $out->account->currency = new stdClass();
    $out->account->currency->id = (int)$balancetx["currid"];
    $out->account->currency->dsc = $balancetx["currname"];
    $out->account->currency->symbol = $balancetx["currsymbol"];
    $out->account->currency->interface = (int)$balancetx["interface"];
    $out->account->currency->decimals = (int)$balancetx["decimals"];

    //Balance a partir de la vista de balances
    $out->account->balance = new stdClass();
    
    $out->account->balance->number = (float)number_format((number_format($balancetx["balance"],$out->account->currency->decimals,'.','')),$out->account->currency->decimals,'.','');
    $out->account->balance->number = $out->account->balance->number < 0 ? 0 : $out->account->balance->number; //Si es negativo se le muestra al usuario cómo 0 
    $out->account->balance->formatted = numberFormatt($out->account->balance->number,$out->account->currency->decimals);
    
    //Balance a partir de la vista de balances
    $out->account->committed = new stdClass();
    $out->account->committed->number = (float)number_format($balancetx["commited"]*-1,$out->account->currency->decimals,'.','');
    $out->account->committed->formatted = numberFormatt($out->account->committed->number, $out->account->currency->decimals);

    //Balance a partir de la vista de balances
    $out->account->deferred = new stdClass();
    $out->account->deferred->number = (float)number_format($balancetx["deferred"],$out->account->currency->decimals,'.','');
    $out->account->deferred->formatted = numberFormatt($out->account->deferred->number, $out->account->currency->decimals);

    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();

    //HASTA AQUI LA SECCIÓN MODIFICADA ---------- LOS BALANCES DEBEN SER SUSTITUIDOS POR LA VISTA DE ACCOUNTBALANCES
    //Balance de la cuenta
    /*
    $sql = "SELECT SUM(amount) - ABS(IF(( ".
    "           SELECT SUM(CASE WHEN orders.side = 1 THEN orders.quantity ELSE orders.total END) AS amount ".
    "           FROM orders ".
    "           WHERE orders.accountid = ".$accountid.
	"           AND orders.canceled IS NULL ".
	"           AND orders.type != 1) IS NOT NULL,  ".
	"               ( ".
    "           SELECT SUM(CASE WHEN orders.side = 1 THEN orders.quantity ELSE orders.total END) AS amount ".
    "           FROM orders ".
    "           WHERE orders.accountid = ".$accountid.
	"           AND orders.canceled IS NULL ".
	"           AND orders.type != 1), 0)".
    "       + IF(( ".
    "           SELECT SUM(transactions.amount) AS amount ".
    "           FROM transactions, orders ".
    "           WHERE orders.id = transactions.orderid ".
    "           AND transactions.accountid = ".$accountid.
    "           AND orders.accountid = ".$accountid.
	"           AND orders.canceled IS NULL ".
	"           AND transactions.amount < 0 ".
	"           AND orders.type != 1) IS NOT NULL, ( ".
    "           SELECT SUM(transactions.amount) AS amount ".
    "           FROM transactions, orders ".
    "           WHERE orders.id = transactions.orderid ".
    "           AND transactions.accountid = ".$accountid.
    "           AND orders.accountid = ".$accountid.
	"           AND orders.canceled IS NULL ".
	"           AND transactions.amount < 0 ".
	"           AND orders.type != 1),0) ".
	"      + IF ((SELECT SUM(transactions.amount + transactions.amountghost) AS amount ".
	"           FROM transactions  ".
	"           WHERE transactions.paypending = 1".
	"           AND transactions.accountid = ".$accountid.
	"           AND NOT EXISTS(SELECT withdrawals.transactionid FROM withdrawals WHERE withdrawals.transactionid = transactions.id)) IS NOT NULL, ".
	"           (SELECT SUM(transactions.amount + transactions.amountghost) AS amount ".
	"           FROM transactions  ".
	"           WHERE transactions.paypending = 1".
	"           AND transactions.accountid = ".$accountid.
	"           AND NOT EXISTS(SELECT withdrawals.transactionid FROM withdrawals WHERE withdrawals.transactionid = transactions.id)), 0)".
	"      ) as qty FROM transactions WHERE accountid = ".$accountid.
    "       AND paypending = 0";
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    $balancetx = $res->fetch_assoc();
        
    $sql = "SELECT SUM(amount) AS qty ".
    "       FROM ( ".
    "           SELECT SUM(CASE WHEN orders.side = 1 THEN orders.quantity ELSE orders.total END) AS amount ".
    "           FROM orders ".
    "           WHERE orders.accountid = ".$accountid.
	"           AND orders.canceled IS NULL ".
	"           AND orders.type != 1 ".
    "       UNION ALL ".
    "           SELECT SUM(transactions.amount) AS amount ".
    "           FROM transactions, orders ".
    "           WHERE orders.id = transactions.orderid ".
    "           AND transactions.accountid = ".$accountid.
    "           AND orders.accountid = ".$accountid.
	"           AND orders.canceled IS NULL ".
	"           AND transactions.amount < 0 ".
	"           AND orders.type != 1 ".
	"       UNION ALL ".
	"           SELECT SUM(ABS(transactions.amount) + ABS(transactions.amountghost)) AS amount ".
	"           FROM transactions  ".
	"           WHERE transactions.paypending = 1".
	"           AND transactions.accountid = ".$accountid.
	"           AND NOT EXISTS(SELECT withdrawals.transactionid FROM withdrawals WHERE withdrawals.transactionid = transactions.id)".
	"      UNION ALL ".
	"           SELECT SUM(ABS(withdrawals.amount) + ABS(withdrawals.fee)) AS amount ".
	"           FROM transactions, withdrawals ".
	"           WHERE transactions.id = withdrawals.transactionid ".
	"           AND transactions.accountid = ".$accountid.
	"           AND withdrawals.valid IS NUll ".
	"           AND withdrawals.rejected IS NULL ".
    "       ) amount";
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    $balanceorder = $res->fetch_assoc();
        
    //Balance a partir de las transacciones
    $out->account->balance = new stdClass();
    
    $out->account->balance->number = (float)number_format((number_format($balancetx["qty"],$out->account->currency->decimals,'.','')),$out->account->currency->decimals,'.','');
    $out->account->balance->number = $out->account->balance->number < 0 ? 0 : $out->account->balance->number;
    
    $out->account->balance->formatted = numberFormatt($out->account->balance->number,$out->account->currency->decimals);
    
    //Balance a partir de las transacciones
    $out->account->committed = new stdClass();
    $out->account->committed->number = (float)number_format($balanceorder["qty"],$out->account->currency->decimals,'.','');
    $out->account->committed->formatted = numberFormatt($out->account->committed->number,$out->account->currency->decimals);
    
    //Balance pendiente de la cuenta
	$sql = "SELECT SUM(deposits.amount - deposits.fee) as qty ".
    "       FROM accounts, transactions, deposits ".
    "       WHERE transactions.id = deposits.transactionid ".
    "       AND deposits.rejected IS NULL ".
    "       AND deposits.valid IS NULL ".
    "       AND accounts.id = transactions.accountid ".
    "       AND accounts.entityusrid = -1 ".
    "       AND accounts.id = ".$accountid.
    "       AND transactions.amountghost >= 0 ";
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $balance = $res->fetch_assoc();
    
    $out->account->deferred = new stdClass();
    $out->account->deferred->number = (float)number_format($balance["qty"],$out->account->currency->decimals,'.','');
    $out->account->deferred->formatted = numberFormatt($out->account->deferred->number,$out->account->currency->decimals);
    */
    
    
    /*  Formateo de fecha para obtener hace cuando se hizo
    *   Recibe $timestamp como fecha de el movimiento
    *
    */
    function getRangeDateString($timestamp) {
        $current = strtotime(date("Y-m-d"));
        $date    = strtotime($timestamp);

        $datediff = $date - $current;
        $difference = floor($datediff/(60*60*24));

        switch( $difference ) {
            case 0:
                return "Hoy";
                break;
            default:
                return date("d/m/Y", $date);
        }    
    }
?>