<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['user_id'])) { header("Location: ../login.php"); exit; }
if (!isset($_GET['id']) || empty($_GET['id'])) { header("Location: custom.php"); exit; }

$match_id = htmlspecialchars($_GET['id']);

global $pdo;

// 1. Balance Fetching
$stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$walletBalance = $stmt->fetchColumn() ?: 0.00;

// 2. Fetch Website Settings
$siteName = 'EXCHANGE PRO'; 
$siteFavicon = '../assets/default-favicon.ico'; 
try {
    $stmtName = $pdo->query("SELECT setting_value FROM site_settings WHERE setting_key = 'site_name'");
    if ($nameResult = $stmtName->fetchColumn()) { $siteName = $nameResult; }
    $stmtFav = $pdo->query("SELECT setting_value FROM site_settings WHERE setting_key = 'favicon'");
    if ($favResult = $stmtFav->fetchColumn()) { $siteFavicon = '../' . $favResult; }
} catch (Exception $e) {}
?>
<!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>Live Match - <?= htmlspecialchars($siteName) ?></title>
    
    <link rel="icon" type="image/x-icon" href="<?= htmlspecialchars($siteFavicon) ?>">
    <link rel="shortcut icon" type="image/x-icon" href="<?= htmlspecialchars($siteFavicon) ?>">
    
    <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">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700;900&display=swap" rel="stylesheet">
    
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <style>
        :root {
            /* ⚪ White Theme Colors ⚪ */
            --bg-main: #FFFFFF;       /* Pure White Background */
            --bg-card: #FFFFFF;
            --bg-sub: #F5F7FA;        /* Light Grey for headers/strips */
            
            --text-main: #111111;     /* Dark Text */
            --text-muted: #666666;    /* Muted Grey Text */
            
            /* Betting Colors (Same as custom.php) */
            --ex-back: #A1D3ED;       /* Standard Light Blue */
            --ex-lay: #FAA9BA;        /* Standard Light Pink */
            
            --theme-blue: #1E88E5;    /* Accent Blue */
            --theme-red: #D32F2F;     /* Accent Red for Live */
            --theme-gold: #BF9B30;    /* Dark Gold for score digits */
            
            --card-shadow: 0 4px 12px rgba(0,0,0,0.1); /* Standard Box Shadow */
            --border-color: #EEEEEE;
        }
        
        * { font-family: 'Roboto', sans-serif; -webkit-tap-highlight-color: transparent; user-select: none; box-sizing: border-box; }
        
        body { 
            background: var(--bg-main); 
            color: var(--text-main); max-width: 480px; margin: 0 auto; min-height: 100vh; position: relative; padding-top: 65px; padding-bottom: 20px;
        }

        /* Standard Light Header */
        .ex-header { 
            position: fixed; top: 0; left: 50%; transform: translateX(-50%); width: 100%; max-width: 480px; 
            background: rgba(255, 255, 255, 0.95); backdrop-filter: blur(5px);
            border-bottom: 1px solid var(--border-color); color: var(--text-main); height: 60px; display: flex; align-items: center; justify-content: space-between; 
            padding: 0 15px; z-index: 1000; box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        }
        .ex-logo { font-size: 16px; font-weight: 800; color: var(--text-main); text-transform: uppercase; letter-spacing: 0.5px;}
        .ex-bal { 
            background: #F1F8FD; border: 1px solid #D1E9F9; padding: 5px 12px; border-radius: 6px; font-weight: 800; font-size: 13px; color: var(--theme-blue);
        }

        /* ✅ Classic Light Scoreboard UI with Shadow ✅ */
        .stadium-board {
            margin: 10px 12px 20px 12px; border-radius: 12px; overflow: hidden; position: relative;
            background: #FFFFFF; border: 1px solid var(--border-color); box-shadow: var(--card-shadow);
        }
        .stadium-header {
            display: flex; justify-content: space-between; padding: 10px 15px; background: var(--bg-sub); border-bottom: 1px solid var(--border-color);
        }
        .live-badge {
            background: rgba(211, 47, 47, 0.1); color: var(--theme-red); border: 1px solid var(--theme-red); padding: 3px 10px; border-radius: 6px; font-size: 11px; font-weight: 900; letter-spacing: 1px; display: flex; align-items: center; gap: 6px;
        }
        .match-name-tag { font-size: 11px; color: var(--text-muted); font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px;}

        .score-display {
            padding: 25px 15px; text-align: center; position: relative; background: #FFFFFF;
        }
        .teams-wrapper { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-bottom: 15px;}
        .team-name { flex: 1; font-size: 15px; font-weight: 800; line-height: 1.2; text-transform: uppercase; color: var(--text-main);}
        .vs-circle { background: #EEEEEE; width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; border-radius: 50%; font-size: 11px; font-weight: 900; color: #888;}
        
        /* The Big Digits (Light Theme) */
        .digital-score {
            font-size: 26px; font-weight: 900; letter-spacing: 1px; color: var(--theme-gold); background: #F9F9F9; padding: 10px 15px; border-radius: 10px; border: 1px solid var(--border-color); display: inline-block; min-width: 180px; box-shadow: inset 0 2px 4px rgba(0,0,0,0.02);
        }

        /* Light Match Info Strip */
        .match-info-strip {
            display: flex; background: #F1F8FD; border-top: 1px solid #D1E9F9;
        }
        .info-box {
            flex: 1; text-align: center; padding: 10px; border-right: 1px solid #D1E9F9;
        }
        .info-box:last-child { border-right: none; }
        .info-label { font-size: 10px; color: var(--theme-blue); font-weight: 700; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 3px;}
        .info-val { font-size: 14px; color: var(--text-main); font-weight: 800;}

        /* Market Section */
        .market-title { margin: 0 12px 10px 12px; font-size: 13px; font-weight: 800; color: var(--text-muted); display: flex; align-items: center; gap: 8px; text-transform: uppercase; letter-spacing: 1px;}
        
        /* ✅ Market Card with Shadow ✅ */
        .market-card {
            background: #FFFFFF; margin: 0 12px 20px 12px; border-radius: 12px; border: 1px solid var(--border-color); box-shadow: var(--card-shadow); overflow: hidden; position: relative;
        }
        .market-header { 
            display: flex; justify-content: flex-end; padding: 8px 15px; font-size: 11px; font-weight: 800; background: var(--bg-sub); border-bottom: 1px solid var(--border-color); color: var(--text-muted);
        }
        .market-header div { width: 65px; text-align: center; margin-left: 6px;}
        
        .runner-row { display: flex; align-items: center; padding: 10px 15px; border-bottom: 1px solid var(--border-color); transition: background 0.3s;}
        .runner-name { flex: 1; font-weight: 700; font-size: 14px; color: var(--text-main);}
        
        /* ✅ Standard Light Odds Buttons ✅ */
        .odd-box { 
            width: 65px; height: 46px; display: flex; flex-direction: column; align-items: center; justify-content: center; border-radius: 6px; cursor: pointer; margin-left: 6px; transition: all 0.2s ease; border: 1px solid #DDDDDD;
        }
        .back-box { background: var(--ex-back); border-color: #82C2E5; }
        .lay-box { background: var(--ex-lay); border-color: #F894A8; }
        .odd-box:active { filter: brightness(0.9); }
        .odd-val { font-weight: 800; font-size: 17px; line-height: 1.1; margin-bottom: 2px; color: #111;}
        .odd-size { font-size: 10px; font-weight: 600; color: #444;}

        /* Suspended Lock */
        .market-suspended { 
            position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.85); z-index: 10; display: none; align-items: center; justify-content: center; backdrop-filter: blur(2px);
        }
        .suspend-text { 
            background: var(--theme-red); color: white; padding: 8px 20px; font-weight: 800; font-size: 14px; border-radius: 6px; text-transform: uppercase; letter-spacing: 1px; box-shadow: 0 4px 10px rgba(211,47,47,0.3);
        }
        .market-card.is-locked .market-suspended { display: flex; }

        /* Loader */
        .full-loader { text-align:center; padding: 100px 20px; color:var(--text-muted); }

        /* ✅ Light Bet Slip ✅ */
        .bet-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100vh; background: rgba(0,0,0,0.6); z-index: 2000; display: none; opacity: 0; transition: 0.3s;}
        .bet-slip { position: fixed; bottom: -100%; left: 50%; transform: translateX(-50%); width: 100%; max-width: 480px; background: #FFFFFF; z-index: 2001; transition: 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); border-radius: 16px 16px 0 0; box-shadow: 0 -5px 25px rgba(0,0,0,0.2);}
        .bet-overlay.active { display: block; opacity: 1; }
        .bet-slip.active { bottom: 0; }
        .slip-header { padding: 18px 20px; color: white; display: flex; justify-content: space-between; align-items: center; font-weight: 800; }
        .slip-header.back-theme { background: var(--theme-blue); }
        .slip-header.lay-theme { background: var(--theme-red); }
        .slip-body { padding: 25px 20px; background: #F9F9F9;}
        .input-row { display: flex; gap: 12px; margin-bottom: 20px;}
        .input-box { flex: 1; background: #FFFFFF; border: 1px solid #CCCCCC; border-radius: 8px; padding: 8px 15px;}
        .input-label { font-size: 11px; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 1px;}
        .ex-input { width: 100%; border: none; font-size: 20px; font-weight: 800; color: var(--text-main); outline: none; background: transparent; margin-top: 4px;}
        .quick-stakes { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin-bottom: 25px;}
        .qs-btn { background: #FFFFFF; border: 1px solid #CCCCCC; border-radius: 6px; padding: 12px 0; font-weight: 700; font-size: 13px; color: var(--text-main); cursor: pointer; transition: 0.2s; }
        .qs-btn:active { background: #EEEEEE; }
        .pl-box { display: flex; justify-content: space-between; background: #FFFFFF; padding: 15px 20px; border-radius: 8px; border: 1px dashed #CCCCCC; margin-bottom: 25px;}
        .profit-val { color: #2E7D32; font-weight: 800; font-size: 18px;}
        .liability-val { color: var(--theme-red); font-weight: 800; font-size: 18px;}
        .place-bet-btn { width: 100%; padding: 16px; font-size: 16px; font-weight: 800; color: white; border: none; border-radius: 8px; text-transform: uppercase; letter-spacing: 1px; }
        .place-bet-btn.back-theme { background: var(--theme-blue); }
        .place-bet-btn.lay-theme { background: var(--theme-red); }

        /* Toast Snackbar */
        #snackbar {
            visibility: hidden; min-width: 250px; background: #333333; color: #fff; text-align: center; border-radius: 8px; padding: 16px; position: fixed; z-index: 9999; left: 50%; bottom: 30px; transform: translateX(-50%); font-size: 14px; font-weight: 700; box-shadow: 0 4px 15px rgba(0,0,0,0.3); opacity: 0; transition: all 0.3s;
        }
        #snackbar.show { visibility: visible; opacity: 1; bottom: 80px; }
        
        ::-webkit-scrollbar { width: 4px; }
        ::-webkit-scrollbar-track { background: var(--bg-main); }
        ::-webkit-scrollbar-thumb { background: #CCCCCC; border-radius: 10px; }
    </style>
</head>
<body>

    <div class="ex-header">
        <a href="custom.php" style="color:var(--text-main); text-decoration:none; font-size: 18px;"><i class="fas fa-arrow-left"></i></a>
        <div class="ex-logo">Live Arena</div>
        <div class="ex-bal" id="headerBal">₹<?= number_format($walletBalance, 2) ?></div>
    </div>

    <div id="loader" class="full-loader">
        <i class="fas fa-satellite-dish fa-spin" style="font-size: 40px; margin-bottom: 20px; color: var(--theme-blue);"></i>
        <div style="font-weight:700; font-size:14px; color: var(--text-muted);">CONNECTING LIVE FEED...</div>
    </div>

    <div id="matchWrapper" style="display:none;">
        
        <div class="stadium-board">
            <div class="stadium-header">
                <span class="match-name-tag" id="uiMatchName">--</span>
                <span class="live-badge" id="uiMatchStatus"><i class="fas fa-circle"></i> LIVE</span>
            </div>
            
            <div class="score-display">
                <div class="teams-wrapper">
                    <div class="team-name" style="text-align: right;" id="uiTeam1">--</div>
                    <div class="vs-circle">VS</div>
                    <div class="team-name" style="text-align: left;" id="uiTeam2">--</div>
                </div>
                <div class="digital-score" id="uiScore">0/0 (0.0)</div>
            </div>

            <div class="match-info-strip">
                <div class="info-box">
                    <div class="info-label">Current Over</div>
                    <div class="info-val" id="uiCurrentOver">--</div>
                </div>
                <div class="info-box">
                    <div class="info-label">Run Rate</div>
                    <div class="info-val" id="uiRR">--</div>
                </div>
                <div class="info-box">
                    <div class="info-label">Feed</div>
                    <div class="info-val" id="uiBalls" style="color:var(--theme-green)">REAL-TIME</div>
                </div>
            </div>
        </div>

        <div class="market-title"><i class="fas fa-align-left" style="color:var(--theme-blue)"></i> Match Odds</div>

        <div class="market-card" id="uiMarketBox">
            </div>

    </div>

    <div class="bet-overlay" id="betOverlay" onclick="closeSlip()"></div>
    <div class="bet-slip" id="betSlip">
        <div class="slip-header back-theme" id="slipHeader">
            <div>
                <div id="slipTypeTxt" style="font-size:12px; color:rgba(255,255,255,0.9); text-transform: uppercase;">Place Bet</div>
                <div id="slipRunnerName" style="font-size:18px;">Runner Name</div>
            </div>
            <div style="width:30px; height:30px; display:flex; align-items:center; justify-content:center; cursor:pointer;" onclick="closeSlip()">
                <i class="fas fa-times" style="font-size:18px;"></i>
            </div>
        </div>
        
        <div class="slip-body">
            <div class="input-row">
                <div class="input-box">
                    <div class="input-label">Odds</div>
                    <input type="number" class="ex-input" id="slipOdds" readonly>
                </div>
                <div class="input-box">
                    <div class="input-label">Stake (₹)</div>
                    <input type="number" class="ex-input" id="slipStake" value="100" oninput="calcProfit()">
                </div>
            </div>

            <div class="quick-stakes">
                <button class="qs-btn" onclick="addStake(100)">+100</button>
                <button class="qs-btn" onclick="addStake(500)">+500</button>
                <button class="qs-btn" onclick="addStake(1000)">+1K</button>
                <button class="qs-btn" onclick="addStake(5000)">+5K</button>
            </div>

            <div class="pl-box">
                <div>
                    <div class="input-label">Profit <i class="fas fa-level-up-alt" style="color:#2E7D32"></i></div>
                    <div class="profit-val" id="slipProfit">₹0.00</div>
                </div>
                <div style="text-align:right;">
                    <div class="input-label">Liability <i class="fas fa-level-down-alt" style="color:var(--theme-red)"></i></div>
                    <div class="liability-val" id="slipLiability">-₹100.00</div>
                </div>
            </div>

            <button class="place-bet-btn back-theme" id="btnPlaceBet" onclick="submitBet()">CONFIRM BET</button>
        </div>
    </div>

    <div id="snackbar">Message here</div>

    <script>
        const targetMatchId = "<?= $match_id ?>";
        let isFirstLoad = true;
        let currentType = ''; let currentRunner = '';

        function showToast(message) {
            var x = document.getElementById("snackbar"); x.innerText = message; x.className = "show";
            setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
        }

        function extractOversInfo(scoreStr) {
            // Basic logic to extract overs info from score string
            let overMatch = scoreStr.match(/\((\d+\.?\d*)/);
            if(overMatch && overMatch[1]) {
                document.getElementById('uiCurrentOver').innerText = overMatch[1] + " ov";
            } else {
                document.getElementById('uiCurrentOver').innerText = "--";
            }
        }

        function loadMatchDetails() {
            fetch('../getlivecricket.php').then(r=>r.json()).then(res => {
                if(res.success && res.data) {
                    const matchData = res.data.find(m => m.id === targetMatchId);
                    
                    if(matchData) {
                        if(isFirstLoad) {
                            document.getElementById('loader').style.display = 'none';
                            document.getElementById('matchWrapper').style.display = 'block';
                            isFirstLoad = false;
                        }
                        renderMatchUI(matchData);
                    } else {
                        if(isFirstLoad) {
                            document.getElementById('loader').innerHTML = '<i class="fas fa-exclamation-triangle" style="font-size:35px; color:var(--theme-red);"></i><br><br>MATCH ENDED OR NOT FOUND';
                        }
                    }
                }
            }).catch(e => console.log("Connection error..."));
        }

        function renderMatchUI(m) {
            // Update Scoreboard Text
            document.getElementById('uiMatchName').innerText = m.name;
            document.getElementById('uiTeam1').innerText = m.team1.name;
            document.getElementById('uiTeam2').innerText = m.team2.name;
            document.getElementById('uiScore').innerText = m.score;
            document.getElementById('uiMatchStatus').innerHTML = `<i class="fas fa-circle" style="font-size:8px;"></i> ${m.status}`;
            
            extractOversInfo(m.score);

            // Update Market Odds
            let lockedClass = m.is_locked == 1 ? 'is-locked' : '';
            let marketHtml = `
                <div class="market-suspended"><div class="suspend-text">Suspended</div></div>
                <div class="market-header">
                    <div style="color:var(--theme-blue);">BACK</div>
                    <div style="color:var(--theme-red);">LAY</div>
                </div>

                <div class="runner-row">
                    <div class="runner-name">${m.team1.name}</div>
                    <div class="odd-box back-box" onclick="openSlip('${m.team1.name}', ${m.team1.back}, 'back')">
                        <span class="odd-val">${m.team1.back}</span><span class="odd-size">100K</span>
                    </div>
                    <div class="odd-box lay-box" onclick="openSlip('${m.team1.name}', ${m.team1.lay}, 'lay')">
                        <span class="odd-val">${m.team1.lay}</span><span class="odd-size">20K</span>
                    </div>
                </div>
                
                <div class="runner-row">
                    <div class="runner-name">${m.team2.name}</div>
                    <div class="odd-box back-box" onclick="openSlip('${m.team2.name}', ${m.team2.back}, 'back')">
                        <span class="odd-val">${m.team2.back}</span><span class="odd-size">150K</span>
                    </div>
                    <div class="odd-box lay-box" onclick="openSlip('${m.team2.name}', ${m.team2.lay}, 'lay')">
                        <span class="odd-val">${m.team2.lay}</span><span class="odd-size">10K</span>
                    </div>
                </div>
            `;
            
            let marketBox = document.getElementById('uiMarketBox');
            
            // Apply locked class to parent
            if(m.is_locked == 1) { marketBox.classList.add('is-locked'); } 
            else { marketBox.classList.remove('is-locked'); }

            if(marketBox.innerHTML !== marketHtml) { marketBox.innerHTML = marketHtml; }
        }

        loadMatchDetails();
        setInterval(loadMatchDetails, 2000);

        // --- Bet Slip Logic ---
        function openSlip(runner, odds, type) {
            if(odds <= 0 || isNaN(odds)) return; 
            currentRunner = runner; currentType = type; 
            
            let header = document.getElementById('slipHeader');
            let btn = document.getElementById('btnPlaceBet');
            let txt = document.getElementById('slipTypeTxt');
            
            if(type === 'back') {
                header.className = 'slip-header back-theme'; btn.className = 'place-bet-btn back-theme'; txt.innerText = 'Back (Bet For)';
            } else {
                header.className = 'slip-header lay-theme'; btn.className = 'place-bet-btn lay-theme'; txt.innerText = 'Lay (Bet Against)';
            }

            document.getElementById('slipRunnerName').innerText = runner;
            document.getElementById('slipOdds').value = odds;
            document.getElementById('slipStake').value = 100;
            calcProfit();
            document.getElementById('betOverlay').classList.add('active');
            document.getElementById('betSlip').classList.add('active');
        }

        function closeSlip() { document.getElementById('betOverlay').classList.remove('active'); document.getElementById('betSlip').classList.remove('active'); }
        function addStake(amt) { document.getElementById('slipStake').value = (parseFloat(document.getElementById('slipStake').value) || 0) + amt; calcProfit(); }

        function calcProfit() {
            let odds = parseFloat(document.getElementById('slipOdds').value) || 0;
            let stake = parseFloat(document.getElementById('slipStake').value) || 0;
            
            if(currentType === 'back') {
                document.getElementById('slipProfit').innerText = '₹' + (stake * (odds - 1)).toFixed(2);
                document.getElementById('slipLiability').innerText = '-₹' + stake.toFixed(2);
            } else {
                document.getElementById('slipProfit').innerText = '₹' + stake.toFixed(2);
                document.getElementById('slipLiability').innerText = '-₹' + (stake * (odds - 1)).toFixed(2);
            }
        }

        async function submitBet() {
            const btn = document.getElementById('btnPlaceBet');
            const stake = parseFloat(document.getElementById('slipStake').value) || 0;
            const odds = parseFloat(document.getElementById('slipOdds').value) || 0;

            if(stake < 10) { showToast("Minimum stake is ₹10"); return; }
            let requiredBalanceToDeduct = currentType === 'back' ? stake : (stake * (odds - 1));

            btn.innerText = "PROCESSING..."; btn.disabled = true;

            let fd = new FormData();
            fd.append('period', targetMatchId); 
            fd.append('selection', `${currentRunner} [${currentType.toUpperCase()}] @${odds}`); 
            fd.append('amount', requiredBalanceToDeduct);

            try {
                let res = await fetch('../getbetting.php', { method: 'POST', body: fd }).then(r => r.json());
                if (res.success) {
                    document.getElementById('headerBal').innerText = "₹" + parseFloat(res.new_balance).toFixed(2);
                    showToast("✅ Bet Successfully Placed!");
                    closeSlip(); 
                } else { showToast("❌ " + res.message); }
            } catch(e) { showToast("⚠️ Connection Error. Try Again."); }
            
            btn.innerText = "CONFIRM BET"; btn.disabled = false;
        }
    </script>
</body>
</html>