<?php
require_once __DIR__ . '/auth.php';

if (!isset($pdo)) {
    die("Database connection failed. Check auth.php.");
}

// ── CONFIGURATION & MODE SETUP ──────────────────────────────────────────────
$mode = $_GET['mode'] ?? '30s';
if (!in_array($mode, ['30s', '1min', '3min', '5min'])) $mode = '30s';

if ($mode === '1min') {
    $interval = 60; $bets_table = 'wingo_bets_1min';
} elseif ($mode === '3min') {
    $interval = 180; $bets_table = 'wingo_bets_3min';
} elseif ($mode === '5min') {
    $interval = 300; $bets_table = 'wingo_bets_5min';
} else {
    $interval = 30; $bets_table = 'wingo_bets';
}

function getPeriod($inv = 30) {
    $seconds_in_day = (date('H') * 3600) + (date('i') * 60) + date('s');
    $issue_num = floor($seconds_in_day / $inv) + 1;
    return date('Ymd') . str_pad($issue_num, 4, '0', STR_PAD_LEFT);
}

$current_period = getPeriod($interval);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'force_result') {
    $force_type = $_POST['force_type'];
    $force_value = $_POST['force_value'];
    
    if ($force_type === 'size_custom') {
        if (is_numeric($force_value)) {
            $force_type = 'number';
        } else {
            $force_type = 'size';
        }
    }
    
    if ($force_type === 'cancel') {
        $st = $pdo->prepare("DELETE FROM wingo_admin_force WHERE period = ?");
        $st->execute([$current_period]);
    } else {
        $st = $pdo->prepare("INSERT INTO wingo_admin_force (period, force_type, force_value) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE force_type=VALUES(force_type), force_value=VALUES(force_value)");
        $st->execute([$current_period, $force_type, $force_value]);
    }
    
    header("Location: " . $_SERVER['REQUEST_URI']);
    exit;
}

// ── FETCH LIVE BETS ─────────────────────────────────────────────────────────
$stmt = $pdo->prepare("SELECT bet_on, SUM(amount) as total_amount FROM {$bets_table} WHERE period = ? AND status = 'pending' GROUP BY bet_on");
$stmt->execute([$current_period]);
$bets = $stmt->fetchAll(PDO::FETCH_ASSOC);

$total_bets_amount = 0;
$raw_bets = [];
foreach ($bets as $b) {
    $raw_bets[$b['bet_on']] = (float)$b['total_amount'];
    $total_bets_amount += (float)$b['total_amount'];
}

// ── FETCH INDIVIDUAL LIVE BETS (For Stream) ──────────────────────────────────
$live_bets_stmt = $pdo->prepare("SELECT b.*, u.number FROM {$bets_table} b JOIN users u ON b.user_id = u.id WHERE b.period = ? ORDER BY b.created_at DESC");
$live_bets_stmt->execute([$current_period]);
$live_bets = $live_bets_stmt->fetchAll(PDO::FETCH_ASSOC);

// ── AI TIPPER: CALCULATE PAYOUT LIABILITY FOR EVERY NUMBER ──────────────────
$payout_scenarios = [];
for ($n = 0; $n <= 9; $n++) {
    $is_big = ($n >= 5);
    $win_color = ($n == 0 || $n == 5) ? 'violet' : (($n % 2 == 0) ? 'red' : 'green');
    $payout = 0;

    if (isset($raw_bets[(string)$n])) { $payout += $raw_bets[(string)$n] * 9; }
    if ($is_big && isset($raw_bets['big'])) { $payout += $raw_bets['big'] * 2; }
    if (!$is_big && isset($raw_bets['small'])) { $payout += $raw_bets['small'] * 2; }
    if ($win_color === 'violet' && isset($raw_bets['violet'])) { $payout += $raw_bets['violet'] * 4.5; }
    if ($win_color === 'red' || $n === 0) {
        if (isset($raw_bets['red'])) { $payout += $raw_bets['red'] * (in_array($n, [2, 4, 6, 8]) ? 2 : 1.5); }
    }
    if ($win_color === 'green' || $n === 5) {
        if (isset($raw_bets['green'])) { $payout += $raw_bets['green'] * (in_array($n, [1, 3, 7, 9]) ? 2 : 1.5); }
    }

    $profit = $total_bets_amount - $payout;
    $payout_scenarios[$n] = [
        'number' => $n,
        'size' => $is_big ? 'Big' : 'Small',
        'color' => $win_color,
        'payout' => $payout,
        'profit' => $profit
    ];
}

$best_options = $payout_scenarios;
usort($best_options, function($a, $b) { return $b['profit'] <=> $a['profit']; });
$best_profit = $best_options[0]['profit'];
$worst_profit = $best_options[count($best_options)-1]['profit'];

$force_chk = $pdo->prepare("SELECT force_type, force_value FROM wingo_admin_force WHERE period = ?");
$force_chk->execute([$current_period]);
$current_force = $force_chk->fetch(PDO::FETCH_ASSOC);

$big_bets = $raw_bets['big'] ?? 0;
$small_bets = $raw_bets['small'] ?? 0;
$total_size_bets = $big_bets + $small_bets;
$big_pct = $total_size_bets > 0 ? round(($big_bets / $total_size_bets) * 100) : 0;
$small_pct = $total_size_bets > 0 ? round(($small_bets / $total_size_bets) * 100) : 0;

$red_bets = $raw_bets['red'] ?? 0;
$green_bets = $raw_bets['green'] ?? 0;
$violet_bets = $raw_bets['violet'] ?? 0;

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WinGo Operations ?" PakClub</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Inter', 'Segoe UI', sans-serif; }
        body { background: #0f172a; color: #f8fafc; display: flex; min-height: 100vh; font-size: 14px; }
        .main { flex: 1; display: flex; flex-direction: column; overflow-x: hidden; }
        
        .topbar { background: #0f172a; border-bottom: 1px solid #1e293b; padding: 16px 32px; display: flex; align-items: center; justify-content: space-between; }
        .topbar h2 { font-size: 20px; font-weight: 600; color: #f8fafc; margin: 0; }
        
        /* Premium Mode Tabs */
        .tabs-container { padding: 24px 32px 0 32px; background: #0f172a; }
        .mode-tabs { display: flex; gap: 8px; border-bottom: 2px solid #1e293b; }
        .mode-tab { padding: 12px 24px; color: #64748b; text-decoration: none; font-size: 14px; font-weight: 600; border-bottom: 2px solid transparent; margin-bottom: -2px; transition: all 0.2s; border-radius: 8px 8px 0 0; }
        .mode-tab:hover { color: #cbd5e1; background: rgba(255,255,255,0.02); }
        .mode-tab.active { color: #38bdf8; border-bottom-color: #38bdf8; background: rgba(56, 189, 248, 0.05); }

        .content { padding: 24px 32px; flex: 1; }
        
        .header-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; }
        .period-info { font-size: 14px; color: #94a3b8; }
        .period-info strong { color: #f8fafc; font-size: 16px; margin-left: 4px; }
        
        /* Elegant Timer */
        .timer-display { background: #1e293b; border: 1px solid #334155; padding: 10px 20px; border-radius: 50px; font-size: 20px; font-weight: 700; color: #f8fafc; display: flex; align-items: center; gap: 10px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); transition: all 0.3s ease; }
        .timer-display i { color: #38bdf8; }
        .timer-display.closing { border-color: #ef4444; color: #ef4444; box-shadow: 0 0 15px rgba(239,68,68,0.2); }
        .timer-display.closing i { color: #ef4444; }

        /* Premium Cards */
        .card { background: #1e293b; border: 1px solid #334155; border-radius: 16px; padding: 24px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); margin-bottom: 24px; }
        .card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
        .card-title { font-size: 15px; font-weight: 600; color: #f1f5f9; display: flex; align-items: center; gap: 8px; }
        .card-title i { color: #94a3b8; }

        /* Stats Row */
        .stats-row { display: grid; grid-template-columns: repeat(3, 1fr); gap: 24px; margin-bottom: 24px; }
        .stat-item { display: flex; flex-direction: column; gap: 8px; }
        .stat-label { font-size: 12px; font-weight: 600; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; }
        .stat-value { font-size: 24px; font-weight: 700; color: #f8fafc; }
        .stat-value.success { color: #10b981; }
        .stat-value.danger { color: #ef4444; }

        .dashboard-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; margin-bottom: 24px; }
        @media (max-width: 1200px) { .dashboard-grid { grid-template-columns: 1fr; } }

        /* Elegant Tables */
        table { width: 100%; border-collapse: collapse; }
        th { text-align: left; padding: 12px 16px; color: #64748b; font-weight: 600; font-size: 12px; border-bottom: 1px solid #334155; }
        td { padding: 14px 16px; border-bottom: 1px solid #334155; color: #cbd5e1; font-size: 14px; }
        tr:last-child td { border-bottom: none; }
        
        /* Premium Badges & Buttons */
        .badge { display: inline-flex; align-items: center; justify-content: center; padding: 4px 10px; border-radius: 6px; font-size: 12px; font-weight: 600; }
        .badge.red { background: rgba(239, 68, 68, 0.1); color: #ef4444; }
        .badge.green { background: rgba(16, 185, 129, 0.1); color: #10b981; }
        .badge.violet { background: rgba(168, 85, 247, 0.1); color: #a855f7; }
        .badge.blue { background: rgba(56, 189, 248, 0.1); color: #38bdf8; }
        .badge.gold { background: rgba(245, 158, 11, 0.1); color: #f59e0b; }
        
        .btn-elegant { background: #334155; color: #f8fafc; border: 1px solid #475569; padding: 6px 14px; border-radius: 6px; font-size: 12px; font-weight: 500; cursor: pointer; transition: all 0.2s; display: inline-flex; align-items: center; gap: 6px; }
        .btn-elegant:hover { background: #475569; border-color: #64748b; }
        .btn-elegant.primary { background: #0284c7; border-color: #0369a1; }
        .btn-elegant.primary:hover { background: #0369a1; }
        
        /* Form Controls */
        .select-elegant { background: #0f172a; color: #f8fafc; border: 1px solid #334155; padding: 6px 12px; border-radius: 6px; font-size: 13px; outline: none; }
        .select-elegant:focus { border-color: #38bdf8; }

        /* AI Highlight */
        .ai-row { background: rgba(16, 185, 129, 0.05); }
        .ai-row td:first-child { position: relative; }
        .ai-row td:first-child::before { content: ''; position: absolute; left: 0; top: 0; bottom: 0; width: 3px; background: #10b981; border-radius: 0 4px 4px 0; }
        
        /* Overrides */
        .alert-override { background: rgba(245, 158, 11, 0.1); border: 1px solid rgba(245, 158, 11, 0.2); padding: 16px 24px; border-radius: 12px; display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; }
        .override-text { color: #fcd34d; font-size: 14px; }
        .override-text strong { font-weight: 600; color: #fde68a; }

        /* Stream Scroll */
        .stream-container { max-height: 400px; overflow-y: auto; padding-right: 8px; }
        .stream-container::-webkit-scrollbar { width: 6px; }
        .stream-container::-webkit-scrollbar-track { background: #0f172a; border-radius: 4px; }
        .stream-container::-webkit-scrollbar-thumb { background: #334155; border-radius: 4px; }
    </style>
</head>
<body>

<?php include 'sidebar.php'; ?>

<div class="main">
    <div class="topbar">
        <h2>WinGo Dashboard</h2>
    </div>
    
    <div class="tabs-container">
        <div class="mode-tabs">
            <a href="?mode=30s" class="mode-tab <?= $mode === '30s' ? 'active' : '' ?>">30 Second</a>
            <a href="?mode=1min" class="mode-tab <?= $mode === '1min' ? 'active' : '' ?>">1 Minute</a>
            <a href="?mode=3min" class="mode-tab <?= $mode === '3min' ? 'active' : '' ?>">3 Minute</a>
            <a href="?mode=5min" class="mode-tab <?= $mode === '5min' ? 'active' : '' ?>">5 Minute</a>
        </div>
    </div>

    <div class="content">
        <div class="header-row">
            <div class="period-info">
                Active Period: <strong><?= $current_period ?></strong>
            </div>
            <div class="timer-display" id="timerBadge">
                <i class="fa-regular fa-clock"></i> <span id="countdown">--</span>
            </div>
        </div>

        <?php if ($current_force): ?>
            <div class="alert-override">
                <div class="override-text">
                    <i class="fa-solid fa-lock" style="margin-right:8px;"></i>
                    Result overridden to: <strong><?= ucfirst($current_force['force_type']) ?> <?= ucfirst($current_force['force_value']) ?></strong>
                </div>
                <form method="POST" style="margin:0;">
                    <input type="hidden" name="action" value="force_result">
                    <input type="hidden" name="force_type" value="cancel">
                    <input type="hidden" name="force_value" value="cancel">
                    <button type="submit" class="btn-elegant">Remove</button>
                </form>
            </div>
        <?php endif; ?>

        <div class="card">
            <div class="stats-row" id="statsRow">
                <div class="stat-item">
                    <div class="stat-label">Total Live Pool</div>
                    <div class="stat-value">Rs <?= number_format($total_bets_amount, 2) ?></div>
                </div>
                <div class="stat-item">
                    <div class="stat-label">Max Risk Exposure</div>
                    <div class="stat-value <?= $worst_profit < 0 ? 'danger' : 'success' ?>">
                        <?= $worst_profit > 0 ? '+' : '' ?>Rs <?= number_format($worst_profit, 2) ?>
                    </div>
                </div>
                <div class="stat-item">
                    <div class="stat-label">AI Target Profit</div>
                    <div class="stat-value success">+Rs <?= number_format($best_profit, 2) ?></div>
                </div>
            </div>
            <div id="sizeBar" style="height:4px; background:#0f172a; border-radius:2px; display:flex; overflow:hidden;">
                <div style="width:<?= $big_pct ?>%; background:#38bdf8;" title="Big: <?= $big_pct ?>%"></div>
                <div style="width:<?= $small_pct ?>%; background:#64748b;" title="Small: <?= $small_pct ?>%"></div>
            </div>
        </div>

        <div class="dashboard-grid">
            <!-- Left: Macro Controls -->
            <div class="card">
                <div class="card-header">
                    <div class="card-title"><i class="fa-solid fa-layer-group"></i> Macro Pools</div>
                </div>
                <table id="macroPools">
                    <thead><tr><th>Segment</th><th>Volume</th><th>Action</th></tr></thead>
                    <tbody>
                        <tr>
                            <td><span class="badge red">Red</span></td>
                            <td>Rs <?= number_format($red_bets, 2) ?></td>
                            <td><form method="POST" style="margin:0;"><input type="hidden" name="action" value="force_result"><input type="hidden" name="force_type" value="color"><input type="hidden" name="force_value" value="red"><button class="btn-elegant">Force</button></form></td>
                        </tr>
                        <tr>
                            <td><span class="badge green">Green</span></td>
                            <td>Rs <?= number_format($green_bets, 2) ?></td>
                            <td><form method="POST" style="margin:0;"><input type="hidden" name="action" value="force_result"><input type="hidden" name="force_type" value="color"><input type="hidden" name="force_value" value="green"><button class="btn-elegant">Force</button></form></td>
                        </tr>
                        <tr>
                            <td><span class="badge violet">Violet</span></td>
                            <td>Rs <?= number_format($violet_bets, 2) ?></td>
                            <td><form method="POST" style="margin:0;"><input type="hidden" name="action" value="force_result"><input type="hidden" name="force_type" value="color"><input type="hidden" name="force_value" value="violet"><button class="btn-elegant">Force</button></form></td>
                        </tr>
                        <tr>
                            <td><span class="badge blue">Big (<?= $big_pct ?>%)</span></td>
                            <td>Rs <?= number_format($big_bets, 2) ?></td>
                            <td>
                                <form method="POST" style="display:flex; gap:8px;">
                                    <input type="hidden" name="action" value="force_result">
                                    <input type="hidden" name="force_type" value="size_custom">
                                    <select name="force_value" class="select-elegant">
                                        <option value="big">Random</option><option value="5">#5</option><option value="6">#6</option><option value="7">#7</option><option value="8">#8</option><option value="9">#9</option>
                                    </select>
                                    <button class="btn-elegant">Set</button>
                                </form>
                            </td>
                        </tr>
                        <tr>
                            <td><span class="badge" style="background:#64748b; color:#fff;">Small (<?= $small_pct ?>%)</span></td>
                            <td>Rs <?= number_format($small_bets, 2) ?></td>
                            <td>
                                <form method="POST" style="display:flex; gap:8px;">
                                    <input type="hidden" name="action" value="force_result">
                                    <input type="hidden" name="force_type" value="size_custom">
                                    <select name="force_value" class="select-elegant">
                                        <option value="small">Random</option><option value="0">#0</option><option value="1">#1</option><option value="2">#2</option><option value="3">#3</option><option value="4">#4</option>
                                    </select>
                                    <button class="btn-elegant">Set</button>
                                </form>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- Right: AI Predictor -->
            <div class="card">
                <div class="card-header">
                    <div class="card-title"><i class="fa-solid fa-microchip"></i> Prediction Matrix</div>
                </div>
                <table id="predictionMatrix">
                    <thead>
                        <tr><th>Num</th><th>Properties</th><th>Payout</th><th>House PNL</th><th></th></tr>
                    </thead>
                    <tbody>
                        <?php foreach ($payout_scenarios as $s): 
                            $is_best = ($s['profit'] == $best_profit && $total_bets_amount > 0);
                        ?>
                        <tr class="<?= $is_best ? 'ai-row' : '' ?>">
                            <td style="font-weight:600;"><?= $s['number'] ?></td>
                            <td><span class="badge <?= $s['size']==='Big'?'blue':'' ?>" style="<?= $s['size']==='Small'?'background:#64748b;color:#fff;':'' ?>"><?= $s['size'] ?></span> <span class="badge <?= $s['color'] ?>"><?= ucfirst($s['color']) ?></span></td>
                            <td style="color:#94a3b8;">Rs <?= number_format($s['payout'], 2) ?></td>
                            <td class="<?= $s['profit'] < 0 ? 'text-red' : 'text-green' ?>" style="font-weight:600;"><?= $s['profit'] > 0 ? '+' : '' ?><?= number_format($s['profit'], 2) ?></td>
                            <td style="text-align:right;">
                                <form method="POST" style="margin:0;">
                                    <input type="hidden" name="action" value="force_result">
                                    <input type="hidden" name="force_type" value="number">
                                    <input type="hidden" name="force_value" value="<?= $s['number'] ?>">
                                    <button class="btn-elegant <?= $is_best ? 'primary' : '' ?>">Target</button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Live Bets Stream -->
        <div class="card">
            <div class="card-header">
                <div class="card-title"><i class="fa-solid fa-satellite-dish"></i> Live Bets Stream</div>
            </div>
            
            <?php if (empty($live_bets)): ?>
                <div id="liveBetsStream" style="padding: 40px; text-align: center; color: #64748b;">No bets placed in this period yet.</div>
            <?php else: ?>
                <div class="stream-container" id="liveBetsStream">
                    <table>
                        <thead>
                            <tr>
                                <th>Time</th>
                                <th>User (Phone)</th>
                                <th>Selection</th>
                                <th>Amount Staked</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($live_bets as $lb): 
                                $s_badge = 'badge ';
                                if (in_array($lb['bet_on'], ['red','green','violet'])) {
                                    $s_badge .= $lb['bet_on'];
                                } elseif ($lb['bet_on'] === 'big') {
                                    $s_badge .= 'blue';
                                } elseif ($lb['bet_on'] === 'small') {
                                    $s_badge .= 'style="background:#64748b;color:#fff;"';
                                } else {
                                    $s_badge .= 'gold';
                                }
                            ?>
                            <tr>
                                <td style="font-size:12px; color:#94a3b8;"><?= date('H:i:s', strtotime($lb['created_at'])) ?></td>
                                <td style="font-weight:600; color:#f8fafc;"><?= htmlspecialchars($lb['number']) ?></td>
                                <td><span class="<?= $s_badge ?>"><?= ucfirst($lb['bet_on']) ?></span></td>
                                <td style="color:#e2e8f0; font-weight:600;">Rs <?= number_format($lb['amount'], 2) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
    const interval = <?= $interval ?>;
    const serverTime = <?= time() ?>;
    const clientTime = Math.floor(Date.now() / 1000);
    const timeOffset = serverTime - clientTime;

    function updateTimer() {
        const syncedNow = Math.floor(Date.now() / 1000) + timeOffset;
        let timeLeft = interval - (syncedNow % interval);
        
        const badge = document.getElementById('timerBadge');
        const countStr = timeLeft.toString().padStart(2, '0');
        document.getElementById('countdown').innerText = countStr;
        
        if (timeLeft <= 10) {
            badge.classList.add('closing');
        } else {
            badge.classList.remove('closing');
        }
        
        if (timeLeft === 2 || timeLeft === interval) {
            window.location.href = window.location.pathname + window.location.search;
        }
    }
    
    // Live Data Polling (AJAX DOM Replacement)
    function pollLiveData() {
        fetch(window.location.href)
            .then(res => res.text())
            .then(html => {
                const parser = new DOMParser();
                const doc = parser.parseFromString(html, "text/html");
                
                const statsRow = doc.getElementById('statsRow');
                if (statsRow) document.getElementById('statsRow').innerHTML = statsRow.innerHTML;
                
                const sizeBar = doc.getElementById('sizeBar');
                if (sizeBar) document.getElementById('sizeBar').innerHTML = sizeBar.innerHTML;
                
                const macroPools = doc.getElementById('macroPools');
                if (macroPools) document.getElementById('macroPools').innerHTML = macroPools.innerHTML;
                
                const predictionMatrix = doc.getElementById('predictionMatrix');
                if (predictionMatrix) document.getElementById('predictionMatrix').innerHTML = predictionMatrix.innerHTML;
                
                const liveBetsStream = doc.getElementById('liveBetsStream');
                if (liveBetsStream) {
                    const currentStream = document.getElementById('liveBetsStream');
                    if (currentStream) {
                        // Replace the outerHTML if switching from empty div to stream-container, 
                        // otherwise innerHTML works. Using outerHTML is safer here.
                        currentStream.outerHTML = liveBetsStream.outerHTML;
                    }
                }
            })
            .catch(err => console.log('Polling error:', err));
    }
    
    setInterval(updateTimer, 1000);
    updateTimer();
    
    // Poll every 3 seconds for live updates
    setInterval(pollLiveData, 3000);
</script>

</body>
</html>