<?php
// cms/api/operations/cancel

    header("Content-Type:application/json");
    include("../dbconn.php");
    include("../utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid","id");
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    
    //Declaramos e inicializamos nuestras variables
    $out= new stdClass;
    $sessionid = $_GET["sessionid"];
    $id = $_GET["id"];
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 41))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
    
    //Consultamos los datos del movimiento para saber si fue rechazado o actualizado
    $sql = "SELECT transactions.id AS transactionid, ".
    "       deposits.transactionid AS depositid, ".
    "       deposits.valid AS depositvalid, ".
    "       deposits.rejected AS depositrejected, ".
    "       withdrawals.transactionid AS withdrawalid, ".
    "       withdrawals.rejected AS withdrawrejected, ".
    "       withdrawals.valid AS withdrawvalid ".
    "       FROM transactions ".
    "       LEFT JOIN deposits ON transactions.id = deposits.transactionid".
    "       LEFT JOIN withdrawals ON transactions.id = withdrawals.transactionid".
    "       WHERE transactions.id = ".$id;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
    
    $row = $rs->fetch_assoc();
    $db->autocommit(FALSE);
    
    // 1 = DEPOSITO; 2 = RETIRO WN
    //Si el campo depositid es distinto a null significa que es un deposito
    if($row["depositid"] != null){
        
        //Para revertir un deposito que fue aceptado, debemos verificar el saldo del usuario
        // Para ello consultamos primero si el deposito fue aceptado y luego consultamos su saldo
        $sql = "SELECT IF( deposits.valid IS NOT NULL, 1, 0) AS isValidDeposit, ".
        "       deposits.amount AS amount ".
        "       FROM deposits ".
        "       WHERE transactionid = ".$id;
        if (!$res=$db->query($sql)){
            $error = $db->error;
            $db->rollback();
            $db->close();
            badEnd("500", array("msg"=>$error));
        }
        
        $depositdata = $res->fetch_assoc();
        
        // Si el deposito fue aceptado, comprobaremos que el usuario tenga saldo para revertir esa aceptacion
        if(intval($depositdata['isValidDeposit']) == 1){
            //Consultamos el balance del usuario
            $sql = "SELECT acc.id AS accountid, ".
            "       currencies.decimals AS decimals, ".
            "       (IF( (SELECT SUM(transactions.amount) ".
            "               FROM transactions ".
            "               WHERE transactions.accountid = acc.id ".
            "           ) IS NOT NULL, ".
            "               (SELECT SUM(transactions.amount) ".
            "               FROM transactions ".
            "               WHERE transactions.accountid = acc.id), ".
            "           0) - ".
            "           ( IF(  ".
            "               (SELECT SUM(CASE WHEN orders.side = 1 THEN orders.quantity ELSE orders.total END) AS amount ".
            "                   FROM orders ".
            "                   WHERE orders.accountid = acc.id ".
            "                   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 = acc.id ".
            "                   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 = acc.id ".
            "                   AND orders.accountid = acc.id ".
            "                   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 = acc.id ".
            "                       AND orders.accountid = acc.id ".
            "                       AND orders.canceled IS NULL ".
	        "                       AND transactions.amount < 0 ".
	        "                       AND orders.type != 1), ".
	        "               0) ".
	        "          ) ".
	        "       ) AS avaliable ".
	        "       FROM deposits, transactions, currencies, accounts acc ".
	        "       WHERE deposits.transactionid = ".$id.
	        "       AND transactions.id = deposits.transactionid ".
	        "       AND transactions.accountid = acc.id ".
	        "       AND currencies.id = acc.currencyid";
	        if (!$res=$db->query($sql)){
                $error = $db->error;
                $db->rollback();
                $db->close();
                badEnd("500", array("msg"=>$error));
            }
            
            $balanceUser = $res->fetch_assoc();
            
            // Obtenemos el numero y lo formateamos para redondear
            $balance = number_format($balanceUser['avaliable'], $balanceUser['decimals'], '.', '');
            
            // Si el balance es menor al monto del deposito, retornamos error 402
            if($balance < $depositdata['amount']){
                badEnd("402", array('msg'=>'No pueden existir saldos negativos'));
            }
        }
        
        //Colocamos las fechas en nulo
        $sql = "UPDATE deposits SET".
        "       rejected = NULL, ".
        "       valid = NULL ".
        "       WHERE transactionid = ".$id;
        if (!$db->query($sql)){
            $error = $db->error;
            $db->rollback();
            $db->close();
            badEnd("500", array("msg"=>$error));
        }
        
        //Cambiamos los montos
        $sql = "UPDATE transactions SET".
        "       amountghost = amount + amountghost, ".
        "       amount = 0 ".
        "       WHERE txid = ".$id;
        if (!$db->query($sql)){
            $error = $db->error;
            $db->rollback();
            $db->close();
            badEnd("500", array("msg"=>$error));
        }
    
    }else if($row["withdrawalid"] != null){
        //Colocamos la fecha en nulo
        $sql = "UPDATE withdrawals SET".
        "       filetype = NULL, ".
        "       rejected = NULL, ".
        "       valid = NULL ".
        "       WHERE transactionid = ".$id;
        if (!$db->query($sql)){
            $error = $db->error;
            $db->rollback();
            $db->close();
            badEnd("500", array("msg"=>$error));
        }
        
        //COnsultamos para verificar que sea un retiro y eliminar su archivo
        $sql = "SELECT COUNT(transactionid) AS qty FROM withdrawals WHERE transactionid = ".$id;
        if (!$rs=$db->query($sql)){
            $error = $db->error;
            $db->rollback();
            $db->close();
            badEnd("500", array("msg"=>$error));
        }
        
        //Cambiamos los montos
        $sql = "UPDATE transactions SET".
        "       amount = amount + amountghost, ".
        "       amountghost = 0 ".
        "       WHERE txid = ".$id;
        if (!$db->query($sql)){
            $error = $db->error;
            $db->rollback();
            $db->close();
            badEnd("500", array("msg"=>$error));
        }
    
        $row = $rs->fetch_assoc();
    
        if($row['qty'] > 0){
            //Creamos la direccion del folder
            $urlimg = "../../../app/api/uploads/payments";
            $filesfromdir = glob($urlimg.'/*');

            //Recorremos todos los files para validar que exista el file
            foreach($filesfromdir as $filefromdir){
            
                $extfromdir = pathinfo($filefromdir, PATHINFO_EXTENSION);
                $filename = basename($filefromdir,".".$extfromdir);
                if($filename == $id){
                    //Eliminamos fichero
                    unlink($filefromdir);
                }
            }
        }
    }else{
        badEnd("500", array("msg"=>"La operacion es una transferencia"));
    }
    
    $out->id = (int)$id;
    
    $ipaddress = getRealIP();
    
    //auditoria
    setAudit($db, "OPERACIONES", $sessionid, "CMS", "Se revirtió el movimiento ".$out->id, $ipaddress);
    
    $db->commit();
    $db->close();
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
