<?php
// api/callback.php - Professional Fixed Version for Simultaneous Bet & Win
ob_start(); 
ini_set('display_errors', 0); 
error_reporting(E_ALL);

header('Content-Type: application/json; charset=utf-8');
date_default_timezone_set('Asia/Dhaka');

require '../includes/db.php'; 
ob_clean();

// ==========================================
// 1. ADVANCED LOGGING SETUP
// ==========================================
$log_file = 'callback_log.txt';
$current_time = date('Y-m-d h:i:s A');
$log_text = "\n[$current_time] =========================================\n";

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

$log_text .= "RAW INPUT: " . $raw_input . "\n";

if (!$data) {
    echo json_encode(['credit_amount' => 0, 'error' => 'Invalid JSON']);
    exit;
}

// 2. EXTRACT DATA
$game_round     = $data['game_round'] ?? ''; 
$member_account = $data['member_account'] ?? ''; 
$bet_amount     = floatval($data['bet_amount'] ?? 0);
$win_amount     = floatval($data['win_amount'] ?? 0);
$game_uid       = $data['game_uid'] ?? '';
$timestamp      = $data['timestamp'] ?? ''; 

// ৩. ইউনিক ট্রানজ্যাকশন আইডি জেনারেট (নিখুঁত করার জন্য সব প্যারামিটার ব্যবহার করা হয়েছে)
$unique_tx_key = md5($game_round . $game_uid . $bet_amount . $win_amount . $timestamp);

$log_text .= "DATA -> User: $member_account | Game: $game_uid | Round: $game_round | Key: $unique_tx_key\n";

// 4. DATABASE TRANSACTION শুরু
$conn->begin_transaction();

try {
    // ৫. ইউজার চেক এবং রো লক (Row Lock)
    $stmt = $conn->prepare("SELECT balance FROM users WHERE id = ? FOR UPDATE");
    $stmt->bind_param("s", $member_account);
    $stmt->execute();
    $user_res = $stmt->get_result();

    if ($user_res->num_rows == 0) {
        throw new Exception('User not found');
    }

    $user = $user_res->fetch_assoc();
    $old_balance = floatval($user['balance']);
    $new_balance = $old_balance;

    // ৬. ডুপ্লিকেট চেক (ইউনিক কী দিয়ে)
    $check_hist = $conn->prepare("SELECT id FROM game_bet_history WHERE tx_key = ? LIMIT 1");
    $check_hist->bind_param("s", $unique_tx_key);
    $check_hist->execute();
    $is_duplicate = $check_hist->get_result()->num_rows > 0;

    if ($is_duplicate) {
        $log_text .= "ACTION -> DUPLICATE DETECTED. Returning current balance.\n";
    } else {
        // --- ফিক্সড লজিক সেকশন ---
        
        // ৭. প্রসেস বেট (যদি থাকে)
        if ($bet_amount > 0) {
            if ($new_balance >= $bet_amount) {
                $new_balance -= $bet_amount;
                $log_text .= "ACTION -> BET: $bet_amount deducted.\n";
            } else {
                throw new Exception('Insufficient balance');
            }
        }

        // ৮. প্রসেস উইন (যদি থাকে - এখানে বেট ০ হওয়ার শর্ত তুলে দেওয়া হয়েছে)
        if ($win_amount > 0) {
            $new_balance += $win_amount;
            $log_text .= "ACTION -> WIN: $win_amount added.\n";
        }

        // ৯. ডাটাবেজ আপডেট
        $update_user = $conn->prepare("UPDATE users SET balance = ? WHERE id = ?");
        $update_user->bind_param("ds", $new_balance, $member_account);
        $update_user->execute();

        // ১০. হিস্ট্রি সেভ (ইউনিক কী সহ)
        $history_insert = $conn->prepare("INSERT INTO game_bet_history (user_id, game_uid, round_id, bet_amount, win_amount, balance_before, balance_after, tx_key, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'processed', NOW())");
        $history_insert->bind_param("sssdidds", $member_account, $game_uid, $game_round, $bet_amount, $win_amount, $old_balance, $new_balance, $unique_tx_key);
        $history_insert->execute();
        
        $log_text .= "DB -> Balance Updated. Final: $new_balance\n";
    }

    $conn->commit();

} catch (Exception $e) {
    $conn->rollback();
    $response = json_encode(['credit_amount' => (float)$old_balance, 'error' => $e->getMessage()]);
    $log_text .= "ERROR: " . $e->getMessage() . "\nRESPONSE: $response\n";
    file_put_contents($log_file, $log_text, FILE_APPEND);
    echo $response;
    exit;
}

// ১১. ফাইনাল রেসপন্স (দশমিকের সমস্যা এড়াতে রাউন্ড করা হয়েছে)
$response_data = [
    'credit_amount' => round((float)$new_balance, 2), 
    'balance'       => round((float)$new_balance, 2),
    'status'        => 'success',
    'timestamp'     => round(microtime(true) * 1000)
];

$json_response = json_encode($response_data);
$log_text .= "FINAL RESPONSE: $json_response\n=========================================\n";
file_put_contents($log_file, $log_text, FILE_APPEND);

echo $json_response;
exit;