<?php 
    function getOrders($db, $ownfilterorders, $pairid, $ordernumofrec, $userid, $ownorders){
        
        $orders = new stdClass();
        
        //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(($ownorders == 1 && $ownfilterorders != '') || $ownorders == 0){
            //Obtenemos la cantidad de ventas que hay
            $sql = "SELECT SUM(o.quantity) AS qty, COUNT(o.id) AS grouptx, ".
            "       GROUP_CONCAT(o.id SEPARATOR '-') AS ids, ".
            "       IF( ".
            "           (SELECT SUM(ABS(transactions.amount)) ".
            "               FROM transactions, orders ".
            "               WHERE orders.id = transactions.orderid ".
            "               AND orders.id = o.id ".
            "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
            "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)) IS NOT NULL, ".
            "           (SELECT SUM(ABS(transactions.amount)) ".
            "               FROM transactions, orders ".
            "               WHERE orders.id = transactions.orderid ".
            "               AND orders.id = o.id ".
            "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
            "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)), ".
            "           0 ".
            "       ) AS totallyfilled, ".
            "       o.price, o.side, o.id, o.total".
            "       FROM orders o".
            "       WHERE o.side = 1 AND o.canceled IS NULL AND o.pairid = ".$pairid.
            "       ".$ownfilterorders.
            "       AND (CASE ".
            "           WHEN o.canceled IS NOT NULL THEN -1 ".
            "           WHEN (SELECT SUM(ABS(transactions.amount)) ".
            "               FROM transactions, orders ".
            "               WHERE orders.id = transactions.orderid ".
            "               AND orders.id = o.id ".
            "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
            "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)) >= o.quantity ".
            "               AND o.canceled IS NULL THEN 1 ".
            "           ELSE 0 ".
            "       END) = 0 ".
            "       GROUP BY o.price".
            "       ORDER BY o.price ASC, o.date DESC".
            "       LIMIT ".$ordernumofrec;
            if (!$rs=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
        
            $total = 0;
            //Ordenamos las ventas
            while($row = $rs->fetch_assoc()){
                $record = new stdClass();
                $record->ids = $row["ids"];
                $record->orders = (int)$row["grouptx"];
                
                $temptotal = (float)($row["qty"] - $row['totallyfilled']);
                
                $total += $temptotal;
                
                $record->price = new stdClass();
                $record->price->number = (float)number_format($row["price"],$currencydecimals,'.','');
                $record->price->formatted = number_format($record->price->number,$currencydecimals,",",".");
                
                $record->quantity = new stdClass();
                $record->quantity->number = (float)number_format(($row["qty"] - $row['totallyfilled']),$refcurrencydecimals,'.','');
                $record->quantity->formatted = number_format($record->quantity->number,$refcurrencydecimals,",",".");
                
                $record->total = new stdClass();
                $record->total->number =  (float)number_format($total,$refcurrencydecimals,'.','');
                $record->total->formatted = number_format($record->total->number,$refcurrencydecimals,",",".");
                
                $bids [] = $record;
            }
            
        }
            
        $orders->bids = $bids;
            
        if(($ownorders == 1 && $ownfilterorders != '') || $ownorders == 0){
            //Obtenemos la cantidad de compras que hay
            $sql = "SELECT SUM(o.quantity) AS qty, COUNT(o.id) AS grouptx, ".
            "       GROUP_CONCAT(o.id SEPARATOR '-') AS ids, ".
            "       IF( ".
            "           (SELECT SUM(ABS(transactions.amount)) ".
            "               FROM transactions, orders ".
            "               WHERE orders.id = transactions.orderid ".
            "               AND orders.id = o.id ".
            "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
            "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)) IS NOT NULL, ".
            "           (SELECT SUM(ABS(transactions.amount)) ".
            "               FROM transactions, orders ".
            "               WHERE orders.id = transactions.orderid ".
            "               AND orders.id = o.id ".
            "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
            "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)), ".
            "           0 ".
            "       ) AS totallyfilled, ".
            "       o.price, o.side, o.id, o.total".
            "       FROM orders o".
            "       WHERE o.side = 2 AND o.canceled IS NULL AND o.pairid = ".$pairid.
            "       ".$ownfilterorders.
            "       AND (CASE ".
            "           WHEN o.canceled IS NOT NULL THEN -1 ".
            "           WHEN (SELECT SUM(ABS(transactions.amount)) ".
            "               FROM transactions, orders ".
            "               WHERE orders.id = transactions.orderid ".
            "               AND orders.id = o.id ".
            "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
            "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)) >= o.quantity ".
            "               AND o.canceled IS NULL THEN 1 ".
            "           ELSE 0 ".
            "       END) = 0 ".
            "       GROUP BY o.price".
            "       ORDER BY o.price DESC, o.date DESC".
            "       LIMIT ".$ordernumofrec;
            if (!$rs=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                
            $total = 0;
            //Ordenamos las compras
            while($row = $rs->fetch_assoc()){
                $record = new stdClass();
                $record->ids = $row["ids"];
                $record->orders = (int)$row["grouptx"];
                
                $temptotal = (float)($row["qty"] - $row['totallyfilled']);
                
                $total += $temptotal;
            
                $record->price = new stdClass();
                $record->price->number = (float)number_format($row["price"], $currencydecimals, '.', '');
                $record->price->formatted = number_format($record->price->number,$currencydecimals,",",".");
            
                $record->quantity = new stdClass();
                $record->quantity->number = (float)number_format(($row["qty"] - $row['totallyfilled']), $refcurrencydecimals, '.', '');
                $record->quantity->formatted = number_format($record->quantity->number,$refcurrencydecimals,",",".");
            
                $record->total = new stdClass();
                $record->total->number = (float)number_format($total, $refcurrencydecimals, '.', '');
                $record->total->formatted = number_format($record->total->number,$refcurrencydecimals,",",".");
            
                $asks [] = $record;
            }
        }
    
        $orders->asks = $asks;
        
        //ID ordenes del usuario
        $ownorders = '';
        //Consultamos los datos del para para obtener las monedas
        $sql = "SELECT * FROM pairs WHERE id = ".$pairid;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $row = $rs->fetch_assoc();
        
        //Consultamos las cuentas del usuario por su moneda
        $sql = "SELECT accounts.id AS accountid ".
        "       FROM accounts, users".
        "       WHERE users.id = ".$userid.
        "       AND accounts.userid = users.id".
        "       AND accounts.paymentmethodid = -1".
        "       AND (accounts.currencyid = ".$row['currencyid'].
        "       OR  accounts.currencyid = ".$row['refcurrencyid'].")";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $ownaccounts = [];
        while($row = $rs->fetch_assoc()){
            $ownaccounts [] = $row['accountid'];
        }
        
        $orders->myown = '';
        
        if(sizeof($ownaccounts) > 0){
            $qtyaccounts = sizeof($ownaccounts) - 1;
            foreach($ownaccounts as $index => $accountid){
                if($index == 0){
                    $ownorders = " (";
                }
            
                if($index != 0){
                    $ownorders .= " OR ";
                }
            
                $ownorders .= " accountid = ".$accountid. ' OR paymentid = '.$accountid;
                
                if($index == $qtyaccounts){
                    $ownorders .= ')';
                }
            }
        
            $sql = "SELECT id FROM orders ".
            "       WHERE ".$ownorders;
            if (!$rs=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            while($row = $rs->fetch_assoc()){
                $orders->myown .= "".$row['id']."-";
            }
        
            $orders->myown = $orders->myown == '' ? '' : substr($orders->myown, 0, -1);
        }
        
        return $orders;
    }
?>