<?php
// cms/api/operations/reject

    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, 32))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
    
    //Validamos que exista el registro
    $sql = "SELECT * FROM transactions WHERE txid = ".$id;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
       
    $txdata = $rs->fetch_assoc();
      
    if($txdata["id"] == null){
        badEnd("404", array("msg"=>"No encontrado"));
    }
    
    $db->autocommit(FALSE);
    
   /* while($row = $rs->fetch_assoc()){
        // Retornamos 404 cuando la busqueda no obtiene resutados
        if($row["id"] == null){
            badEnd("404", array("msg"=>"No se encuentra el registro"));
        }
        
        //Insertamos una transaccion con los mismos valores
        $sql = "INSERT INTO transactions(".
        "       datecreated, ".
        "       dsc, ".
        "       amount, ".
        "       amountghost, ".
        "       accountid, ".
        "       txid, ".
        "       accountorigin, ".
        "       accountdestination ".
        "       )".
        "       VALUES (".
        "       NOW(), ".
        "       'Rechazo de ".strtolower($row["dsc"])."', ".
        "       ".($row["amountghost"]*-1).", ".
        "       0, ".
        "       ".$row["accountid"].", ".
        "       ".$row["txid"].", ".
        "       ".($row["accountorigin"] == null ? "NULL" : $row["accountorigin"]).", ".
        "       ".($row["accountdestination"] == null ? "NULL" : $row["accountdestination"]).
        "       )";
        if (!$db->query($sql)){
            $error = $db->error;
            $db->rollback();
            $db->close();
            badEnd("500", array("msg"=>$error));
        }
    }
    
    */
    $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));
    }
        
    //Colocamos la fecha de validacion del retiro
    $sql = "UPDATE withdrawals SET".
    "       rejected = NOW() ".
    "       WHERE transactionid = ".$id;
    if (!$db->query($sql)){
        $error = $db->error;
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    
    //Colocamos la fecha de validacion del deposito
    $sql = "UPDATE deposits SET".
    "       rejected = NOW() ".
    "       WHERE transactionid = ".$id;
    if (!$db->query($sql)){
        $error = $db->error;
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    $out->id = (int)$id;
    
    $ipaddress = getRealIP();
    
    //Obtenemos si es deposito o retiro
    $sql = "SELECT IF(deposits.transactionid IS NULL, 0, 1) AS isDeposit, ".
    "       IF(withdrawals.transactionid IS NULL, 0, 1) AS isWithdraw".
    "       FROM transactions ".
    "       LEFT JOIN deposits ON deposits.transactionid = transactions.id ".
    "       LEFT JOIN withdrawals ON withdrawals.transactionid = transactions.id".
    "       WHERE id = ".$id;
    if (!$res=$db->query($sql)){
        $error = $db->error;
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
            
    $txdataaudit = $res->fetch_assoc();
    
    //auditoria
    setAudit($db, "OPERACIONES", $sessionid, "CMS", "Se rechazó el ".(intval($txdataaudit['isDeposit']) == 1 ? 'depósito' : 'retiro')." ".$out->id, $ipaddress);
    
    $db->commit();
    $db->close();
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
