<?php 
    function getExchanges($db, $pairid, $userid, $exchangenumofrec,$ownexchange){
        if($ownexchange){ //Se crea el filtro en caso de que se pida el reques de solo las nuestras
            /*$filtacc =  "INNER JOIN     accounts A ".
                        "ON             ".$userid." = A.userid " .
                        "AND            T.accountid = A.id";*/
            $filtacc = "AND ".$userid." = A.userid";
        }
        /*
        $trans =    "SELECT		O.pairid, O.price, " .
                    "           ABS(T.amount) AS amount, T.datecreated, T.id AS tid, " . 
                    "           IF  ( ".
                    "               (O.type = 2), ".
                    "               IF(O.side = 1, '2','1'), ".
                    "               IF(O.side = 1, '1','2') " .
                    "               )   AS side " .
                    "FROM		orders O  ".
                    "INNER JOIN	transactions T ".
                    "ON			O.id = T.orderid ". 
                    "INNER JOIN pairs P " .
                    "ON         P.id = O.pairid ".
                    "INNER JOIN accounts A ".
                    "ON         A.id = O.accountid AND P.refcurrencyid = A.currencyid " .                    
                    "WHERE		T.id IN ".
                    "            ( ".
                    "            	SELECT 		T.id tid ".
                    "            	FROM 		transactions T  ".
                    "               INNER JOIN  orders O ".
                    "               ON          O.id = T.orderid ".
                    "               AND         T.accountid = O.accountid " .
                    "               WHERE		T.txid IN ".
                    "               ( ".
                    "            	    SELECT 		T.txid tid ".
                    "            	    FROM 		transactions T  ".
                    "                   INNER JOIN  orders O ".
                    "                   ON          O.id = T.orderid ".
                                        $filtacc .  
                    "                   GROUP BY    O.id ".
                    "               ) ".
                    "           ) ".                  
                    "LIMIT       ".$exchangenumofrec;*/
                    $trans ="SELECT A.* FROM (  ".
                    "   SELECT O.id id, ".
                    "   O.pairid,   ".
                    "   O.price,".
                    "   A.currencyid,".
                    "   O.quantity AS amount, ".
                    "   T.datecreated, ".
                    "   T.txid AS tid, ".
                    "   IF( ".
                    "       (O.type = 2),".
                    "       IF(O.side = 1, '2', '1'), ".
                    "       IF(O.side = 1, '1', '2') ".
                    "   ) AS side ".
                    "   FROM ".
                    "   orders O ".
                    "   INNER JOIN transactions T ON ".
                    "   O.id = T.orderid ".
                    "   INNER JOIN pairs P ON ".
                    "   P.id = O.pairid ".
                    "   INNER JOIN accounts A ON ".
                    "   A.id = T.accountid AND P.refcurrencyid = A.currencyid ".                    
                        $filtacc .  
                    "   GROUP BY O.id  ".
                    "   ORDER BY `tid`  DESC) A GROUP BY A.tid  ".
                    "ORDER BY `A`.`id`  DESC ";
        
        $sql =      "SELECT 	P.id AS pairsid, " .
                    "           P.refcurrencyid AS pairsrefcurrency,  ".
                    "           C.name AS currencyname, ".
                    "           C.symbol AS currencysymbol, ".
                    "           C.icon AS currencyicon, ".
                    "           C.decimals AS currencydecimals, ".
                    "           C.id AS currencyid, ".
                    "           CR.name AS refcurrencyname, ".
                    "           CR.symbol AS refcurrencysymbol, ".
                    "           CR.icon AS refcurrencyicon, ".
                    "           CR.decimals AS refcurrencydecimals, ".
                    "           IFNULL(T.amount, 0) qty, ".
                    "           IFNULL(T.price, 0) orderprice , ".
                    "           IFNULL(T.datecreated, '') datecreated, ".
                    "           IFNULL(T.tid, '') tid, ".
                    "           IFNULL(T.side, '1') orderside ".
                    "FROM 		pairs P ".
                    "INNER JOIN currencies C ".
                    "ON			C.id = P.currencyid ".
                    "INNER JOIN currencies CR ".
                    "ON			P.refcurrencyid= CR.id ".
                    "INNER JOIN  (".$trans .") T ".
                    "ON         T.pairid = P.id " .
                    "WHERE 		P.status = 1 AND P.id = " .$pairid. " ".                    
                    "ORDER BY   T.datecreated DESC, T.tid DESC ".
                    "LIMIT       ".$exchangenumofrec;

            if (!$rs=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            while($row = $rs->fetch_assoc()){
                
                $currencydecimals = $row['currencydecimals'];
                $refcurrencydecimals = $row['refcurrencydecimals'];

                $record = new stdClass();
            
                $record->price = new stdClass();
                $record->price->number = (float)number_format($row['orderprice'],$currencydecimals,".","");
                $record->price->formatted = number_format($record->price->number,$currencydecimals,",",".");
            
                $record->quantity = new stdClass();
                $record->quantity->number = (float)number_format(abs($row['qty']),$refcurrencydecimals,".","");
                $record->quantity->formatted = number_format($record->quantity->number,$refcurrencydecimals,",",".");
            
                $record->date = new stdClass();
                $record->date->cannonical = date("Y-m-d H:i:s", strtotime($row['datecreated']));
                $record->date->formatted = date("d/m/Y H:i", strtotime($row['datecreated']));
            
                $record->side = new stdClass();
                $record->side->id = (int)$row['orderside'];
                $record->side->dsc = $record->side->id == 1 ? 'Venta' : 'Compra' ;
            
                $exchanges [] = $record;
            }
        /*
        
        //Obtenemos los datos del par para obtener los decimales base
        $sql = "SELECT pairs.refcurrencyid AS pairscurrency, ".
        "       currencies.decimals AS currencydecimals ".
        "       FROM pairs, currencies ".
        "       WHERE pairs.id AND".
        "       pairs.status = 1 AND ".
        "       pairs.id = ".$pairid." AND ".
        "       currencies.id = pairs.currencyid ".
        "       GROUP BY pairs.id".
        "       ORDER BY pairs.id ASC";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $row = $rs->fetch_assoc();
        $currencydecimals = $row['currencydecimals'];
        
        //Obtenemos los datos del par para obtener los decimales ref
        $sql = "SELECT pairs.refcurrencyid AS pairscurrency, ".
        "       currencies.decimals AS currencydecimals ".
        "       FROM pairs, currencies ".
        "       WHERE pairs.id AND".
        "       pairs.status = 1 AND ".
        "       pairs.id = ".$pairid." AND ".
        "       currencies.id = pairs.refcurrencyid ".
        "       GROUP BY pairs.id".
        "       ORDER BY pairs.id ASC";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $row = $rs->fetch_assoc();
        $refcurrencydecimals = $row['currencydecimals'];
        */
        
        /*
        if(($ownexchange == 1 && $ownfilterexchange != '') || $ownexchange == 0){
            $sql = "SELECT orders.id AS orderid, ".
            "       orders.quantity AS orderqty, ".
            "       IF(orders.type = 1, orders.side, IF(orders.side = 1, 2, 1)) AS orderside, ".
            "       (SELECT ord.price FROM orders ord ".
            "       WHERE ord.type = 2 AND (ord.id = t.orderid OR ord.id = txother.orderid)) AS orderprice, ".
            "       t.id AS txid, ".
            "       t.datecreated AS datecreated,  ".
            "       IF(orders.side = 2, t.amount, tx.amount) AS qty ".
            "       FROM orders, accounts, transactions t  ".
            "           LEFT JOIN transactions tx ".
            "           ON t.orderid = tx.orderid  ".
            "           AND t.txid = tx.txid ".
            "           AND tx.amount < 0 ".
            "           AND tx.dsc NOT LIKE 'Comisi%' ".
            "           LEFT JOIN transactions txother ".
            "           ON t.orderid != txother.orderid ".
            "           AND t.txid = txother.txid  ".
            "           AND txother.amount > 0 ".
            "           AND txother.dsc NOT LIKE 'Comisi%' ".
            "       WHERE t.orderid IS NOT NULL ".
            "       ".$ownfilterexchange.
            "       AND orders.id = txother.orderid ".
            "       AND orders.pairid = ".$pairid.
            "       AND t.id = t.txid ".
            "       AND t.dsc NOT LIKE 'Comisi%' ".
            "       AND accounts.id = orders.accountid ".
            "       GROUP BY t.txid ".
            "       ORDER BY datecreated DESC, txid DESC".
            "       LIMIT ".$exchangenumofrec;
            if (!$rs=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
        
            while($row = $rs->fetch_assoc()){
                $record = new stdClass();
                $record->id = (int)$row['orderid'];
            
                $record->price = new stdClass();
                $record->price->number = (float)number_format($row['orderprice'],$currencydecimals,".","");
                $record->price->formatted = number_format($record->price->number,$currencydecimals,",",".");
            
                $record->quantity = new stdClass();
                $record->quantity->number = (float)number_format(abs($row['qty']),$refcurrencydecimals,".","");
                $record->quantity->formatted = number_format($record->quantity->number,$refcurrencydecimals,",",".");
            
                $record->date = new stdClass();
                $record->date->cannonical = date("Y-m-d H:i:s", strtotime($row['datecreated']));
                $record->date->formatted = date("d/m/Y H:i", strtotime($row['datecreated']));
            
                $record->side = new stdClass();
                $record->side->id = (int)$row['orderside'];
                $record->side->dsc = $record->side->id == 1 ? 'Venta' : 'Compra' ;
            
                $exchanges [] = $record;
            }   
        }
    */
        return $exchanges;
    }
?>