<?php
session_start();
error_reporting(0); // Hide errors for clean JSON API

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

// Auth Check
if (!isset($_SESSION['user_id'])) {
    if (isset($_POST['action'])) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Please login first!']);
        exit;
    }
    header("Location: ../login.php");
    exit;
}

$user_id = $_SESSION['user_id'];
global $pdo;

// ===================================================================================
// MINES MULTIPLIER MATH ENGINE (Combinatorics)
// ===================================================================================
function nCr($n, $r) {
    if ($r < 0 || $r > $n) return 0;
    if ($r == 0 || $r == $n) return 1;
    if ($r > $n / 2) $r = $n - $r;
    $res = 1;
    for ($i = 1; $i <= $r; $i++) {
        $res = $res * ($n - $i + 1) / $i;
    }
    return $res;
}

function calculate_multiplier($mines, $diamonds) {
    if ($diamonds == 0) return 1.00;
    $house_edge = 0.03; // 3% House Edge
    $total_safe = 25 - $mines;
    
    if ($diamonds > $total_safe) return 0;

    // Probability = (Safe tiles nCr Diamonds) / (25 nCr Diamonds)
    $prob = nCr($total_safe, $diamonds) / nCr(25, $diamonds);
    $mult = (1 - $house_edge) / $prob;
    
    return round($mult, 2);
}

// ===================================================================================
// BACKEND API LOGIC
// ===================================================================================
if (isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    // FETCH HISTORY
    if ($_POST['action'] == 'get_history') {
        try {
            $stmt = $pdo->prepare("SELECT bet_amount, win_amount, multiplier, status, created_at FROM game_history WHERE user_id = ? AND game_name = 'Mines Pro' ORDER BY id DESC LIMIT 20");
            $stmt->execute([$user_id]);
            echo json_encode(['success' => true, 'data' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
        } catch(Exception $e) { echo json_encode(['success' => false]); }
        exit;
    }

    // 1. START GAME
    if ($_POST['action'] == 'start_game') {
        $bet = (float)$_POST['bet_amount'];
        $mines = (int)$_POST['mines'];
        
        if ($mines < 1 || $mines > 24) $mines = 1;
        if ($bet < 10) { echo json_encode(['success' => false, 'message' => 'Min bet ₹10']); exit; }
        
        $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ? FOR UPDATE");
        $stmt->execute([$user_id]);
        $balance = (float)$stmt->fetchColumn();
        
        if ($balance < $bet) { echo json_encode(['success' => false, 'message' => 'Low balance!']); exit; }
        
        // Deduct Bet
        $new_balance = $balance - $bet;
        $pdo->prepare("UPDATE users SET balance = ? WHERE id = ?")->execute([$new_balance, $user_id]);
        
        // --- RIGGING & BOARD GENERATION LOGIC ---
        try {
            $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'mines_win_percent'");
            $stmt->execute();
            $win_percent = (int)$stmt->fetchColumn();
        } catch(Exception $e) { $win_percent = 40; }
        if($win_percent <= 0) $win_percent = 40;

        // Generate Fair Board initially
        $board = array_fill(0, 25, 'safe');
        $mine_positions = (array)array_rand(range(0, 24), $mines);
        if(!is_array($mine_positions)) $mine_positions = [$mine_positions];
        foreach($mine_positions as $pos) $board[$pos] = 'mine';

        // Check if server forces loss
        $is_forced_loss = (rand(1, 100) > $win_percent);
        $crash_step = 26; // Safe default
        
        if ($is_forced_loss) {
            $max_clicks = 25 - $mines;
            if ($mines == 1) $crash_step = rand(2, 6);
            else if ($mines <= 3) $crash_step = rand(1, 4);
            else if ($mines <= 10) $crash_step = rand(1, 2);
            else $crash_step = 1;
            
            if ($crash_step > $max_clicks) $crash_step = $max_clicks;
        }

        $_SESSION['mines_state'] = [
            'active' => true,
            'bet' => $bet,
            'mines' => $mines,
            'board' => $board,
            'clicked' => [],
            'is_forced_loss' => $is_forced_loss,
            'crash_step' => $crash_step
        ];
        
        echo json_encode([
            'success' => true, 
            'balance' => number_format($new_balance, 2, '.', ''),
            'bet_id' => 'MNS' . time() . rand(100, 999),
            'next_mult' => calculate_multiplier($mines, 1)
        ]);
        exit;
    }

    // 2. CLICK TILE
    if ($_POST['action'] == 'click_tile') {
        if(!isset($_SESSION['mines_state']) || !$_SESSION['mines_state']['active']) {
            echo json_encode(['status' => 'error', 'message' => 'No active game']); exit;
        }
        
        $tile_id = (int)$_POST['tile_id'];
        $state = &$_SESSION['mines_state'];
        
        if (in_array($tile_id, $state['clicked'])) {
            echo json_encode(['status' => 'error', 'message' => 'Already clicked']); exit;
        }
        
        $step = count($state['clicked']) + 1;
        
        // =========================================================
        // 🔥 ULTIMATE RIGGING & GOD MODE INTERVENTION 🔥
        // =========================================================
        
        // CASE A: User is DESTINED TO LOSE (Forced Crash)
        if ($state['is_forced_loss'] && $step == $state['crash_step']) {
            if ($state['board'][$tile_id] == 'safe') {
                // User clicked a safe tile, but we move a mine here to kill them
                $mine_idx = array_search('mine', $state['board']);
                $state['board'][$mine_idx] = 'safe';
                $state['board'][$tile_id] = 'mine';
            }
        } 
        // CASE B: User is DESTINED TO WIN (100% Win Rate / God Mode)
        else if (!$state['is_forced_loss']) {
            if ($state['board'][$tile_id] == 'mine') {
                // User accidentally clicked a mine! We MUST save them.
                // Find a safe tile that hasn't been clicked yet
                $empty_safes = [];
                foreach ($state['board'] as $idx => $val) {
                    if ($val == 'safe' && $idx != $tile_id && !in_array($idx, $state['clicked'])) {
                        $empty_safes[] = $idx;
                    }
                }
                
                // Move the mine to the unclicked safe spot
                if (count($empty_safes) > 0) {
                    $new_mine = $empty_safes[array_rand($empty_safes)];
                    $state['board'][$new_mine] = 'mine';
                    $state['board'][$tile_id] = 'safe';
                }
            }
        }

        // =========================================================

        // CHECK TILE RESULT
        if ($state['board'][$tile_id] == 'mine') {
            // CRASHED!
            try {
                $pdo->prepare("INSERT INTO game_history (user_id, game_name, bet_amount, win_amount, multiplier, status) VALUES (?, 'Mines Pro', ?, 0, 0, 'loss')")->execute([$user_id, $state['bet']]);
            } catch(Exception $e) {}
            
            $final_board = $state['board'];
            unset($_SESSION['mines_state']);
            
            echo json_encode(['status' => 'mine', 'board' => $final_board]);
            exit;
        } else {
            // SAFE!
            $state['clicked'][] = $tile_id;
            $current_mult = calculate_multiplier($state['mines'], $step);
            $next_mult = calculate_multiplier($state['mines'], $step + 1);
            
            $max_safe = 25 - $state['mines'];
            $is_cleared = ($step == $max_safe);

            echo json_encode([
                'status' => 'safe', 
                'current_mult' => $current_mult,
                'next_mult' => $next_mult,
                'cleared' => $is_cleared,
                'win_amount' => $state['bet'] * $current_mult
            ]);
            exit;
        }
    }

    // 3. CASHOUT
    if ($_POST['action'] == 'cash_out') {
        if (!isset($_SESSION['mines_state']) || !$_SESSION['mines_state']['active']) {
            echo json_encode(['success' => false]); exit;
        }
        
        $state = $_SESSION['mines_state'];
        $step = count($state['clicked']);
        
        if ($step == 0) { echo json_encode(['success' => false, 'message' => 'Click a tile first!']); exit; }
        
        $multiplier = calculate_multiplier($state['mines'], $step);
        $win_amount = $state['bet'] * $multiplier;
        
        $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $balance = (float)$stmt->fetchColumn();
        
        $new_balance = $balance + $win_amount;
        $pdo->prepare("UPDATE users SET balance = ? WHERE id = ?")->execute([$new_balance, $user_id]);
        
        try {
            $pdo->prepare("INSERT INTO game_history (user_id, game_name, bet_amount, win_amount, multiplier, status) VALUES (?, 'Mines Pro', ?, ?, ?, 'win')")
                ->execute([$user_id, $state['bet'], $win_amount, $multiplier]);
        } catch(Exception $e) { }
            
        $final_board = $state['board'];
        unset($_SESSION['mines_state']);
        
        echo json_encode([
            'success' => true, 
            'win_amount' => $win_amount, 
            'balance' => number_format($new_balance, 2, '.', ''),
            'board' => $final_board,
            'multiplier' => $multiplier
        ]);
        exit;
    }
}

$stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user_balance = number_format((float)$stmt->fetchColumn(), 2, '.', '');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Boom Mines - Pro Edition</title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.6.0/dist/confetti.browser.min.js"></script>

    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@500;700;800;900&family=Montserrat:wght@800;900&display=swap');

        :root {
            --bg-body: #000;
            --bg-game: #005bcc; 
            --bg-panel: #004bb0; 
            --tile-bg: #1157ba;
            --tile-shadow: #0b4291;
            --tile-circle: #2572db;
            --tile-safe: #082d63;
            --tile-safe-shadow: #051d40;
            --tile-mine: #ff3b30;
            --color-green: #6bba14;
            --color-green-dark: #4d8c0c;
            --color-yellow: #ffc107;
            --text-light: #a9c6f2;
        }

        * { box-sizing: border-box; margin: 0; padding: 0; user-select: none; -webkit-tap-highlight-color: transparent;}
        body { background-color: var(--bg-body); font-family: 'Inter', sans-serif; display: flex; justify-content: center; height: 100vh; overflow: hidden; color: #fff;}
        
        .game-wrapper { width: 100%; max-width: 480px; height: 100%; display: flex; flex-direction: column; background: var(--bg-game); position: relative; box-shadow: 0 0 50px rgba(0,0,0,0.9); overflow: hidden;}

        .bg-watermark { position: absolute; top: 30%; left: -10%; font-size: 300px; color: rgba(255,255,255,0.03); transform: rotate(-20deg); pointer-events: none; z-index: 0;}

        /* LOADER */
        #gameLoader { position: absolute; inset: 0; background: #000; z-index: 9999; display: flex; flex-direction: column; align-items: center; justify-content: center; transition: opacity 0.5s;}
        .loader-icon { width: 120px; height: 120px; margin-bottom: 20px; animation: pulse 1s infinite alternate; }
        .loader-text { font-family: 'Montserrat', sans-serif; font-size: 38px; font-weight: 900; color: #007bff; letter-spacing: 2px; text-shadow: 0 0 15px rgba(0,123,255,0.6);}
        .loader-bar { width: 50%; height: 6px; background: #222; border-radius: 10px; margin-top: 20px; overflow: hidden; position: relative;}
        .loader-fill { height: 100%; width: 0%; background: #007bff; transition: width 0.1s;}
        .loader-percent { font-size: 12px; color: #666; margin-top: 5px; font-weight: 800;}
        @keyframes pulse { 0% { transform: scale(1); } 100% { transform: scale(1.1); } }

        /* HEADER */
        .header { display: flex; justify-content: space-between; align-items: center; padding: 12px 15px; background: rgba(0, 75, 176, 0.9); z-index: 10; border-bottom: 1px solid rgba(255,255,255,0.1); box-shadow: 0 4px 10px rgba(0,0,0,0.2);}
        .brand { display: flex; align-items: center; gap: 10px; font-family: 'Montserrat', sans-serif; font-size: 22px; font-weight: 900;}
        .brand a { color: #fff; text-decoration: none; }
        .how-to { background: var(--color-yellow); color: #000; font-size: 11px; font-weight: 800; padding: 4px 10px; border-radius: 20px; box-shadow: 0 2px 0 #cc9a06;}
        
        .header-right { display: flex; align-items: center; gap: 12px; }
        .bal-text { font-size: 15px; font-weight: 800; }
        .menu-btn { width: 35px; height: 35px; background: #003785; border-radius: 8px; display: flex; justify-content: center; align-items: center; color: #fff; font-size: 16px; cursor: pointer; box-shadow: 0 2px 0 #002052;}
        .menu-btn:active { transform: translateY(2px); box-shadow: none;}

        /* INFO BAR */
        .info-bar { display: flex; gap: 10px; padding: 15px; z-index: 1;}
        .game-id { flex: 1; background: #004bb0; color: var(--text-light); border-radius: 20px; font-size: 12px; font-weight: 700; padding: 8px 15px; display: flex; justify-content: space-between; align-items: center;}
        .next-win { flex: 0.8; background: var(--color-yellow); color: #000; border-radius: 20px; font-size: 13px; font-weight: 800; padding: 8px 15px; text-align: center; box-shadow: 0 3px 0 #cc9a06;}

        /* GRID AREA */
        .grid-wrapper { flex: 1; display: flex; justify-content: center; align-items: center; padding: 0 15px 15px; z-index: 1;}
        .mines-grid { display: grid; grid-template-columns: repeat(5, 1fr); gap: 8px; width: 100%; max-width: 380px; background: #004bb0; padding: 10px; border-radius: 12px; box-shadow: inset 0 0 20px rgba(0,0,0,0.2);}
        
        .tile { background: var(--tile-bg); border-radius: 8px; box-shadow: 0 4px 0 var(--tile-shadow); position: relative; aspect-ratio: 1; cursor: pointer; transition: transform 0.1s, background 0.3s;}
        .tile::after { content: ''; position: absolute; width: 35%; height: 35%; background: var(--tile-circle); border-radius: 50%; top: 50%; left: 50%; transform: translate(-50%, -50%); transition: 0.2s;}
        
        .tile:active:not(.locked) { transform: translateY(4px); box-shadow: 0 0 0 var(--tile-shadow); }
        .tile.locked { cursor: default; pointer-events: none; }
        
        .tile.safe { background: var(--tile-safe); box-shadow: 0 4px 0 var(--tile-safe-shadow); animation: popIn 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275); }
        .tile.safe::after { display: none; }
        .tile.safe svg { position: absolute; width: 70%; height: 70%; top: 15%; left: 15%; filter: drop-shadow(0 4px 4px rgba(0,0,0,0.5));}
        
        .tile.mine { background: var(--tile-mine); box-shadow: 0 4px 0 #cc2f26; animation: shake 0.4s; }
        .tile.mine::after { display: none; }
        .tile.mine svg { position: absolute; width: 80%; height: 80%; top: 10%; left: 10%; filter: drop-shadow(0 4px 4px rgba(0,0,0,0.5));}
        
        .tile.revealed-mine { background: #082d63; box-shadow: 0 4px 0 #051d40; opacity: 0.6;}
        .tile.revealed-mine::after { display: none; }
        .tile.revealed-mine svg { position: absolute; width: 70%; height: 70%; top: 15%; left: 15%;}

        @keyframes popIn { 0% { transform: scale(0.5); } 100% { transform: scale(1); } }
        @keyframes shake { 0%, 100% { transform: translateX(0); } 25% { transform: translateX(-5px); } 75% { transform: translateX(5px); } }

        /* CONTROLS */
        .controls { background: var(--bg-panel); padding: 15px; border-top-left-radius: 20px; border-top-right-radius: 20px; box-shadow: 0 -10px 20px rgba(0,0,0,0.3); z-index: 10;}
        
        .sub-controls { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;}
        .btn-random { background: transparent; color: var(--text-light); border: 1px solid #1157ba; padding: 6px 15px; border-radius: 20px; font-size: 12px; font-weight: 700;}
        
        .auto-toggle { display: flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 700; color: #fff;}
        .switch { width: 40px; height: 20px; background: #1157ba; border-radius: 10px; position: relative; transition: 0.3s; box-shadow: inset 0 2px 5px rgba(0,0,0,0.3);}
        .switch::after { content:''; position: absolute; left: 2px; top: 2px; width: 16px; height: 16px; background: #fff; border-radius: 50%; transition: 0.3s;}
        .switch.on { background: var(--color-green); }
        .switch.on::after { transform: translateX(20px); }

        .mines-select { background: #1157ba; color: #fff; border: none; padding: 6px 15px; border-radius: 20px; font-size: 13px; font-weight: 800; outline: none; appearance: none; text-align: center; box-shadow: 0 3px 0 #0b4291; cursor: pointer;}

        .bet-row { display: flex; gap: 10px; align-items: stretch; height: 50px;}
        
        .input-group-custom { flex: 1.2; background: #003785; border-radius: 25px; display: flex; align-items: center; padding: 4px; box-shadow: inset 0 2px 5px rgba(0,0,0,0.3);}
        .bet-input-box { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; line-height: 1.1;}
        .bet-input-box label { font-size: 10px; color: var(--text-light); font-weight: 700;}
        .bet-input { background: transparent; border: none; color: #fff; font-family: 'Inter', sans-serif; font-size: 15px; font-weight: 900; text-align: center; width: 100%; outline: none;}
        
        .bet-btn-sm { background: #1157ba; color: #fff; border: none; width: 35px; height: 35px; border-radius: 50%; font-weight: 900; font-size: 18px; display: flex; align-items: center; justify-content: center; box-shadow: 0 2px 0 #0b4291;}
        .bet-btn-sm:active { transform: translateY(2px); box-shadow: none;}
        
        .btn-auto-spin { background: #1157ba; border: none; width: 45px; height: 45px; border-radius: 50%; color: #fff; font-size: 18px; display: flex; justify-content: center; align-items: center; box-shadow: 0 3px 0 #0b4291;}

        .btn-play { flex: 1.5; background: var(--color-green); color: #fff; border: none; border-radius: 25px; font-family: 'Inter', sans-serif; font-size: 18px; font-weight: 900; display: flex; align-items: center; justify-content: center; gap: 10px; box-shadow: 0 5px 0 var(--color-green-dark); transition: 0.1s;}
        .btn-play:active { transform: translateY(5px); box-shadow: 0 0 0 var(--color-green-dark); }
        .btn-cashout { flex: 1.5; background: var(--color-yellow); color: #000; border: none; border-radius: 25px; font-family: 'Inter', sans-serif; font-size: 16px; font-weight: 900; display: none; flex-direction: column; align-items: center; justify-content: center; line-height: 1.1; box-shadow: 0 5px 0 #cc9a06; transition: 0.1s;}
        .btn-cashout:active { transform: translateY(5px); box-shadow: none;}
        .btn-disabled { background: #1157ba !important; color: #777 !important; box-shadow: 0 5px 0 #0b4291 !important; pointer-events: none;}

        /* MENUS & TOASTS */
        .menu-modal { display: none; position: absolute; top: 60px; right: 15px; width: 220px; background: #1a1e24; border-radius: 12px; z-index: 200; box-shadow: 0 10px 30px rgba(0,0,0,0.8); overflow: hidden; }
        .menu-item { display: flex; align-items: center; gap: 12px; padding: 15px 20px; color: #c9d1d9; font-size: 14px; font-weight: 700; cursor: pointer; border-bottom: 1px solid #2b3139; }
        .menu-item:hover { background: #2b3139; color: #fff;}
        
        .history-modal { display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.85); z-index: 300; flex-direction: column; align-items: center; justify-content: flex-end; }
        .history-content { width: 100%; height: 75%; background: #004bb0; border-top-left-radius: 20px; border-top-right-radius: 20px; padding: 20px; display: flex; flex-direction: column; animation: slideUp 0.3s ease-out; }
        @keyframes slideUp { from { transform: translateY(100%); } to { transform: translateY(0); } }
        .close-history { color: #fff; font-size: 24px; cursor: pointer; float: right; margin-bottom: 15px;}
        
        .toast-msg { position: absolute; top: 30%; left: 50%; transform: translate(-50%, -50%) scale(0); background: rgba(0,0,0,0.9); padding: 15px 30px; border-radius: 12px; font-size: 28px; font-weight: 900; color: #fff; border: 3px solid; z-index: 100; box-shadow: 0 10px 30px rgba(0,0,0,0.8); transition: 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275); text-transform: uppercase; white-space: nowrap;}
        .toast-msg.show { transform: translate(-50%, -50%) scale(1); }
    </style>
</head>
<body>

    <svg style="display: none;">
        <symbol id="icon-star" viewBox="0 0 24 24">
            <path fill="#facc15" d="M12 2L15.09 8.26L22 9.27L17 14.14L18.18 21.02L12 17.77L5.82 21.02L7 14.14L2 9.27L8.91 8.26L12 2Z"/>
        </symbol>
        <symbol id="icon-bomb" viewBox="0 0 24 24">
            <path fill="#111" d="M19.07 4.93C18.68 4.54 18.05 4.54 17.66 4.93L15.54 7.05C14.5 6.39 13.3 6 12 6C8.69 6 6 8.69 6 12C6 15.31 8.69 18 12 18C15.31 18 18 15.31 18 12C18 10.7 17.61 9.5 16.95 8.46L19.07 6.34C19.46 5.95 19.46 5.32 19.07 4.93M12 16C9.79 16 8 14.21 8 12C8 9.79 9.79 8 12 8C14.21 8 16 9.79 16 12C16 14.21 14.21 16 12 16M21 10.5V13.5H23V10.5H21M10.5 1H13.5V3H10.5V1M3 10.5H1V13.5H3V10.5Z"/>
            <circle cx="12" cy="12" r="4" fill="#333"/>
        </symbol>
    </svg>

    <audio id="s-click" src="https://assets.mixkit.co/active_storage/sfx/2568/2568-preview.mp3"></audio>
    <audio id="s-bomb" src="https://assets.mixkit.co/active_storage/sfx/1468/1468-preview.mp3"></audio>
    <audio id="s-win" src="https://assets.mixkit.co/active_storage/sfx/2013/2013-preview.mp3"></audio>

    <div class="game-wrapper">
        <i class="fas fa-star bg-watermark"></i>
        
        <div id="gameLoader">
            <svg class="loader-icon" viewBox="0 0 24 24"><use href="#icon-bomb"></use></svg>
            <div class="loader-text">BOOM MINES</div>
            <div class="loader-bar"><div class="loader-fill" id="lBar"></div></div>
            <div class="loader-percent" id="lPct">0%</div>
        </div>

        <div class="header">
            <div class="brand">
                <a href="../index.php"><i class="fas fa-arrow-left"></i></a>
                <span>MINES</span>
                <div class="how-to"><i class="fas fa-question-circle"></i> How to Play?</div>
            </div>
            <div class="header-right">
                <div class="bal-text"><span id="uiBalance"><?= $user_balance ?></span> INR</div>
                <div class="menu-btn" onclick="Game.toggleMenu()"><i class="fas fa-bars"></i></div>
            </div>
        </div>

        <div class="menu-modal" id="menuModal">
            <div class="menu-item" onclick="Game.toggleSound()">
                <i class="fas fa-volume-up"></i> Sound <div class="switch on" id="soundToggle" style="margin-left:auto;"></div>
            </div>
            <div class="menu-item" onclick="Game.openHistory()"><i class="fas fa-history"></i> Bets History</div>
            <div class="menu-item"><i class="fas fa-book"></i> Game Rules</div>
        </div>

        <div class="history-modal" id="historyModal">
            <div class="history-content">
                <i class="fas fa-times close-history" onclick="Game.closeHistory()"></i>
                <h4 class="text-white fw-bold mb-3"><i class="fas fa-history text-warning"></i> My Bets</h4>
                <div id="historyList" style="overflow-y:auto; flex:1;"></div>
            </div>
        </div>

        <div class="info-bar">
            <div class="game-id">Game ID: <span id="uiBetId">Waiting...</span> <i class="fas fa-chevron-down ms-1"></i></div>
            <div class="next-win" id="uiNextWin">Next: 0.00 INR</div>
        </div>

        <div class="grid-wrapper">
            <div class="mines-grid" id="minesGrid"></div>
            <div class="toast-msg" id="toastBox">TEXT</div>
        </div>

        <div class="controls">
            <div class="sub-controls">
                <button class="btn-random" onclick="Game.pickRandom()">RANDOM</button>
                <div class="auto-toggle">
                    <div class="switch" id="autoSwitch" onclick="this.classList.toggle('on')"></div> Auto Game
                </div>
                <select class="mines-select" id="uiMines" onchange="Game.updateNextMultPreview()">
                    <?php foreach([1,2,3,4,5,10,15,20] as $m): ?>
                        <option value="<?= $m ?>">Mines: <?= $m ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="bet-row">
                <div class="input-group-custom">
                    <button class="bet-btn-sm" onclick="Game.adjustBet(-10)">-</button>
                    <div class="bet-input-box">
                        <label>Bet</label>
                        <input type="number" id="uiBetInput" class="bet-input" value="10.00" readonly>
                    </div>
                    <button class="bet-btn-sm" onclick="Game.adjustBet(10)">+</button>
                </div>
                
                <button class="btn-auto-spin"><i class="fas fa-sync-alt"></i></button>
                
                <button class="btn-play" id="btnStart" onclick="Game.startGame()"><i class="fas fa-play"></i> BET</button>
                <button class="btn-cashout" id="btnCashout" onclick="Game.cashOut()">CASH OUT<br><small id="uiCashAmt">₹0.00</small></button>
            </div>
        </div>
    </div>

    <script>
        const Game = (function() {
            let state = { status: 'idle', bet: 10, mines: 1, step: 0 };
            let soundOn = true;

            const els = {
                grid: document.getElementById('minesGrid'),
                btnStart: document.getElementById('btnStart'),
                btnCashout: document.getElementById('btnCashout'),
                uiBet: document.getElementById('uiBetInput'),
                uiBal: document.getElementById('uiBalance'),
                uiNext: document.getElementById('uiNextWin'),
                uiCash: document.getElementById('uiCashAmt'),
                uiId: document.getElementById('uiBetId'),
                uiMines: document.getElementById('uiMines'),
                toast: document.getElementById('toastBox'),
                menu: document.getElementById('menuModal'),
                historyMod: document.getElementById('historyModal'),
                historyList: document.getElementById('historyList')
            };

            function nCr(n, r) {
                if (r < 0 || r > n) return 0;
                if (r === 0 || r === n) return 1;
                if (r > n / 2) r = n - r;
                let res = 1;
                for (let i = 1; i <= r; i++) { res = res * (n - i + 1) / i; }
                return res;
            }
            function getMult(mines, diamonds) {
                if(diamonds === 0) return 1.00;
                let total_safe = 25 - mines;
                if(diamonds > total_safe) return 0;
                let prob = nCr(total_safe, diamonds) / nCr(25, diamonds);
                return (0.97 / prob).toFixed(2);
            }

            function init() {
                let p = 0;
                let intv = setInterval(() => {
                    p += Math.random() * 12;
                    if(p > 100) p = 100;
                    document.getElementById('lBar').style.width = p + '%';
                    document.getElementById('lPct').innerText = Math.floor(p) + '%';
                    if(p === 100) {
                        clearInterval(intv);
                        setTimeout(() => document.getElementById('gameLoader').style.opacity = '0', 300);
                        setTimeout(() => document.getElementById('gameLoader').style.display = 'none', 800);
                    }
                }, 50);

                buildGrid();
                updateNextMultPreview();
            }

            function buildGrid() {
                els.grid.innerHTML = '';
                for(let i=0; i<25; i++) {
                    let t = document.createElement('div');
                    t.className = 'tile locked';
                    t.id = 'tile-' + i;
                    t.onclick = () => clickTile(i);
                    els.grid.appendChild(t);
                }
            }

            function playSnd(id) { if(soundOn) { let a = document.getElementById(id); if(a) { a.currentTime = 0; a.play().catch(()=>{}); } } }
            
            function toggleMenu() { els.menu.style.display = els.menu.style.display === 'block' ? 'none' : 'block'; }
            function toggleSound() { soundOn = !soundOn; document.getElementById('soundToggle').className = soundOn ? 'switch on' : 'switch'; }
            window.onclick = (e) => { if (!e.target.closest('.menu-btn') && !e.target.closest('.menu-modal')) els.menu.style.display = 'none'; }

            function adjustBet(v) {
                if(state.status !== 'idle') return;
                state.bet += v;
                if(state.bet < 10) state.bet = 10;
                els.uiBet.value = state.bet.toFixed(2);
                updateNextMultPreview();
            }

            function updateNextMultPreview() {
                if(state.status === 'idle') {
                    let m = parseInt(els.uiMines.value);
                    let mult = getMult(m, 1);
                    els.uiNext.innerText = `Next: ${(state.bet * mult).toFixed(2)} INR`;
                }
            }

            function showToast(txt, col) {
                els.toast.innerText = txt; els.toast.style.borderColor = col; els.toast.style.color = col;
                els.toast.classList.add('show');
            }

            async function startGame() {
                if(state.status !== 'idle') return;
                state.bet = parseFloat(els.uiBet.value);
                state.mines = parseInt(els.uiMines.value);
                
                els.btnStart.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
                els.btnStart.disabled = true;

                let fd = new FormData();
                fd.append('action', 'start_game'); fd.append('bet_amount', state.bet); fd.append('mines', state.mines);

                try {
                    let res = await fetch('', { method: 'POST', body: fd });
                    let data = await res.json();
                    if(data.success) {
                        state.status = 'playing'; state.step = 0;
                        els.uiBal.innerText = data.balance;
                        els.uiId.innerText = data.bet_id;
                        els.uiNext.innerText = `Next: ${(state.bet * data.next_mult).toFixed(2)} INR`;
                        
                        els.toast.classList.remove('show');
                        buildGrid(); 
                        document.querySelectorAll('.tile').forEach(t => t.classList.remove('locked'));

                        els.btnStart.style.display = 'none';
                        els.btnCashout.style.display = 'flex';
                        els.btnCashout.disabled = true; 
                        els.uiCash.innerText = '₹0.00';
                        els.uiMines.disabled = true;
                    } else { alert(data.message); }
                } catch(e) {}
                els.btnStart.innerHTML = '<i class="fas fa-play"></i> BET';
                els.btnStart.disabled = false;
            }

            async function clickTile(id) {
                if(state.status !== 'playing') return;
                let tile = document.getElementById('tile-'+id);
                if(tile.classList.contains('safe') || tile.classList.contains('locked')) return;
                
                document.querySelectorAll('.tile').forEach(t => t.classList.add('locked'));
                els.btnCashout.disabled = true;
                
                let fd = new FormData(); fd.append('action', 'click_tile'); fd.append('tile_id', id);
                
                try {
                    let res = await fetch('', { method: 'POST', body: fd });
                    let data = await res.json();

                    if(data.status === 'safe') {
                        state.step++;
                        tile.classList.add('safe');
                        tile.innerHTML = '<svg viewBox="0 0 24 24"><use href="#icon-star"></use></svg>';
                        playSnd('s-click');
                        
                        els.uiNext.innerText = `Next: ${(state.bet * data.next_mult).toFixed(2)} INR`;
                        els.uiCash.innerText = `₹${parseFloat(data.win_amount).toFixed(2)}`;
                        
                        if(data.cleared) {
                            setTimeout(() => cashOut(), 500);
                        } else {
                            document.querySelectorAll('.tile:not(.safe)').forEach(t => t.classList.remove('locked'));
                            els.btnCashout.disabled = false;
                        }
                    } else if(data.status === 'mine') {
                        state.status = 'crashed';
                        tile.classList.add('mine');
                        tile.innerHTML = '<svg viewBox="0 0 24 24"><use href="#icon-bomb"></use></svg>';
                        playSnd('s-bomb');
                        
                        revealBoard(data.board, id);
                        showToast('CRASHED!', 'var(--color-red)');
                        setTimeout(() => resetGame(), 2500);
                    }
                } catch(e) { document.querySelectorAll('.tile:not(.safe)').forEach(t => t.classList.remove('locked')); }
            }

            function revealBoard(board, ignoreId = -1) {
                board.forEach((val, idx) => {
                    if(idx === ignoreId) return;
                    let t = document.getElementById('tile-'+idx);
                    if(!t.classList.contains('safe')) {
                        if(val === 'mine') {
                            t.classList.add('revealed-mine');
                            t.innerHTML = '<svg viewBox="0 0 24 24" style="opacity:0.5"><use href="#icon-bomb"></use></svg>';
                        } else {
                            t.style.opacity = '0.5'; 
                        }
                    }
                });
            }

            function pickRandom() {
                if(state.status !== 'playing') return;
                let unclicked = [];
                document.querySelectorAll('.tile:not(.safe)').forEach(t => {
                    let id = parseInt(t.id.replace('tile-',''));
                    unclicked.push(id);
                });
                if(unclicked.length > 0) {
                    let rnd = unclicked[Math.floor(Math.random() * unclicked.length)];
                    clickTile(rnd);
                }
            }

            async function cashOut() {
                if(state.status !== 'playing' || state.step === 0) return;
                els.btnCashout.disabled = true;
                els.btnCashout.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
                document.querySelectorAll('.tile').forEach(t => t.classList.add('locked'));

                let fd = new FormData(); fd.append('action', 'cash_out');
                
                try {
                    let res = await fetch('', { method: 'POST', body: fd });
                    let data = await res.json();
                    
                    if(data.success) {
                        playSnd('s-win');
                        els.uiBal.innerText = data.balance;
                        revealBoard(data.board);
                        
                        showToast(`WIN ₹${data.win_amount.toFixed(2)}`, 'var(--color-green)');
                        confetti({ particleCount: 150, spread: 80, origin: { y: 0.5 }, zIndex: 9999 });
                        
                        setTimeout(() => resetGame(), 3000);
                    }
                } catch(e) {}
            }

            function resetGame() {
                state.status = 'idle';
                els.btnCashout.style.display = 'none';
                els.btnCashout.innerHTML = `CASH OUT<br><small id="uiCashAmt">₹0.00</small>`;
                els.uiCash = document.getElementById('uiCashAmt');
                
                els.btnStart.style.display = 'flex';
                els.btnStart.disabled = false;
                els.uiMines.disabled = false;
                
                els.toast.classList.remove('show');
                buildGrid();
                updateNextMultPreview();
            }

            function openHistory() {
                els.menu.style.display = 'none'; els.historyMod.style.display = 'flex';
                els.historyList.innerHTML = '<div class="text-center text-white mt-5"><i class="fas fa-spinner fa-spin fs-2"></i></div>';
                
                let fd = new FormData(); fd.append('action', 'get_history');
                fetch('', { method: 'POST', body: fd }).then(r=>r.json()).then(data => {
                    if(data.success && data.data.length > 0) {
                        let html = '';
                        data.data.forEach(h => {
                            let type = h.status === 'win' ? 'text-success' : 'text-danger';
                            let sign = h.status === 'win' ? '+' : '-';
                            html += `
                            <div style="background:#003785; padding:10px; border-radius:8px; margin-bottom:10px; display:flex; justify-content:space-between; align-items:center;">
                                <div><div style="font-size:11px; color:#a9c6f2;">${new Date(h.created_at).toLocaleString()}</div><div class="fw-bold text-white">Bet: ₹${parseFloat(h.bet_amount).toFixed(2)}</div></div>
                                <div class="text-end"><div style="font-size:12px; background:#002052; padding:2px 6px; border-radius:4px; color:#fff; display:inline-block; margin-bottom:3px;">${parseFloat(h.multiplier).toFixed(2)}x</div><div class="fw-bold ${type}">${sign}₹${parseFloat(h.win_amount).toFixed(2)}</div></div>
                            </div>`;
                        });
                        els.historyList.innerHTML = html;
                    } else els.historyList.innerHTML = '<div class="text-center text-white mt-5">No history found.</div>';
                });
            }
            function closeHistory() { els.historyMod.style.display = 'none'; }

            return { init, adjustBet, startGame, clickTile, cashOut, pickRandom, updateNextMultPreview, toggleMenu, toggleSound, openHistory, closeHistory };
        })();

        document.addEventListener('DOMContentLoaded', Game.init);
    </script>
</body>
</html>