<?php
// app/api/dashboard/entry

    header("Content-Type:application/json");
    include("../dbconn.php");
    include("../utils.php");
    include_once('pairs.php');
    include_once('orders.php');
    include_once('pairdetails.php');
    include_once('exchanges.php');
    include_once('portfolio.php');
    include_once('chart.php');
    
    // parametros obligatorios
    $parmsob = array("sessionid",'ordernumofrec','exchangenumofrec');
    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();
    $out->dashboard = new stdClass();
    $sessionid = $_GET["sessionid"];
    $pairid = '';
    $ordernumofrec = $_GET['ordernumofrec'];
    $exchangenumofrec = $_GET['exchangenumofrec'];
    $ownorders = 0;
    $ownexchange = 0;
    $ownfilterorders = '';
    $ownfilterexchange = '';
    $totportfolio = '';
    $charttime = (int)$_GET['charttime'];
    
    //Validamos la session
    $userid = isSessionValid($db, $sessionid);
    
    //Validamos el si el usuario puede hacer operaciones
    //isLevelValid($db, $userid);
    
    //Si recibimos totportfolio, guardamos su valor
    if(isset($_GET['totportfolio']) && $_GET['totportfolio'] != ''){
        $totportfolio = $_GET['totportfolio'];
    }else{
        $totportfolio = 0;
    }
    
    //Si recibimos pairid, guardamos su valor
    if(isset($_GET['pairid']) && $_GET['pairid'] != ''){
        $pairid = $_GET['pairid'];
        
        //Contamos para ver que exista el par
        $sql = "SELECT COUNT(id) AS qty FROM pairs WHERE id = ".$pairid;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error.$sql));
    
        $row = $rs->fetch_assoc();
        
        if($row['qty'] == 0){
            badEnd('404',array('msg'=>'Par no encontrado'));
        }
    }else{
        $pairid = getFirstPair($db);
    }
    
    //Si recibimos ownorders, guardamos su valor
    if(isset($_GET['ownorders']) && $_GET['ownorders'] != ''){
        $ownorders = $_GET['ownorders'];
    }
    
    //Si recibimos ownexchange, guardamos su valor
    if(isset($_GET['ownexchange']) && $_GET['ownexchange'] != ''){
        $ownexchange = $_GET['ownexchange'];
    }
    
    //Si el ownorders es 1 se traen las de el usuario
    if($ownorders == 1){
        //Consultamos los datos del par para obtener las monedas
        $sql = "SELECT * FROM pairs WHERE id = ".$pairid;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
        
        $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"=>$db->error));
            
        $ownaccounts = [];
        while($row = $rs->fetch_assoc()){
            $ownaccounts [] = $row['accountid'];
        }
        
        if(sizeof($ownaccounts) > 0){
            $qtyaccounts = sizeof($ownaccounts) - 1;
            foreach($ownaccounts as $index => $accountid){
                if($index == 0){
                    $ownfilterorders = "AND (";
                }
                
                if($index != 0){
                    $ownfilterorders .= " OR ";
                }
                
                $ownfilterorders .= " o.accountid = ".$accountid. ' OR o.paymentid = '.$accountid;
                
                if($index == $qtyaccounts){
                    $ownfilterorders .= ')';
                }
            }
        }
    }
    
    //Si el ownexchange es 1 se traen las de el usuario
    if($ownexchange == 1){
        //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"=>$db->error));
        
        $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"=>$db->error));
            
        $ownaccounts = [];
        while($row = $rs->fetch_assoc()){
            $ownaccounts [] = $row['accountid'];
        }
        
        if(sizeof($ownaccounts) > 0){
            $qtyaccounts = sizeof($ownaccounts) - 1;
            foreach($ownaccounts as $index => $accountid){
                if($index == 0){
                    $ownfilterexchange = "AND (";
                }
            
                if($index != 0){
                    $ownfilterexchange .= " OR ";
                }
            
                $ownfilterexchange .= " orders.accountid = ".$accountid. ' OR orders.paymentid = '.$accountid." OR t.accountid = ".$accountid;
            
                if($index == $qtyaccounts){
                    $ownfilterexchange .= ')';
                }
            }
        }
    }
    
    /*DATOS DE LOS PARES*/
    
    $out->dashboard->pairs = getPairs($db);
    
    /*ORDENES*/
    
    $out->dashboard->orders = getOrders($db, $ownfilterorders, $pairid, $ordernumofrec, $userid, $ownorders);
    
    /*INTERCAMBIOS*/
    
    $out->dashboard->exchanges = getExchanges($db, $pairid, $exchangenumofrec, $ownfilterexchange, $ownexchange);
    
    /*DETALLES DEL PAR*/
    
    $out->dashboard->pairdetails = getPairDetails($db, $pairid, $userid);
    
    /*GRAFICA*/
    
    $out->dashboard->chart = getChart($db, $pairid, $charttime);
    
    /**Portafolio del usuario**/
    
    $out->dashboard->portfolio = getPortfolio($db, $userid, $totportfolio);
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
    
    function getFirstPair($db){
        //Consultamos el primer par de la tabla
        $sql = "SELECT id FROM pairs ".
        "       ORDER BY id ASC ".
        "       LIMIT 0, 1";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $row = $rs->fetch_assoc();
        
        return (int)$row['id'];
        
    }
?>