<?php
// error_reporting(E_ALL);
// ini_set('display_errors', 1);
include_once 'db/koneksi.php';
include 'api/sgx.php';
include 'api/nexus.php';

$logFile = __DIR__ . "/qris_callback_log.txt";

function writeLog($message, $data = [])
{
    global $logFile;
    $log = "[" . date("Y-m-d H:i:s") . "] " . $message;

    if (!empty($data)) {
        $log .= " | " . json_encode($data, JSON_PRETTY_PRINT);
    }

    file_put_contents($logFile, $log . PHP_EOL, FILE_APPEND);
}
$input = file_get_contents("php://input");
$data = json_decode($input, true);
writeLog("Incoming Request", ["raw" => $input, "decoded" => $data]);

if (!$data || !isset($data['terminal_id'], $data['status'], $data['amount'])) {
    writeLog("ERROR: Invalid request body", ["received" => $data]);
    http_response_code(400);
    echo json_encode(["status" => false, "message" => "Invalid request body"]);
    exit;
}

$terminal_id = $koneksi->real_escape_string($data['terminal_id']);
$status = strtolower(trim($data['status']));
$amount = (int)$data['amount'];

$sqlUser = "SELECT * FROM tb_user WHERE username = '$terminal_id' LIMIT 1";
$userResult = mysqli_query($koneksi, $sqlUser);

if (!$userResult) {
    writeLog("ERROR: Gagal mencari user", ["query" => $sqlUser, "error" => $koneksi->error]);
    http_response_code(500);
    echo json_encode(["status" => false, "message" => "Database query error"]);
    exit;
}

if ($userResult->num_rows === 0) {
    writeLog("ERROR: User not found", ["terminal_id" => $terminal_id]);
    http_response_code(404);
    echo json_encode(["status" => false, "message" => "User not found"]);
    exit;
}

$user = mysqli_fetch_assoc($userResult);
writeLog("SUCCESS: User found", ["user" => $user]);

if ($status === 'success') {
    $extplayer = $user['extplayer'];
    $username  = $user['username'];
    $ref       = 'DEP' . strtoupper(substr(md5(uniqid()), 0, 8));
    $jumlah    = $amount;
    $bonus     = 0;
    $bukti     = 'QRIS AUTO';
    $bank_asal = 'QRIS';
    $bank_tujuan = 'SYSTEM AUTO';
    $statusDeposit = 'Sukses';

    $stmt = $koneksi->prepare("
        INSERT INTO tb_deposit 
        (extplayer, username, ref, jumlah, bonus, bukti, bank_asal, bank_tujuan, status, created_at, updated_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
    ");

    $stmt->bind_param(
        "sssisssss",
        $extplayer,
        $username,
        $ref,
        $jumlah,
        $bonus,
        $bukti,
        $bank_asal,
        $bank_tujuan,
        $statusDeposit
    );

    if ($stmt->execute()) {
        $deposit_id = $stmt->insert_id;
        writeLog("SUCCESS: Deposit created", ["deposit_id" => $deposit_id, "user" => $username]);
    } else {
        writeLog("ERROR: Gagal insert tb_deposit", ["error" => $stmt->error]);
        http_response_code(500);
        echo json_encode(["status" => false, "message" => "Gagal menyimpan deposit"]);
        exit;
    }

    $stmt->close();

    $newSaldo = $user['saldo'] + $jumlah;
    $updateSaldo = mysqli_query($koneksi, "UPDATE tb_user SET saldo = $newSaldo WHERE id = {$user['id']}");

    if ($updateSaldo) {
        writeLog("SUCCESS: Saldo updated", ["user_id" => $user['id'], "new_saldo" => $newSaldo]);
    } else {
        writeLog("ERROR: Gagal update saldo", ["error" => mysqli_error($koneksi)]);
    }
    $nx->deposit_member($user['extplayer'], $jumlah);
    $SGX->deposit_member($user['extplayer'], $jumlah);

    echo json_encode([
        "status" => true,
        "message" => "Deposit created successfully",
        "ref" => $ref
    ]);
} else {
    writeLog("INFO: Transaksi bukan success", ["status" => $status]);
    echo json_encode([
        "status" => false,
        "message" => "Transaction not processed (status: $status)"
    ]);
}

$koneksi->close();
writeLog("SUCCESS: Callback execution completed");
