<?php
// app/api/transactions/cancel

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid","id");
    if (!parametrosValidos($_GET, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    }
    
    //Declaracion de variables
    $out = new stdClass();
    $sessionid = $_GET["sessionid"];
    $id = $_GET["id"];
    
    //Validamos la session
    isSessionValid($db, $sessionid);
    
    //Obtenemos el lenguaje del usuario
    $lang = updateLang($db,$sessionid);
    
    //Validamos que exista el registro
    $sql = "SELECT id FROM transactions WHERE id = ".$id. " AND validator IS NOT NULL AND amount = 0";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
            
    $row = $rs->fetch_assoc();
        
    // Retornamos 404 cuando la busqueda no obtiene resutados
    if($row["id"] == null){
        badEnd("404", array("msg"=>determinateMsgFail(array(
            "esp"=>"No se encuentra el registro",
            "eng"=>"Cannot find the record"), $lang, "No se encuentra el registro")));
    }
    
    //Abrimos la transaccion
    $db->autocommit(FALSE);

    //eliminar el retiro(si existe)
    $sql = "DELETE FROM withdrawals WHERE transactionid = ".$id . " AND rejected IS NULL AND valid IS NULL";
    if (!$db->query($sql)){
        $error = determinateDBError($db);
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    //eliminar la transaccion
    $sql = "DELETE FROM transactions ".
    "       WHERE id = ".$id.
    "       OR txid = ".$id . " AND validator IS NOT NULL AND amount = 0";
    if (!$db->query($sql)){
        $error = determinateDBError($db);
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    //Retornamos 304 si no se elimino ningun registro
    if ($db->affected_rows == 0){
        $db->rollback();
        $db->close();
        badEnd("403", array("msg"=>determinateMsgFail(array(
            "esp"=>"No se pudo modificar",
            "eng"=>"Cannot modify"), $lang, "No se pudo modificar")));
    }
    
    $db->commit();
    $db->close();
    
    $out->id = (int)$id;
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>