<?php
header('Content-Type: application/json');
include 'config/koneksi.php';
include 'config/class.hgi.php';

$jsonInput = file_get_contents('php://input');
$data = json_decode($jsonInput, true);

if (!$data || !isset($data['data']['transaction_id'])) {
    die(json_encode(['status' => 'error', 'message' => 'Invalid Data']));
}

$callbackData = $data['data'];
$transaction_id = mysqli_real_escape_string($conn, $callbackData['transaction_id']); // QR-8S7IN20BM
$amount = (int)$callbackData['amount'];

// 1. Cari transaksi berdasarkan kd_transaksi (lebih cepat daripada LIKE)
$sqlTrx = mysqli_query($conn, "SELECT userID, status FROM tb_transaksi WHERE kd_transaksi = '$transaction_id' LIMIT 1");
$trxData = mysqli_fetch_assoc($sqlTrx);

if (!$trxData) {
    die(json_encode(['status' => 'error', 'message' => 'ID Transaksi tidak dikenal: ' . $transaction_id]));
}

// 2. Jika sudah sukses, berhenti
if ($trxData['status'] == 1) {
    die(json_encode(['status' => 'success', 'message' => 'Sudah diproses']));
}

$userID = $trxData['userID'];

// 3. Ambil username dari tb_user berdasarkan userID dari transaksi
$sqlUser = mysqli_query($conn, "SELECT username FROM tb_user WHERE cuid = '$userID' LIMIT 1");
$u = mysqli_fetch_assoc($sqlUser);
$username_web = $u['username'];

if ($callbackData['status'] === 'success') {
    // A. Update Status & Saldo Lokal
    mysqli_query($conn, "UPDATE tb_transaksi SET status = 1 WHERE kd_transaksi = '$transaction_id'");
    mysqli_query($conn, "UPDATE tb_balance SET active = active + $amount WHERE userID = '$userID'");

    // B. Tembak API HGI
    $hgi = new HypergateAPI();
    $hgiResponse = $hgi->deposit($username_web, $amount);

    echo json_encode(['status' => 'success', 'hgi' => $hgiResponse]);
}
?>