<?php
header('Content-Type: application/json');
date_default_timezone_set("Asia/Jakarta");
include 'config/koneksi.php';
include 'config/class_softgaming.php';

// Log callback untuk debugging
$logFile = __DIR__ . '/logs/qris_callback_' . date('Y-m-d') . '.log';
$logDir = dirname($logFile);
if (!is_dir($logDir)) {
    mkdir($logDir, 0755, true);
}

function writeLog($message) {
    global $logFile;
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}

writeLog('=== CALLBACK QRIS OTOMATIS RECEIVED ===');

// Ambil raw input
$jsonInput = file_get_contents('php://input');
writeLog('Raw Input: ' . $jsonInput);

$data = json_decode($jsonInput, true);

if (!$data) {
    writeLog('ERROR: Invalid JSON input');
    die(json_encode(['status' => 'error', 'message' => 'Invalid JSON data']));
}

writeLog('Parsed Data: ' . print_r($data, true));

// Validasi data yang diperlukan
if (!isset($data['trx_id']) || !isset($data['amount']) || !isset($data['terminal_id']) || !isset($data['status'])) {
    writeLog('ERROR: Missing required fields');
    die(json_encode(['status' => 'error', 'message' => 'Missing required fields']));
}

$trx_id = mysqli_real_escape_string($conn, $data['trx_id']);
$amount = (int)$data['amount'];
$terminal_id = mysqli_real_escape_string($conn, $data['terminal_id']); // username
$status = mysqli_real_escape_string($conn, $data['status']);
$rrn = isset($data['rrn']) ? mysqli_real_escape_string($conn, $data['rrn']) : '';
$custom_ref = isset($data['custom_ref']) ? mysqli_real_escape_string($conn, $data['custom_ref']) : '';
$vendor = isset($data['vendor']) ? mysqli_real_escape_string($conn, $data['vendor']) : '';
$created_at = isset($data['created_at']) ? mysqli_real_escape_string($conn, $data['created_at']) : date('Y-m-d H:i:s');
$finish_at = isset($data['finish_at']) ? mysqli_real_escape_string($conn, $data['finish_at']) : date('Y-m-d H:i:s');

writeLog("Processing: trx_id=$trx_id, amount=$amount, terminal_id=$terminal_id, status=$status");

// Cari transaksi berdasarkan trx_id (disimpan di note)
$sqlTrx = mysqli_query($conn, "SELECT userID, status, kd_transaksi, total, gameid FROM tb_transaksi WHERE note LIKE '%$trx_id%' AND jenis = 1 LIMIT 1");
$trxData = mysqli_fetch_assoc($sqlTrx);

if (!$trxData) {
    writeLog("ERROR: Transaction not found for trx_id: $trx_id");
    die(json_encode(['status' => 'error', 'message' => 'Transaction not found: ' . $trx_id]));
}

writeLog("Found transaction: kd_transaksi=" . $trxData['kd_transaksi'] . ", userID=" . $trxData['userID'] . ", status=" . $trxData['status']);

// Jika sudah diproses, return success
if ($trxData['status'] == 1) {
    writeLog("Transaction already processed");
    die(json_encode(['status' => 'success', 'message' => 'Already processed']));
}

// Hanya proses jika status = 'success'
if ($status !== 'success') {
    writeLog("Status is not success: $status");
    die(json_encode(['status' => 'error', 'message' => 'Payment status is not success']));
}

$userID = $trxData['userID'];
$kd_transaksi = mysqli_real_escape_string($conn, $trxData['kd_transaksi']);
$gameid = $trxData['gameid'];

writeLog("Extracted data - userID: $userID, kd_transaksi: $kd_transaksi, gameid: $gameid");

// Ambil username dari database
$sqlUser = mysqli_query($conn, "SELECT username FROM tb_user WHERE cuid = '$userID' LIMIT 1");
$u = mysqli_fetch_assoc($sqlUser);

if (!$u) {
    writeLog("ERROR: User not found for userID: $userID");
    die(json_encode(['status' => 'error', 'message' => 'User not found']));
}

$username_web = $u['username'];
writeLog("Username: $username_web");

// Deposit ke NexusGGR API DULU sebelum update status
$WL = new fiver();
$agent_sign = 'DEPO_' . $kd_transaksi . '_' . time();
$res = $WL->deposit($username_web, $amount, $agent_sign);

writeLog("NexusGGR Deposit Response: " . print_r($res, true));

if (isset($res['status']) && $res['status'] == 1) {
    // Jika deposit API berhasil, baru update status dan saldo
    writeLog("NexusGGR deposit successful, updating transaction status and balance");
    
    // Update status transaksi di database
    // Gunakan kondisi yang lebih spesifik: kd_transaksi + userID + jenis + status = 0 untuk memastikan update row yang benar
    $updateStatusQuery = "UPDATE tb_transaksi SET status = 1 WHERE kd_transaksi = '$kd_transaksi' AND userID = '$userID' AND jenis = 1 AND status = 0";
    writeLog("Executing query: $updateStatusQuery");
    $updateStatusResult = mysqli_query($conn, $updateStatusQuery);
    
    if (!$updateStatusResult) {
        $error = mysqli_error($conn);
        writeLog("ERROR: Failed to update transaction status: $error");
        die(json_encode(['status' => 'error', 'message' => 'Failed to update transaction status: ' . $error]));
    }
    
    $affectedRows = mysqli_affected_rows($conn);
    writeLog("Update status affected rows: $affectedRows");
    
    if ($affectedRows == 0) {
        writeLog("WARNING: No rows affected. Checking transaction status...");
        // Verifikasi apakah transaksi sudah status 1 atau ada masalah lain
        $verifyQuery = mysqli_query($conn, "SELECT status, kd_transaksi, userID, jenis FROM tb_transaksi WHERE kd_transaksi = '$kd_transaksi' LIMIT 1");
        if ($verifyQuery) {
            $verifyData = mysqli_fetch_assoc($verifyQuery);
            if ($verifyData) {
                writeLog("Current transaction in DB - status: " . $verifyData['status'] . ", kd_transaksi: " . $verifyData['kd_transaksi'] . ", userID: " . $verifyData['userID'] . ", jenis: " . $verifyData['jenis']);
                
                // Jika status sudah 1, berarti sudah diproses sebelumnya
                if ($verifyData['status'] == 1) {
                    writeLog("Transaction already has status = 1, skipping update");
                } else {
                    // Coba update lagi tanpa kondisi status = 0 (mungkin ada race condition)
                    writeLog("Attempting update without status condition...");
                    $updateStatusQuery2 = "UPDATE tb_transaksi SET status = 1 WHERE kd_transaksi = '$kd_transaksi' AND userID = '$userID' AND jenis = 1";
                    $updateStatusResult2 = mysqli_query($conn, $updateStatusQuery2);
                    if ($updateStatusResult2) {
                        $affectedRows2 = mysqli_affected_rows($conn);
                        writeLog("Second update attempt affected rows: $affectedRows2");
                    }
                }
            } else {
                writeLog("ERROR: Transaction not found in database for kd_transaksi: $kd_transaksi");
            }
        }
    } else {
        writeLog("Successfully updated transaction status to 1 for kd_transaksi: $kd_transaksi");
    }
    
    // Update saldo lokal
    $updateBalanceQuery = "UPDATE tb_balance SET active = active + $amount WHERE userID = '$userID'";
    writeLog("Executing query: $updateBalanceQuery");
    $updateBalanceResult = mysqli_query($conn, $updateBalanceQuery);
    
    if (!$updateBalanceResult) {
        $error = mysqli_error($conn);
        writeLog("ERROR: Failed to update balance: $error");
        // Rollback status jika update balance gagal
        mysqli_query($conn, "UPDATE tb_transaksi SET status = 0 WHERE kd_transaksi = '$kd_transaksi'");
        die(json_encode(['status' => 'error', 'message' => 'Failed to update balance: ' . $error]));
    }
    
    $balanceAffectedRows = mysqli_affected_rows($conn);
    writeLog("Update balance affected rows: $balanceAffectedRows, Amount: +$amount");
    
    // Verifikasi final status
    $finalCheck = mysqli_query($conn, "SELECT status FROM tb_transaksi WHERE kd_transaksi = '$kd_transaksi' LIMIT 1");
    if ($finalCheck) {
        $finalData = mysqli_fetch_assoc($finalCheck);
        $finalStatus = $finalData['status'] ?? 'not found';
        writeLog("Final verification - Transaction status: $finalStatus");
        
        // Jika status masih belum 1, coba update sekali lagi sebagai fallback
        if ($finalStatus != 1 && $finalStatus != 'not found') {
            writeLog("WARNING: Final status is not 1 ($finalStatus), attempting final update...");
            $finalUpdateQuery = "UPDATE tb_transaksi SET status = 1 WHERE kd_transaksi = '$kd_transaksi'";
            $finalUpdateResult = mysqli_query($conn, $finalUpdateQuery);
            if ($finalUpdateResult) {
                $finalAffectedRows = mysqli_affected_rows($conn);
                writeLog("Final update attempt affected rows: $finalAffectedRows");
                
                // Verifikasi lagi setelah final update
                $finalCheck2 = mysqli_query($conn, "SELECT status FROM tb_transaksi WHERE kd_transaksi = '$kd_transaksi' LIMIT 1");
                if ($finalCheck2) {
                    $finalData2 = mysqli_fetch_assoc($finalCheck2);
                    writeLog("After final update - Transaction status: " . ($finalData2['status'] ?? 'not found'));
                }
            }
        }
    }
    
    writeLog("NexusGGR deposit successful");
    
    // Jika ada bonus (gameid), update turnover
    if ($gameid > 0) {
        $getTO = mysqli_query($conn, "SELECT * FROM `tb_turnover` WHERE trxID = '$kd_transaksi'") or die(mysqli_error($conn));
        $goo = mysqli_num_rows($getTO);
        
        if ($goo > 0) {
            $go = mysqli_fetch_array($getTO);
            $bonus = $go['bonus'];
            $totalBalance = $amount + $bonus;
            
            // Update saldo dengan bonus
            mysqli_query($conn, "UPDATE `tb_balance` SET `active` = `active` + '$bonus' WHERE `userID` = '$userID'") or die(mysqli_error($conn));
            
            // Deposit bonus ke NexusGGR juga
            $agent_sign_bonus = 'BONUS_' . $kd_transaksi . '_' . time();
            $resBonus = $WL->deposit($username_web, $bonus, $agent_sign_bonus);
            
            // Update status turnover
            mysqli_query($conn, "UPDATE `tb_turnover` SET `status` = 1 WHERE `trxID` = '$kd_transaksi'") or die(mysqli_error($conn));
            
            writeLog("Bonus processed: $bonus, NexusGGR Response: " . print_r($resBonus, true));
        }
    }
    
    writeLog("=== CALLBACK PROCESSED SUCCESSFULLY ===");
    echo json_encode([
        'status' => 'success',
        'message' => 'Payment processed successfully',
        'trx_id' => $trx_id,
        'amount' => $amount,
        'username' => $username_web
    ]);
} else {
    $errorMsg = isset($res['msg']) ? $res['msg'] : 'Unknown error';
    writeLog("ERROR: NexusGGR deposit failed: $errorMsg");
    
    // Rollback status transaksi jika deposit API gagal
    mysqli_query($conn, "UPDATE tb_transaksi SET status = 0 WHERE kd_transaksi = '$kd_transaksi'") or die(mysqli_error($conn));
    mysqli_query($conn, "UPDATE tb_balance SET active = active - $amount WHERE userID = '$userID'") or die(mysqli_error($conn));
    
    writeLog("Rolled back transaction due to API failure");
    
    echo json_encode([
        'status' => 'error',
        'message' => 'NexusGGR deposit failed: ' . $errorMsg,
        'trx_id' => $trx_id
    ]);
}
?>
