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

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

global $pdo;

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

// 2. Fetch Website Name, Logo & Favicon from 'site_settings'
$siteName = 'EXCHANGE PRO'; 
$siteLogo = '../assets/default-logo.png'; 
$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; }

    $stmtLogo = $pdo->query("SELECT setting_value FROM site_settings WHERE setting_key = 'site_logo'");
    if ($logoResult = $stmtLogo->fetchColumn()) { $siteLogo = '../' . $logoResult; }

    $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><?= htmlspecialchars($siteName) ?> - Live Matches</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 {
            --ex-header: #1E2329;
            --ex-bg: #EAECEF;
            
            /* Standard Betting App Colors */
            --ex-back: #A1D3ED;       /* Light Blue */
            --ex-lay: #FAA9BA;        /* Light Pink */
            --ex-back-dark: #72BBE3;
            --ex-lay-dark: #E53935;
            
            --text-dark: #111111;
            --text-muted: #555555;
        }
        
        * { font-family: 'Roboto', sans-serif; -webkit-tap-highlight-color: transparent; user-select: none; box-sizing: border-box; }
        
        body { 
            background: var(--ex-bg); 
            max-width: 480px; 
            margin: 0 auto; 
            min-height: 100vh; 
            position: relative; 
            padding-top: 55px; 
            padding-bottom: 20px;
        }

        /* Standard Header */
        .ex-header { 
            position: fixed; top: 0; left: 50%; transform: translateX(-50%); width: 100%; max-width: 480px; 
            background: var(--ex-header); color: white; height: 55px; 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.2);
        }
        .ex-logo { font-size: 16px; font-weight: 800; font-style: italic; letter-spacing: 0.5px; color: #F1C40F;}
        .ex-bal { font-weight: 700; font-size: 14px; background: rgba(255,255,255,0.1); padding: 4px 10px; border-radius: 4px;}

        /* Tabs */
        .ex-tabs { 
            display: flex; background: white; border-bottom: 2px solid #ddd; box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        }
        .ex-tab { 
            flex: 1; text-align: center; padding: 12px 0; font-weight: 700; font-size: 13px; 
            color: var(--text-muted); cursor: pointer; text-transform: uppercase;
        }
        .ex-tab.active { 
            color: #1E88E5; border-bottom: 3px solid #1E88E5; background: #f8fbff;
        }

        /* Match Card */
        .match-card { 
            background: white; margin: 10px; border-radius: 8px; box-shadow: 0 2px 6px rgba(0,0,0,0.1); overflow: hidden; position: relative;
        }
        .m-header { 
            background: #2A3B4C; color: white; padding: 8px 12px; font-size: 12px; font-weight: 700; 
            display: flex; justify-content: space-between; align-items: center;
        }
        
        .live-pulse { 
            background: #D32F2F; padding: 3px 8px; border-radius: 4px; font-size: 10px; font-weight: 800; display: flex; align-items: center; gap: 5px; color: white;
        }
        .live-pulse i { animation: blink 1.5s infinite; }
        .future-timer { background: #F39C12; padding: 3px 8px; border-radius: 4px; font-size: 11px; font-weight: 800; color: white;}
        @keyframes blink { 0% { opacity: 1; } 50% { opacity: 0.3; } 100% { opacity: 1; } }

        /* Classic Score Area (Clickable) */
        .score-board { 
            padding: 20px 15px; 
            background: linear-gradient(to right, #0F2027, #203A43, #2C5364); 
            color: white; display: flex; align-items: center; justify-content: space-between; gap: 10px;
            cursor: pointer;
        }
        .score-board:active { opacity: 0.9; }
        
        .team-name-big { flex: 1; font-size: 14px; font-weight: 800; line-height: 1.2; text-transform: uppercase; }
        .score-text { 
            flex: 1; text-align: center; font-size: 18px; font-weight: 800; color: #F1C40F; 
            background: rgba(0,0,0,0.3); padding: 5px 10px; border-radius: 6px;
        }
        .view-info-icon { position: absolute; top: 8px; right: 10px; font-size: 11px; color: rgba(255,255,255,0.5); }

        /* Market Area */
        .market-body { position: relative; }
        .market-header { 
            display: flex; justify-content: flex-end; padding: 6px 15px; font-size: 11px; font-weight: 800; 
            background: #F5F7FA; border-bottom: 1px solid #E0E0E0;
        }
        .market-header div { width: 60px; text-align: center; margin-left: 4px;}
        
        .runner-row { display: flex; align-items: center; padding: 8px 15px; border-bottom: 1px solid #EEEEEE;}
        
        /* 🔥 Team Name Clickable Area 🔥 */
        .runner-name { 
            flex: 1; font-weight: 700; font-size: 14px; color: var(--text-dark); cursor: pointer; padding: 10px 0;
        }
        .runner-name:active { color: #1E88E5; } /* Feedback on click */
        
        /* Clean Odds Buttons */
        .odd-box { 
            width: 60px; height: 42px; display: flex; flex-direction: column; align-items: center; justify-content: center; 
            border-radius: 4px; cursor: pointer; margin-left: 4px; box-shadow: 0 1px 2px rgba(0,0,0,0.1);
        }
        .back-box { background: var(--ex-back); border: 1px solid #82C2E5; }
        .lay-box { background: var(--ex-lay); border: 1px solid #F894A8; }
        .odd-box:active { filter: brightness(0.9); }
        
        .odd-val { font-weight: 800; font-size: 15px; color: #111; line-height: 1.1;}
        .odd-size { font-size: 10px; font-weight: 600; color: #444;}

        /* Suspended Overlay */
        .market-suspended { 
            position: absolute; top: 0; left: 0; width: 100%; height: 100%; 
            background: rgba(255,255,255,0.8); z-index: 10; display: none; align-items: center; justify-content: center; 
        }
        .suspend-text { 
            background: #D32F2F; color: white; padding: 6px 20px; font-weight: 800; font-size: 14px; border-radius: 4px; text-transform: uppercase;
        }
        .match-card.is-locked .market-suspended { display: flex; }

        /* Clean 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: white; z-index: 2001; transition: 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); 
            border-radius: 12px 12px 0 0; overflow: hidden; box-shadow: 0 -5px 20px rgba(0,0,0,0.3);
        }
        .bet-overlay.active { display: block; opacity: 1; }
        .bet-slip.active { bottom: 0; }
        
        .slip-header { padding: 15px; color: white; display: flex; justify-content: space-between; align-items: center; font-weight: 800;}
        .slip-header.back-theme { background: #1E88E5; }
        .slip-header.lay-theme { background: #E53935; }
        
        .slip-body { padding: 20px; background: #F9F9F9;}
        .input-row { display: flex; gap: 10px; margin-bottom: 15px;}
        .input-box { flex: 1; background: white; border: 1px solid #CCC; border-radius: 6px; padding: 5px 12px;}
        .input-label { font-size: 11px; font-weight: 700; color: #666; text-transform: uppercase;}
        .ex-input { width: 100%; border: none; font-size: 20px; font-weight: 800; color: #111; outline: none; background: transparent;}
        
        .quick-stakes { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin-bottom: 20px;}
        .qs-btn { 
            background: white; border: 1px solid #CCC; border-radius: 4px; padding: 10px 0; font-weight: 700; font-size: 13px; color: #333; cursor: pointer;
        }
        .qs-btn:active { background: #E0E0E0; }
        
        .pl-box { display: flex; justify-content: space-between; background: white; padding: 15px; border-radius: 6px; border: 1px dashed #AAA; margin-bottom: 20px;}
        .profit-val { color: #2E7D32; font-weight: 800; font-size: 18px;}
        .liability-val { color: #D32F2F; font-weight: 800; font-size: 18px;}

        .place-bet-btn { width: 100%; padding: 14px; font-size: 16px; font-weight: 800; color: white; border: none; border-radius: 6px; text-transform: uppercase;}
        .place-bet-btn.back-theme { background: #1E88E5; }
        .place-bet-btn.lay-theme { background: #E53935; }

        /* Simple History Table */
        .history-container { padding: 10px; display: none;}
        .hist-table { width: 100%; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 5px rgba(0,0,0,0.1); text-align: center;}
        .hist-table thead { background: #2A3B4C; color: white; font-size: 12px;}
        .hist-table th { padding: 10px; font-weight: 700;}
        .hist-table td { padding: 12px 10px; font-size: 13px; font-weight: 600; border-bottom: 1px solid #EEE;}

        #snackbar {
            visibility: hidden; min-width: 250px; background-color: #333; color: #fff; text-align: center; border-radius: 6px; padding: 12px; position: fixed; z-index: 9999; left: 50%; bottom: 30px; transform: translateX(-50%); font-size: 13px; font-weight: 700; box-shadow: 0 4px 10px rgba(0,0,0,0.3); opacity: 0; transition: opacity 0.3s, bottom 0.3s;
        }
        #snackbar.show { visibility: visible; opacity: 1; bottom: 50px; }
    </style>
</head>
<body>

    <div class="ex-header">
        <a href="../index.php" style="color:white; text-decoration:none;"><i class="fas fa-chevron-left"></i></a>
        <div class="ex-logo"><?= htmlspecialchars($siteName) ?></div>
        <div class="ex-bal" id="headerBal">₹<?= number_format($walletBalance, 2) ?></div>
    </div>

    <div class="ex-tabs">
        <div class="ex-tab active" onclick="switchTab('live')" id="tab-live"><i class="fas fa-satellite-dish"></i> Live Matches</div>
        <div class="ex-tab" onclick="switchTab('history')" id="tab-history"><i class="fas fa-list-alt"></i> My Bets</div>
    </div>

    <div id="liveContainer">
        <div id="loader" style="text-align:center; padding: 50px; color:#888;">
            <i class="fas fa-spinner fa-spin" style="font-size: 35px; margin-bottom: 15px; color: #1E88E5;"></i>
            <div style="font-weight:700;">Loading Markets...</div>
        </div>
        <div id="matchesWrapper"></div>
    </div>

    <div id="historyContainer" class="history-container">
        <table class="hist-table">
            <thead>
                <tr>
                    <th style="text-align:left;">Runner</th>
                    <th>Type</th>
                    <th>Stake</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody id="historyBody"></tbody>
        </table>
    </div>

    <div id="snackbar">Message here</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);">Place Bet</div>
                <div id="slipRunnerName" style="font-size:16px;">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-arrow-up text-success"></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-arrow-down text-danger"></i></div>
                    <div class="liability-val" id="slipLiability">-₹100.00</div>
                </div>
            </div>

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

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

        window.alert = function(msg) { showToast(msg); };

        let currentType = ''; let currentMatchId = ''; let currentRunner = '';
        let liveMatchesData = []; 
        let isFirstLoad = true;

        // 🔥 Function jo Match Details page par redirect karega
        function viewMatchDetails(matchId) {
            window.location.href = `match_details.php?id=${matchId}`;
        }

        function loadLiveMatches() {
            fetch('../getlivecricket.php').then(r=>r.json()).then(res => {
                if(isFirstLoad) {
                    document.getElementById('loader').style.display = 'none';
                    isFirstLoad = false;
                }
                if(res.success && res.data.length > 0) {
                    liveMatchesData = res.data;
                    renderMatches();
                } else { 
                    document.getElementById('matchesWrapper').innerHTML = '<div style="padding:40px; text-align:center; font-weight:700; color:#888;">No Live Matches Available</div>'; 
                }
            }).catch(e => console.log("Silent update ongoing..."));
        }
        
        loadLiveMatches();
        setInterval(loadLiveMatches, 3000); 

        function renderMatches() {
            let html = '';
            let now = new Date().getTime();

            liveMatchesData.forEach(m => {
                let lockedClass = m.is_locked == 1 ? 'is-locked' : '';
                let timerBadgeHtml = `<span class="live-pulse"><i class="fas fa-circle"></i> ${m.status}</span>`;
                
                if (m.start_time) {
                    let matchTime = new Date(m.start_time).getTime();
                    let diff = matchTime - now;

                    if (diff > 0) {
                        let d = Math.floor(diff / (1000 * 60 * 60 * 24));
                        let h = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                        let mnts = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
                        let s = Math.floor((diff % (1000 * 60)) / 1000);
                        timerBadgeHtml = `<span class="future-timer"><i class="fas fa-clock"></i> Starts in: ${d}d ${h}h ${mnts}m ${s}s</span>`;
                    }
                }

                html += `
                <div class="match-card ${lockedClass}">
                    <div class="m-header">
                        <span><i class="fas fa-trophy text-warning"></i> Match Odds</span>
                        ${timerBadgeHtml}
                    </div>
                    
                    <div class="score-board" onclick="viewMatchDetails('${m.id}')">
                        <i class="fas fa-info-circle view-info-icon"></i>
                        <div class="team-name-big" style="text-align:right;">${m.team1.name}</div>
                        <div class="score-text">${m.score}</div>
                        <div class="team-name-big" style="text-align:left;">${m.team2.name}</div>
                    </div>
                    
                    <div class="market-body">
                        <div class="market-suspended"><div class="suspend-text"><i class="fas fa-lock"></i> Suspended</div></div>
                        
                        <div class="market-header">
                            <div style="color:#1E88E5;">BACK</div>
                            <div style="color:#E53935;">LAY</div>
                        </div>

                        <div class="runner-row">
                            <div class="runner-name" onclick="viewMatchDetails('${m.id}')" title="Click to view match details">
                                ${m.team1.name}
                            </div>
                            <div class="odd-box back-box" onclick="openSlip('${m.id}', '${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.id}', '${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" onclick="viewMatchDetails('${m.id}')" title="Click to view match details">
                                ${m.team2.name}
                            </div>
                            <div class="odd-box back-box" onclick="openSlip('${m.id}', '${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.id}', '${m.team2.name}', ${m.team2.lay}, 'lay')">
                                <span class="odd-val">${m.team2.lay}</span><span class="odd-size">10K</span>
                            </div>
                        </div>
                    </div>
                </div>`;
            });
            
            let wrapper = document.getElementById('matchesWrapper');
            if(wrapper.innerHTML !== html) { wrapper.innerHTML = html; }
        }

        setInterval(() => { if (document.getElementById('liveContainer').style.display !== 'none') { renderMatches(); } }, 1000);

        function openSlip(matchId, runner, odds, type) {
            if(odds <= 0 || isNaN(odds)) return; 
            currentMatchId = matchId; 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') {
                let profit = stake * (odds - 1);
                document.getElementById('slipProfit').innerText = '₹' + profit.toFixed(2);
                document.getElementById('slipLiability').innerText = '-₹' + stake.toFixed(2);
            } else {
                let liability = stake * (odds - 1);
                document.getElementById('slipProfit').innerText = '₹' + stake.toFixed(2);
                document.getElementById('slipLiability').innerText = '-₹' + liability.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', currentMatchId); 
            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(); loadMyBets();
                } else { showToast(res.message); }
            } catch(e) { showToast("Connection Error. Try Again."); }
            
            btn.innerText = "PLACE BET"; btn.disabled = false;
        }

        function switchTab(tab) {
            document.getElementById('tab-live').classList.remove('active'); document.getElementById('tab-history').classList.remove('active');
            document.getElementById('liveContainer').style.display = 'none'; document.getElementById('historyContainer').style.display = 'none';

            if(tab === 'live') { document.getElementById('tab-live').classList.add('active'); document.getElementById('liveContainer').style.display = 'block'; } 
            else { document.getElementById('tab-history').classList.add('active'); document.getElementById('historyContainer').style.display = 'block'; loadMyBets(); }
        }

        function loadMyBets() {
            fetch('../getbethistory.php').then(r=>r.json()).then(res => {
                let html = '';
                if(res.success && res.data.length > 0) {
                    let cricketBets = res.data.filter(b => b.selection.includes('@'));
                    if(cricketBets.length > 0) {
                        cricketBets.forEach(b => {
                            let isBack = b.selection.includes('[BACK]');
                            let tColor = isBack ? '#1E88E5' : '#E53935';
                            let sColor = b.status === 'win' ? '#2E7D32' : (b.status === 'lose' ? '#D32F2F' : '#F39C12');
                            
                            html += `
                            <tr>
                                <td style="text-align:left;">
                                    <div style="font-weight:700; color:#111;">${b.selection.split(' [')[0]}</div>
                                    <div style="font-size:11px; color:#666; margin-top:3px;">${b.selection.split('@')[1]}</div>
                                </td>
                                <td><span style="background:${tColor}; color:white; padding:4px 8px; border-radius:4px; font-size:10px; font-weight:700;">${isBack?'BACK':'LAY'}</span></td>
                                <td style="font-weight:700; color:#111;">₹${b.amount}</td>
                                <td style="color:${sColor}; font-weight:800; text-transform:uppercase;">${b.status}</td>
                            </tr>`;
                        });
                    } else { html = '<tr><td colspan="4" style="padding:20px; color:#888;">No sports bets placed.</td></tr>'; }
                } else { html = '<tr><td colspan="4" style="padding:20px; color:#888;">No sports bets placed.</td></tr>'; }
                document.getElementById('historyBody').innerHTML = html;
            });
        }
    </script>
</body>
</html>