<?php
// cms/api/operations/accept

    header("Content-Type:application/json");
    include("../dbconn.php");
    include("../utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid","id");
    if (!parametrosValidos($_POST, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
        
    $paymentfile = $_FILES["paymentfile"];
    
    //Declaramos e inicializamos nuestras variables
    $out= new stdClass;
    $sessionid = $_POST["sessionid"];
    $id = $_POST["id"];
    $paymentdate = "";
    $paymentref = "";
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    //En caso de que el paymentdate sea enviado, se construye el query
    if(isset($_POST["paymentdate"]) && $_POST["paymentdate"] != ""){
        $paymentdate = " paymentdate = '".$_POST["paymentdate"]."', ";
    }
    
    //En caso de que el paymentref sea enviado, se construye el query
    if(isset($_POST["paymentref"]) && $_POST["paymentref"] != ""){
        $paymentref = " paymentref = '".$_POST["paymentref"]."', ";
    }
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 31))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
        
    //Validamos que exista el registro
    $sql = "SELECT id FROM transactions WHERE id = ".$id;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
            
    $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"));
    }
    
    $db->autocommit(FALSE);
    
    //Actualizamos la transaccion
    $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));
    }
    
    if($paymentfile["name"] != null){
        //Obtenemos la extension de la imagen
        $ext = pathinfo($paymentfile['name'], PATHINFO_EXTENSION);
        //Creamos la direccion del folder
        $urlfolder = "../../../app/api/uploads/payments/";
        
        //Movemos el FILE del directorio temporal al del sistema para su uso
        if(!move_uploaded_file($paymentfile["tmp_name"], $urlfolder . "/" . $id . "." . $ext)){
            $db->rollback();
            $db->close();
            badEnd("500", array("msg"=>"Error guardando la imagen"));
        }
    }
    
    //Colocamos la fecha de validacion del retiro
    $sql = "UPDATE withdrawals SET".
    "       ".$paymentref.
    "       ".$paymentdate.
    "       ".($paymentfile["name"] != null ? "filetype = '".$paymentfile["type"]."', " : "").
    "       valid = 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".
    "       valid = 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))
        badEnd("500", array("msg"=>$db->error));
            
    $txdataaudit = $res->fetch_assoc();
    
    //auditoria
    setAudit($db, "OPERACIONES", $sessionid, "CMS", "Se aprobó 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();
?>
