<?php
session_start();
header('Content-Type: application/json');

// Cek apakah user sudah login
if (!isset($_SESSION['user'])) {
    echo json_encode(['status' => 'error', 'message' => 'Anda harus login terlebih dahulu.']);
    exit;
}

include('../../config/koneksi.php');

// Cek apakah trans_id dikirim
if (!isset($_POST['trans_id']) || !is_numeric($_POST['trans_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'ID transaksi tidak valid.']);
    exit;
}

$trans_id = (int)$_POST['trans_id'];
$user = mysqli_query($conn, "SELECT * FROM `tb_user` WHERE username = '" . mysqli_real_escape_string($conn, $_SESSION['user']) . "'") or die(mysqli_error());
$u = mysqli_fetch_array($user);
$userID = (int)$u['cuid'];

// Escape untuk keamanan
$trans_id_escaped = mysqli_real_escape_string($conn, $trans_id);
$userID_escaped = mysqli_real_escape_string($conn, $userID);

// Cek apakah transaksi ada dan milik user yang login
$checkTransaksi = mysqli_query($conn, "SELECT * FROM `tb_transaksi` WHERE cuid = '$trans_id_escaped' AND userID = '$userID_escaped' AND jenis = 1 AND status = 0") or die(mysqli_error());

if (mysqli_num_rows($checkTransaksi) == 0) {
    echo json_encode(['status' => 'error', 'message' => 'Transaksi tidak ditemukan atau sudah diproses.']);
    exit;
}

$transaksi = mysqli_fetch_array($checkTransaksi);

// Mulai transaksi database
mysqli_begin_transaction($conn);

try {
    // Update status transaksi menjadi 2 (Dibatalkan)
    $note = mysqli_real_escape_string($conn, 'Dibatalkan oleh user');
    $updateQuery = "UPDATE `tb_transaksi` SET `status` = 2, `note` = '$note' WHERE `cuid` = '$trans_id_escaped' AND `userID` = '$userID_escaped' AND `jenis` = 1 AND `status` = 0";
    
    if (!mysqli_query($conn, $updateQuery)) {
        throw new Exception('Gagal mengupdate status transaksi: ' . mysqli_error($conn));
    }
    
    // Commit transaksi
    mysqli_commit($conn);
    
    echo json_encode([
        'status' => 'success',
        'message' => 'Deposit berhasil dibatalkan.',
        'trans_id' => $trans_id
    ]);
    
} catch (Exception $e) {
    // Rollback jika terjadi error
    mysqli_rollback($conn);
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
}

mysqli_close($conn);
?>
