<?php
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');

require_once __DIR__ . '/../config.php';

// Ensure user_bets table exists
if ($db_connected && $conn) {
    @$conn->query("CREATE TABLE IF NOT EXISTS user_bets (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id BIGINT UNSIGNED NOT NULL DEFAULT 1,
        match_id INT NOT NULL,
        match_name VARCHAR(255) NOT NULL,
        market_type VARCHAR(50) NOT NULL,
        runner_name VARCHAR(255) NOT NULL,
        bet_type ENUM('back','lay') NOT NULL DEFAULT 'back',
        odds DECIMAL(10,2) NOT NULL,
        stake DECIMAL(15,2) NOT NULL,
        potential_profit DECIMAL(15,2) NOT NULL,
        status ENUM('open','won','lost','cancelled') NOT NULL DEFAULT 'open',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
}

$input = json_decode(file_get_contents('php://input'), true) ?? $_POST;

$match_id = (int)($input['match_id'] ?? 0);
$match_name = sanitize($input['match_name'] ?? 'Cricket Match');
$market_type = sanitize($input['market_type'] ?? 'match_odds');
$runner_name = sanitize($input['runner_name'] ?? '');
$bet_type = strtolower($input['bet_type'] ?? 'back') === 'lay' ? 'lay' : 'back';
$odds = (float)($input['odds'] ?? 1.50);
$stake = (float)($input['stake'] ?? 0);

if ($stake <= 0) {
    echo json_encode(['success' => false, 'error' => 'Please enter a valid stake amount.']);
    exit;
}

if (empty($runner_name)) {
    echo json_encode(['success' => false, 'error' => 'Please select a runner or odds.']);
    exit;
}

// Calculate potential profit
$potential_profit = $bet_type === 'back' ? round($stake * ($odds - 1), 2) : $stake;
$liability = $bet_type === 'lay' ? round($stake * ($odds - 1), 2) : $stake;

$user_id = $_SESSION['user_id'] ?? 10;
$current_balance = 15000.00;
$exposure = $_SESSION['exposure'] ?? 0.00;

if ($db_connected && $conn && isset($_SESSION['user_id'])) {
    $res = $conn->query("SELECT id, balance, wallet_balance FROM users WHERE id=" . (int)$_SESSION['user_id']);
    if ($res && $u = $res->fetch_assoc()) {
        $current_balance = (float)(!empty($u['wallet_balance']) ? $u['wallet_balance'] : $u['balance']);
    }
} else {
    // If demo session
    if (!isset($_SESSION['demo_balance'])) {
        $_SESSION['demo_balance'] = 15000.00;
    }
    $current_balance = (float)$_SESSION['demo_balance'];
}

if ($liability > $current_balance) {
    echo json_encode(['success' => false, 'error' => 'Insufficient Balance! Available: ' . formatINR($current_balance)]);
    exit;
}

$new_balance = $current_balance - $liability;
$new_exposure = $exposure + $liability;
$_SESSION['exposure'] = $new_exposure;

// Update DB or session
if ($db_connected && $conn && isset($_SESSION['user_id'])) {
    $conn->query("UPDATE users SET wallet_balance = $new_balance, balance = $new_balance WHERE id=" . (int)$_SESSION['user_id']);
    
    $stmt = $conn->prepare("INSERT INTO user_bets (user_id, match_id, match_name, market_type, runner_name, bet_type, odds, stake, potential_profit) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
    if ($stmt) {
        $stmt->bind_param('iissssddd', $_SESSION['user_id'], $match_id, $match_name, $market_type, $runner_name, $bet_type, $odds, $stake, $potential_profit);
        $stmt->execute();
        $bet_id = $conn->insert_id;
    } else {
        $bet_id = rand(1000, 9999);
    }
} else {
    $_SESSION['demo_balance'] = $new_balance;
    $bet_id = rand(1000, 9999);
}

// Store in session bets list
if (!isset($_SESSION['open_bets'])) {
    $_SESSION['open_bets'] = [];
}

$new_bet = [
    'id' => $bet_id,
    'match_name' => $match_name,
    'runner_name' => $runner_name,
    'market_type' => $market_type,
    'bet_type' => $bet_type,
    'odds' => $odds,
    'stake' => $stake,
    'profit' => $potential_profit,
    'time' => date('H:i:s')
];

array_unshift($_SESSION['open_bets'], $new_bet);

echo json_encode([
    'success' => true,
    'message' => 'Bet placed successfully!',
    'new_balance' => $new_balance,
    'formatted_balance' => formatINR($new_balance),
    'exposure' => $new_exposure,
    'formatted_exposure' => formatINR($new_exposure),
    'bet' => $new_bet,
    'open_bets' => array_slice($_SESSION['open_bets'], 0, 10)
]);
