<?php
// app/api/web/prices

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // Armamos primero el objeto 
    $out = new stdClass();
    
    // Obtenemos la fecha en Venezuela
    $date = new DateTime('now', new DateTimeZone('America/Caracas'));
    $currentDate = $date->format('Y-m-d H:i:s');
    
    // Fecha de update
    $out->time = new stdClass();
    $out->time->date = date("Y-m-d H:i:s", strtotime($currentDate));
    $out->time->formatted = date("j", strtotime($out->time->date))." ".determinateMonth(date("n", strtotime($out->time->date)))." ".date("Y h:ia", strtotime($out->time->date));
    
    // Consultamos los datos de los pares
    $sql = "SELECT pairs.refcurrencyid AS pairsrefcurrency, ".
    "       currencies.name AS currencyname, currencies.symbol AS currencysymbol, ".
    "       currencies.icon AS currencyicon, ".
    "       currencies.id AS currencyid, pairs.id AS pairsid,".
    "       currencies.decimals AS currencydecimals ".
    "       FROM pairs, currencies ".
    "       WHERE pairs.status = 1 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)));
    
    while($pairdata = $rs->fetch_assoc()){
        $record = new stdClass();
        $record->id = (int) $pairdata["pairsid"];
        
        $rate = determinateRate($db, $pairdata['pairsrefcurrency'], $pairdata['currencyid'], $pairdata['currencydecimals']);
        
        $record->price = new stdClass();
        $record->price->number = (float)number_format($rate->number, $pairdata['currencydecimals'],'.','');
        $record->price->formatted = number_format($record->price->number, $pairdata['currencydecimals'],",",".");
        
        //Consultamos decimales de moneda ref
        $sql = "SELECT * FROM currencies WHERE id = ".$pairdata['pairsrefcurrency'];
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
    
        $pairrefdata = $res->fetch_assoc();
        
        //Consultamos la ultima transaccion hace 24horas
        $sql = "SELECT (SELECT ord.price FROM orders ord ".
        "       WHERE ord.type = 2 AND (ord.id = t.orderid OR ord.id = txother.orderid)) AS transactionamount ".
        "       FROM orders, accounts, transactions t  ".
        "           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 ".
        "       AND orders.id = txother.orderid ".
        "       AND orders.pairid = ".$record->id.
        "       AND t.id = t.txid ".
        "       AND t.dsc NOT LIKE 'Comisi%' ".
        "       AND accounts.id = orders.accountid ".
        "       AND t.datecreated <= DATE_SUB(NOW(), INTERVAL 1 DAY) ".
        "       GROUP BY t.txid ".
        "       ORDER BY t.datecreated DESC, t.id DESC".
        "       LIMIT 1";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $row = $res->fetch_assoc();
        
        $record->variation = new stdClass();
        
        if($record->price->number == 0){
            $record->variation->number = 0;
        }else{
            if($row['transactionamount'] > 0){
                $record->variation->number = (($record->price->number - $row['transactionamount'])*100)/$row['transactionamount'] ;
                //$record->variation->par = $row['transactionamount'];
            }else{
                $record->variation->number = 0;
                //$record->variation->par = $row['transactionamount'];
            }
        }
        
        if($record->variation->number < 0){
            $record->variation->trend = "-";
        }else if($record->variation->number > 0){
            $record->variation->trend = "+";
        }else{
            $record->variation->trend = "";
        }
        
        $record->variation->number = abs($record->variation->number);
        $record->variation->formatted = number_format($record->variation->number,2,",",".")."%";
        
        
        $sql = "SELECT * FROM currencies WHERE id = ".$pairdata["pairsrefcurrency"];
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $row = $res->fetch_assoc();
        
        $record->name = $row["symbol"].'/'.$pairdata["currencysymbol"];
        
        $records [] = $record;
    }
    
    $out->pairs = $records;
    
    $fp = fopen('../../../api/info/prices.json', 'w');
    fwrite($fp, json_encode($out));
    fclose($fp);
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
    
    /* Funcion para determinar mes, recibe:
    *   $month = Numero de el mes
    */
    function determinateMonth($month){
        $str = "";
        
        switch($month){
            case 1:
                $str = "ENE";
                break;
            case 2:
                $str = "FEB";
                break;
            case 3:
                $str = "MAR";
                break;
            case 4:
                $str = "ABR";
                break;
            case 5:
                $str = "MAY";
                break;
            case 6:
                $str = "JUN";
                break;
            case 7:
                $str = "JUL";
                break;
            case 8:
                $str = "AGO";
                break;
            case 9:
                $str = "SEP";
                break;
            case 10:
                $str = "OCT";
                break;
            case 11:
                $str = "NOV";
                break;
            case 12:
                $str = "DIC";
                break;
        }
        
        return $str;
    }
?>
