<?php
include "../../conn.php";
include "../../functions2.php";

try {
    // Extract POST data
    $data = json_decode(file_get_contents('php://input'), true);

    $game_uid = $data['game_uid'];
    $game_provider = $data['game_provider'];
    $game_name = $data['game_name'];
    $game_type = $data['game_type'];
    $game_round = $data['game_round'];
    $bet_amount = $data['bet_amount'];
    $serial_number = $data['serial_number'];
    $win_amount = $data['win_amount'];
    $member_account = $data['member_account'];
    $currency_code = $data['currency_code'];
    $timestamp = $data['timestamp'];
    $token = $data['token'];

    // Insert into bet_check table
    $stmt = $conn->prepare("INSERT INTO bet_check (game_uid, game_provider, game_name, game_type, game_round, bet_amount, serial_number, win_amount, member_account, currency_code, timestamp, token) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    if (!$stmt) {
        error_log("Insert prepare failed: " . $conn->error);
        return sendResponse(0, "Insert prepare failed", $currency_code, 0);
    }
    $stmt->bind_param("sssssdssdsss", $game_uid, $game_provider, $game_name, $game_type, $game_round, $bet_amount, $serial_number, $win_amount, $member_account, $currency_code, $timestamp, $token);
    $stmt->execute();
    $stmt->close();

    // Fetch user's balance
    $stmt = $conn->prepare("SELECT motta FROM shonu_kaichila WHERE balakedara = ?");
    if (!$stmt) {
        error_log("Select prepare failed: " . $conn->error);
        return sendResponse(0, "Select prepare failed", $currency_code, 0);
    }

    $stmt->bind_param("s", $member_account);
    $stmt->execute();
    $stmt->bind_result($motta);
    $stmt->fetch();
    $stmt->close();

    if (!empty($motta)) {
        $username = $member_account;
        $balance = $motta;

        // Log original values
        error_log("Original Balance: $balance, Bet: $bet_amount, Win: $win_amount");

        // Validate numeric values
        if (!is_numeric($balance) || !is_numeric($bet_amount) || !is_numeric($win_amount)) {
            return sendResponse(0, "Invalid numeric value", $currency_code, 0);
        }

        // Check if user has enough balance
        if ($balance < $bet_amount) {
            return sendResponse(0, "Insufficient balance", $currency_code, $balance);
        }

        // Calculate final balance
        $finalAmount = $balance - $bet_amount + $win_amount;
        error_log("Final calculated balance: $finalAmount");

        // Update the user's balance
        $updateBalanceQuery = "UPDATE shonu_kaichila SET motta = ? WHERE balakedara = ?";
        $stmt = $conn->prepare($updateBalanceQuery);

        if (!$stmt) {
            error_log("Update prepare failed: " . $conn->error);
            return sendResponse(0, "Prepare failed: " . $conn->error, $currency_code, 0);
        }

        error_log("Attempting to update balance. User: $username | New Balance: $finalAmount");

        $stmt->bind_param("ds", $finalAmount, $username);
        $stmt->execute();

        if ($stmt->affected_rows === 0) {
            error_log("No rows updated. Possibly user not found or balance unchanged.");
            return sendResponse(0, "Balance not updating", $currency_code, $balance);
        }

        $stmt->close();

        // Return success response
        return sendResponse(0, "success", $currency_code, $finalAmount);
    }

    // If user not found
    return sendResponse(0, "User not found or token invalid", $currency_code, 0);

} catch (Exception $e) {
    error_log("Launch game error: " . $e->getMessage());
    return sendResponse(0, "Server Error: " . $e->getMessage(), "INR", 0);
}

// JSON response function
function sendResponse($errorCode, $message, $currency, $creditAmount) {
    header('Content-Type: application/json');
    echo json_encode([
        'errorCode' => $errorCode,
        'message' => $message,
        'currency' => $currency,
        'credit_amount' => $creditAmount
    ]);
    exit;
}
?>
