<?php
session_start();
require_once 'config.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_SESSION['user_id'])) { 
        echo json_encode(["success" => false, "message" => "Please login first."]); 
        exit; 
    }
    
    $userId = $_SESSION['user_id'];
    $period = $_POST['period'] ?? '';
    $selection = $_POST['selection'] ?? '';
    $amount = (float)($_POST['amount'] ?? 0);
    $gameType = 'wingo_1min';

    // 🔥 FIX: Ab minimum bet ₹1 hogi
    if ($amount < 1) { 
        echo json_encode(["success" => false, "message" => "Minimum bet amount is ₹1"]); 
        exit; 
    }

    try {
        global $pdo;
        $pdo->beginTransaction(); 
        
        $stmt = $pdo->prepare("SELECT main_balance FROM wallets WHERE user_id = ? FOR UPDATE");
        $stmt->execute([$userId]);
        $bal = $stmt->fetchColumn();

        if ($bal < $amount) {
            $pdo->rollBack();
            echo json_encode(["success" => false, "message" => "Insufficient balance. Please recharge!"]);
            exit;
        }

        $pdo->prepare("UPDATE wallets SET main_balance = main_balance - ? WHERE user_id = ?")->execute([$amount, $userId]);
        $pdo->prepare("INSERT INTO bets (user_id, game_type, period, selection, amount, status) VALUES (?, ?, ?, ?, ?, 'pending')")->execute([$userId, $gameType, $period, $selection, $amount]);
        
        $pdo->commit(); 
        echo json_encode(["success" => true, "message" => "Bet placed successfully!", "new_balance" => $bal - $amount]);
        
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        echo json_encode(["success" => false, "message" => "System Error. Please try again."]);
    }
}
?>