<?php
require_once 'config.php';

// Set timezone
date_default_timezone_set('Asia/Kolkata');

// Check if user wants to load all results
$load_all = isset($_GET['load_all']) && $_GET['load_all'] === 'true';

// Get current month and year for filtering
$current_month = date('m');
$current_year = date('Y');

// Fetch results grouped by date
$results = [];

if ($load_all) {
    // Load all results when requested
    $sql = "SELECT result_date, game, result_number FROM results ORDER BY result_date ASC";
    if ($res = mysqli_query($link, $sql)) {
        while ($row = mysqli_fetch_assoc($res)) {
            $date = date('d-m-Y', strtotime($row['result_date']));
            $results[$date][$row['game']] = $row['result_number'];
        }
    }
} else {
    // Default: filter by current month in ascending order
    $sql = "SELECT result_date, game, result_number FROM results 
            WHERE MONTH(result_date) = ? AND YEAR(result_date) = ? 
            ORDER BY result_date ASC";
            
    if ($stmt = mysqli_prepare($link, $sql)) {
        mysqli_stmt_bind_param($stmt, 'ii', $current_month, $current_year);
        mysqli_stmt_execute($stmt);
        $res = mysqli_stmt_get_result($stmt);
        
        while ($row = mysqli_fetch_assoc($res)) {
            $date = date('d-m-Y', strtotime($row['result_date']));
            $results[$date][$row['game']] = $row['result_number'];
        }
        mysqli_stmt_close($stmt);
    }
}

// Get today's date for highlighting
$today = date('d-m-Y');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Live Results - Shubank | Real-time Market Results</title>
    <meta name="description" content="Check live results for Disawar, Delhi Bazaar, Shree Ganesh, Faridabad, Ghaziabad, Radhey-Radhey & Gali markets. Updated in real-time with accurate data.">
    <meta name="keywords" content="Shubank results, live results, disawar result, delhi bazaar result, market results">
    <link rel="stylesheet" href="style.css">
</head>
<body>

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

    <!-- Hero Section -->
    <section class="results-hero-section">
        <div class="container">
            <div class="results-hero-content">
                <div class="eyebrow">
                    <span>📊</span>
                    Live Results
                </div>
                <h1>Real-Time Market Results</h1>
                <p>Get instant access to accurate results from all major markets. Updated in real-time with transparent and verified data from Disawar, Delhi Bazaar, Shree Ganesh, Faridabad, Ghaziabad, Radhey-Radhey, and Gali.</p>
            </div>
        </div>
    </section>

    <!-- Quick Stats Section -->
    <section class="results-stats-section">
        <div class="container">
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon">🎯</div>
                    <div class="stat-info">
                        <div class="stat-number">7</div>
                        <div class="stat-label">Live Markets</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">📊</div>
                    <div class="stat-info">
                        <div class="stat-number">Real-Time</div>
                        <div class="stat-label">Updates</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">🔄</div>
                    <div class="stat-info">
                        <div class="stat-number">24/7</div>
                        <div class="stat-label">Data Access</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">✅</div>
                    <div class="stat-info">
                        <div class="stat-number">100%</div>
                        <div class="stat-label">Accurate</div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- Main Results Section -->
    <section class="main-results-section">
        <div class="container">
            <div class="section-header">
                <h2>🏆 Complete Results Chart</h2>
                <p>Historical data and latest results from all markets - your comprehensive results dashboard</p>
            </div>

            <!-- Filter Options -->
            <div class="results-filter">
                <div class="filter-buttons">
                     <button class="filter-btn <?php echo !$load_all ? 'active' : ''; ?>" data-filter="month">This Month</button>
                    <button class="filter-btn" data-filter="today">Today's Results</button>
                    <button class="filter-btn" data-filter="week">This Week</button>
                   <button class="filter-btn <?php echo $load_all ? 'active' : ''; ?>" data-filter="all">All Results</button>
                </div>
                <div class="search-box">
                    <select id="monthSearch" class="search-input">
                        <option value="">All Months</option>
                        <?php
                        // Dynamic month generation - automatically shows current year's months
                        // When year changes (e.g., 2025 → 2026), this will automatically update
                        $current_year = date('Y'); // Gets current year dynamically
                        $current_month_year = date('m-Y'); // Current month-year for pre-selection
                        
                        // Generate all 12 months for the current year
                        for ($month = 1; $month <= 12; $month++) {
                            // Create month name with current year (e.g., "January 2025", "February 2025")
                            $month_name = date('F Y', mktime(0, 0, 0, $month, 1, $current_year));
                            $month_value = str_pad($month, 2, '0', STR_PAD_LEFT) . '-' . $current_year;
                            
                            // Pre-select current month
                            $selected = ($month_value === $current_month_year) ? 'selected' : '';
                            
                            echo '<option value="' . $month_value . '" ' . $selected . '>' . $month_name . '</option>';
                        }
                        ?>
                    </select>
                    <button class="search-btn" onclick="filterByMonth()">🔍 Filter</button>
                </div>
            </div>

            <!-- Results Table Container -->
            <div class="results-table-container">
                <div class="table-header">
                    <h3>📈 Shubank Results Chart</h3>
                    <div class="refresh-indicator">
                        <span class="live-dot"></span>
                        <span>Live Updates</span>
                    </div>
                </div>

                <!-- Desktop Table View -->
                <div class="desktop-table-view">
                    <div class="table-wrapper">
                        <table class="modern-results-table">
                            <thead>
                                <tr>
                                    <th class="date-column">📅 DATE</th>
                                    <th>DS<br><small>Disawar</small></th>
                                    <th>DB<br><small>Delhi Bazaar</small></th>
                                    <th>SG<br><small>Shree Ganesh</small></th>
                                    <th>FB<br><small>Faridabad</small></th>
                                    <th>GB<br><small>Ghaziabad</small></th>
                                    <th>GL<br><small>Gali</small></th>
                                    <th>RR<br><small>Radhey Radhey</small></th>
                                    
                                </tr>
                            </thead>
                            <tbody id="resultsTableBody">
                                <?php
                                $games = ['disawar', 'dl_bazaar', 'shri_ganesh', 'faridabad', 'ghaziabad', 'gali', 'radhey_radhey'];
                                foreach ($results as $date => $row) {
                                    $isToday = ($date === $today) ? 'today-row' : '';
                                    echo '<tr class="result-row ' . $isToday . '" data-date="' . $date . '">';
                                    echo '<td class="date-cell">';
                                    if ($date === $today) {
                                        echo '<span class="today-badge">Today</span>';
                                    }
                                    echo '<span class="date-text">' . $date . '</span>';
                                    echo '</td>';
                                    foreach ($games as $game) {
                                        $result = htmlspecialchars($row[$game] ?? '--');
                                        echo '<td class="result-cell">';
                                        echo '<span class="result-number">' . $result . '</span>';
                                        echo '</td>';
                                    }
                                    echo '</tr>';
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Mobile Card View -->
                <div class="mobile-card-view">
                    <?php foreach ($results as $date => $row): ?>
                    <div class="result-card <?php echo ($date === $today) ? 'today-card' : ''; ?>" data-date="<?php echo $date; ?>">
                        <div class="card-header">
                            <div class="card-date">
                                <?php if ($date === $today): ?>
                                    <span class="today-badge">Today</span>
                                <?php endif; ?>
                                <span class="date-text"><?php echo $date; ?></span>
                            </div>
                            <?php if ($date === $today): ?>
                                <div class="live-indicator">
                                    <span class="live-dot"></span>
                                    <span>Live</span>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="card-results">
                            <?php
                            $gameNames = [
                                'disawar' => 'Disawar',
                                'dl_bazaar' => 'Delhi Bazaar', 
                                'shri_ganesh' => 'Shree Ganesh',
                                'faridabad' => 'Faridabad',
                                'ghaziabad' => 'Ghaziabad',
                                'radhey_radhey' => 'Radhey Radhey',
                                'gali' => 'Gali'
                            ];
                            foreach ($games as $game):
                            ?>
                            <div class="result-item">
                                <span class="game-name"><?php echo $gameNames[$game]; ?></span>
                                <span class="result-value"><?php echo htmlspecialchars($row[$game] ?? '--'); ?></span>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Load More Button -->
            <?php if (!$load_all): ?>
            <div class="load-more-section">
                <button class="load-more-btn">📊 Load All Results</button>
                <p class="results-note">Showing current month's results. Click to load all historical data.</p>
            </div>
            <?php else: ?>
            <div class="load-more-section">
                <div class="all-loaded-message">
                    <p class="results-note">✅ All historical results loaded. <a href="<?php echo $_SERVER['PHP_SELF']; ?>" style="color: #17a2b8; text-decoration: none;">← Back to current month</a></p>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </section>

    <!-- Features Section -->
    <section class="results-features-section">
        <div class="container">
            <div class="features-grid">
                <div class="feature-item">
                    <div class="feature-icon">⚡</div>
                    <div class="feature-text">Real-Time Updates</div>
                </div>
                <div class="feature-item">
                    <div class="feature-icon">📊</div>
                    <div class="feature-text">Complete Historical Data</div>
                </div>
                <div class="feature-item">
                    <div class="feature-icon">📱</div>
                    <div class="feature-text">Mobile Optimized View</div>
                </div>
                <div class="feature-item">
                    <div class="feature-icon">🔍</div>
                    <div class="feature-text">Advanced Search & Filter</div>
                </div>
            </div>
        </div>
    </section>

    <!-- Custom Styles for Results Page -->
    <style>
    /* Results Page Specific Styles */
    .results-hero-section {
        background: linear-gradient(135deg, #005c97 0%, #17a2b8 50%, #ffd600 100%);
        padding: 80px 0 60px 0;
        color: white;
        position: relative;
        overflow: hidden;
    }

    .results-hero-section::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: url('images/shubank-bg.png') center/cover no-repeat;
        opacity: 0.1;
        z-index: 1;
    }

    .results-hero-content {
        text-align: center;
        position: relative;
        z-index: 2;
        max-width: 800px;
        margin: 0 auto;
    }

    .results-hero-content h1 {
        font-size: 3rem;
        font-weight: 800;
        margin: 20px 0;
        text-shadow: 0 2px 8px rgba(0,0,0,0.2);
    }

    .results-hero-content p {
        font-size: 1.2rem;
        line-height: 1.6;
        opacity: 0.95;
        margin: 0;
    }

    /* Stats Section */
    .results-stats-section {
        padding: 60px 0;
        background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
    }

    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 24px;
        max-width: 1200px;
        margin: 0 auto;
        padding: 0 20px;
    }

    .stat-card {
        background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
        border-radius: 16px;
        padding: 32px 24px;
        box-shadow: 0 4px 20px rgba(0, 92, 151, 0.08);
        border: 1px solid rgba(23, 162, 184, 0.1);
        display: flex;
        align-items: center;
        gap: 20px;
        transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        position: relative;
        overflow: hidden;
    }

    .stat-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: linear-gradient(90deg, #005c97 0%, #17a2b8 50%, #ffd600 100%);
        transform: scaleX(0);
        transform-origin: left;
        transition: transform 0.4s ease;
    }

    .stat-card:hover::before {
        transform: scaleX(1);
    }

    .stat-card:hover {
        transform: translateY(-8px);
        box-shadow: 0 12px 40px rgba(0, 92, 151, 0.15);
        border-color: rgba(23, 162, 184, 0.2);
    }

    .stat-icon {
        background: linear-gradient(135deg, #17a2b8 0%, #ffd600 100%);
        width: 64px;
        height: 64px;
        border-radius: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.8rem;
        box-shadow: 0 4px 16px rgba(23, 162, 184, 0.3);
        transition: all 0.3s ease;
        flex-shrink: 0;
    }

    .stat-card:hover .stat-icon {
        transform: rotate(5deg) scale(1.1);
        box-shadow: 0 6px 24px rgba(23, 162, 184, 0.4);
    }

    .stat-info {
        flex: 1;
        min-width: 0;
    }

    .stat-number {
        font-size: 2.2rem;
        font-weight: 800;
        color: #005c97;
        line-height: 1.1;
        margin-bottom: 4px;
        background: linear-gradient(135deg, #005c97 0%, #17a2b8 100%);
        background-clip: text;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        text-shadow: 0 2px 8px rgba(0, 92, 151, 0.1);
    }

    .stat-label {
        font-size: 1rem;
        font-weight: 600;
        color: #64748b;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        line-height: 1.2;
    }

    /* Main Results Section */
    .main-results-section {
        padding: 80px 0;
        background: white;
    }

    .section-header {
        text-align: center;
        margin-bottom: 60px;
    }

    .section-header h2 {
        font-size: 2.5rem;
        color: #005c97;
        margin-bottom: 16px;
        font-weight: 700;
    }

    .section-header p {
        font-size: 1.2rem;
        color: #64748b;
        max-width: 600px;
        margin: 0 auto;
    }

    /* Filter Section */
    .results-filter {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 40px;
        flex-wrap: wrap;
        gap: 20px;
    }

    .filter-buttons {
        display: flex;
        gap: 12px;
        flex-wrap: wrap;
    }

    .filter-btn {
        padding: 8px 16px;
        border: 2px solid #e2e8f0;
        background: white;
        color: #64748b;
        border-radius: 8px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .filter-btn.active,
    .filter-btn:hover {
        background: #17a2b8;
        color: white;
        border-color: #17a2b8;
    }

    .search-box {
        display: flex;
        gap: 8px;
        align-items: center;
    }

    .search-input {
        padding: 8px 12px;
        border: 2px solid #e2e8f0;
        border-radius: 8px;
        font-size: 1rem;
        width: 200px;
        background: white;
        cursor: pointer;
    }
    
    .search-input:focus {
        outline: none;
        border-color: #17a2b8;
        box-shadow: 0 0 0 3px rgba(23, 162, 184, 0.1);
    }

    .search-btn {
        padding: 8px 12px;
        background: #17a2b8;
        color: white;
        border: none;
        border-radius: 8px;
        cursor: pointer;
        font-size: 1rem;
    }

    /* Results Table Container */
    .results-table-container {
        background: white;
        border-radius: 16px;
        box-shadow: 0 8px 32px rgba(0,0,0,0.1);
        overflow: hidden;
        margin-bottom: 40px;
    }

    .table-header {
        background: linear-gradient(135deg, #005c97 0%, #17a2b8 100%);
        color: white;
        padding: 20px 24px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .table-header h3 {
        margin: 0;
        font-size: 1.3rem;
        font-weight: 700;
    }

    .refresh-indicator {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 0.9rem;
    }

    .live-dot {
        width: 8px;
        height: 8px;
        background: #22c55e;
        border-radius: 50%;
        animation: pulse 2s infinite;
    }

    /* Desktop Table */
    .desktop-table-view {
        display: block;
    }

    .table-wrapper {
        overflow-x: auto;
    }

    .modern-results-table {
        width: 100%;
        border-collapse: collapse;
        min-width: 800px;
    }

    .modern-results-table th {
        background: #ffd600;
        color: #005c97;
        padding: 16px 12px;
        text-align: center;
        font-weight: 700;
        font-size: 0.9rem;
    }

    .modern-results-table th small {
        display: block;
        font-size: 0.75rem;
        opacity: 0.8;
        margin-top: 2px;
    }

    .modern-results-table td {
        padding: 12px;
        text-align: center;
        border-bottom: 1px solid #e2e8f0;
        font-weight: 600;
    }

    .date-column {
        min-width: 120px;
    }

    .date-cell {
        background: rgba(23,162,184,0.05);
        position: relative;
    }

    .today-badge {
        background: #22c55e;
        color: white;
        padding: 2px 8px;
        border-radius: 12px;
        font-size: 0.7rem;
        font-weight: 700;
        display: block;
        margin-bottom: 4px;
    }

    .date-text {
        font-weight: 700;
        color: #005c97;
    }

    .result-cell {
        font-size: 1.1rem;
    }

    .result-number {
        background: linear-gradient(135deg, #17a2b8 0%, #ffd600 100%);
        color: #005c97;
        padding: 4px 8px;
        border-radius: 6px;
        font-weight: 700;
        display: inline-block;
        min-width: 30px;
    }

    .today-row {
        background: rgba(34,197,94,0.05);
    }

    .today-row:hover {
        background: rgba(34,197,94,0.1);
    }

    .modern-results-table tbody tr:hover {
        background: rgba(23,162,184,0.05);
    }

    /* Mobile Card View */
    .mobile-card-view {
        display: none;
    }

    .result-card {
        background: white;
        border: 1px solid #e2e8f0;
        border-radius: 12px;
        margin-bottom: 16px;
        overflow: hidden;
        transition: transform 0.3s ease, box-shadow 0.3s ease;
    }

    .result-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(23,162,184,0.1);
    }

    .today-card {
        border-color: #22c55e;
        box-shadow: 0 0 16px rgba(34,197,94,0.2);
    }

    .card-header {
        background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
        padding: 12px 16px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #e2e8f0;
    }

    .card-date {
        display: flex;
        flex-direction: column;
        gap: 4px;
    }

    .live-indicator {
        display: flex;
        align-items: center;
        gap: 6px;
        color: #22c55e;
        font-size: 0.8rem;
        font-weight: 600;
    }

    .card-results {
        padding: 16px;
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 12px;
    }

    .result-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px;
        background: rgba(23,162,184,0.05);
        border-radius: 8px;
    }

    .game-name {
        font-size: 0.85rem;
        color: #64748b;
        font-weight: 600;
    }

    .result-value {
        font-weight: 700;
        color: #005c97;
        font-size: 1rem;
        background: #ffd600;
        padding: 2px 8px;
        border-radius: 4px;
    }

    /* Load More Section */
    .load-more-section {
        text-align: center;
        margin-top: 40px;
    }

    .load-more-btn {
        background: linear-gradient(135deg, #17a2b8 0%, #ffd600 100%);
        color: #005c97;
        padding: 12px 24px;
        border: none;
        border-radius: 8px;
        font-weight: 700;
        font-size: 1rem;
        cursor: pointer;
        transition: transform 0.3s ease;
    }

    .load-more-btn:hover {
        transform: translateY(-2px);
    }

    .results-note {
        margin-top: 12px;
        color: #64748b;
        font-size: 0.9rem;
    }

    /* Features Section */
    .results-features-section {
        padding: 60px 0;
        background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
    }

    /* Responsive Design */
    @media (max-width: 1024px) {
        .results-hero-content h1 {
            font-size: 2.5rem;
        }
        
        .modern-results-table {
            min-width: 700px;
        }
        
        .section-header h2 {
            font-size: 2rem;
        }

        .stats-grid {
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 20px;
        }

        .stat-card {
            padding: 28px 20px;
        }

        .stat-icon {
            width: 56px;
            height: 56px;
            font-size: 1.6rem;
        }

        .stat-number {
            font-size: 2rem;
        }
    }

    @media (max-width: 768px) {
        .results-hero-section {
            padding: 60px 0 40px 0;
        }
        
        .results-hero-content h1 {
            font-size: 2rem;
        }
        
        .main-results-section {
            padding: 60px 0;
        }
        
        .results-filter {
            flex-direction: column;
            align-items: stretch;
        }
        
        .filter-buttons {
            justify-content: center;
        }
        
        .search-box {
            justify-content: center;
        }
        
        .search-input {
            width: 250px;
            font-size: 0.9rem;
        }
        
        .desktop-table-view {
            display: none;
        }
        
        .mobile-card-view {
            display: block;
        }
        
        .card-results {
            grid-template-columns: 1fr;
            gap: 8px;
        }

        .stats-grid {
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 16px;
            padding: 0 16px;
        }

        .stat-card {
            padding: 24px 20px;
            gap: 16px;
        }

        .stat-icon {
            width: 52px;
            height: 52px;
            font-size: 1.5rem;
        }

        .stat-number {
            font-size: 1.8rem;
        }

        .stat-label {
            font-size: 0.9rem;
        }
    }

    @media (max-width: 480px) {
        .results-hero-section,
        .results-stats-section,
        .main-results-section,
        .results-features-section {
            padding: 40px 0;
        }
        
        .results-hero-content h1 {
            font-size: 1.8rem;
        }
        
        .section-header h2 {
            font-size: 1.8rem;
        }
        
        .filter-btn {
            padding: 6px 12px;
            font-size: 0.9rem;
        }
        
        .search-input {
            width: 180px;
            font-size: 0.85rem;
        }
        
        .table-header {
            padding: 16px;
            flex-direction: column;
            gap: 8px;
            text-align: center;
        }
        
        .results-hero-content p,
        .section-header p {
            font-size: 1rem;
        }

        .stats-grid {
            grid-template-columns: 1fr;
            gap: 12px;
            padding: 0 12px;
        }

        .stat-card {
            padding: 20px 16px;
            gap: 12px;
            flex-direction: column;
            text-align: center;
        }

        .stat-icon {
            width: 48px;
            height: 48px;
            font-size: 1.4rem;
            margin: 0 auto;
        }

        .stat-number {
            font-size: 1.6rem;
        }

        .stat-label {
            font-size: 0.85rem;
        }
    }

    /* Animation for pulse effect */
    @keyframes pulse {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.5; }
    }
    </style>

    <!-- Enhanced JavaScript -->
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Check if all data is loaded
        const urlParams = new URLSearchParams(window.location.search);
        const allDataLoaded = urlParams.get('load_all') === 'true';
        
        // Filter functionality
        const filterBtns = document.querySelectorAll('.filter-btn');
        const resultRows = document.querySelectorAll('.result-row');
        const resultCards = document.querySelectorAll('.result-card');
        
        filterBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                // Reset month search when using other filters
                const monthSearch = document.getElementById('monthSearch');
                if (monthSearch) {
                    monthSearch.value = '';
                }
                
                // If clicking "All Results" and not all data loaded, redirect to load all
                if (this.dataset.filter === 'all' && !allDataLoaded) {
                    window.location.href = window.location.pathname + '?load_all=true';
                    return;
                }
                
                // If clicking "This Month" and all data is loaded, redirect to default view
                if (this.dataset.filter === 'month' && allDataLoaded) {
                    window.location.href = window.location.pathname;
                    return;
                }
                
                // Remove active class from all buttons
                filterBtns.forEach(b => b.classList.remove('active'));
                this.classList.add('active');
                
                const filter = this.dataset.filter;
                filterResults(filter);
            });
        });
        
        function filterResults(filter) {
            const today = new Date();
            const todayStr = formatDate(today);
            
            // Remove any "no results" message when using filter buttons
            removeNoResultsMessage();
            
            resultRows.forEach(row => {
                const rowDate = row.dataset.date;
                let show = true;
                
                switch(filter) {
                    case 'today':
                        show = rowDate === todayStr;
                        break;
                    case 'week':
                        const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
                        show = isDateInRange(rowDate, weekAgo, today);
                        break;
                    case 'month':
                        const monthAgo = new Date(today.getFullYear(), today.getMonth() - 1, today.getDate());
                        show = isDateInRange(rowDate, monthAgo, today);
                        break;
                    default:
                        show = true;
                }
                
                row.style.display = show ? '' : 'none';
            });
            
            resultCards.forEach(card => {
                const cardDate = card.dataset.date;
                let show = true;
                
                switch(filter) {
                    case 'today':
                        show = cardDate === todayStr;
                        break;
                    case 'week':
                        const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
                        show = isDateInRange(cardDate, weekAgo, today);
                        break;
                    case 'month':
                        const monthAgo = new Date(today.getFullYear(), today.getMonth() - 1, today.getDate());
                        show = isDateInRange(cardDate, monthAgo, today);
                        break;
                    default:
                        show = true;
                }
                
                card.style.display = show ? '' : 'none';
            });
        }
        
        function formatDate(date) {
            const day = String(date.getDate()).padStart(2, '0');
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const year = date.getFullYear();
            return `${day}-${month}-${year}`;
        }
        
        function isDateInRange(dateStr, startDate, endDate) {
            const [day, month, year] = dateStr.split('-');
            const date = new Date(year, month - 1, day);
            return date >= startDate && date <= endDate;
        }
        
        // Month search functionality
        const monthSearch = document.getElementById('monthSearch');
        
        // Add global function for month filtering
        window.filterByMonth = function() {
            const selectedMonth = monthSearch.value;
            
            // Reset other filter buttons when using month search
            if (selectedMonth !== '') {
                filterBtns.forEach(b => b.classList.remove('active'));
            }
            
            if (selectedMonth === '') {
                // Show all results and restore default filter state
                resultRows.forEach(row => {
                    row.style.display = '';
                });
                resultCards.forEach(card => {
                    card.style.display = '';
                });
                
                // Restore default filter button state
                const defaultFilter = allDataLoaded ? 'all' : 'month';
                filterBtns.forEach(btn => {
                    if (btn.dataset.filter === defaultFilter) {
                        btn.classList.add('active');
                    }
                });
                
                // Remove any "no results" message
                removeNoResultsMessage();
                return;
            }
            
            const [month, year] = selectedMonth.split('-');
            let hasResults = false;
            
            resultRows.forEach(row => {
                const rowDate = row.dataset.date; // DD-MM-YYYY format
                const [day, rowMonth, rowYear] = rowDate.split('-');
                
                const matches = (rowMonth === month && rowYear === year);
                row.style.display = matches ? '' : 'none';
                if (matches) hasResults = true;
            });
            
            resultCards.forEach(card => {
                const cardDate = card.dataset.date; // DD-MM-YYYY format
                const [day, cardMonth, cardYear] = cardDate.split('-');
                
                const matches = (cardMonth === month && cardYear === year);
                card.style.display = matches ? '' : 'none';
                if (matches) hasResults = true;
            });
            
            // Show message if no results found for selected month
            if (!hasResults) {
                showNoResultsMessage(month, year);
            } else {
                removeNoResultsMessage();
            }
        };
        
        // Helper function to show "no results" message
        function showNoResultsMessage(month, year) {
            removeNoResultsMessage(); // Remove any existing message
            
            const monthName = new Date(year, month - 1, 1).toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
            const messageHtml = `
                <div id="noResultsMessage" style="
                    text-align: center;
                    padding: 40px 20px;
                    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
                    border-radius: 12px;
                    margin: 20px 0;
                    border: 2px dashed #cbd5e1;
                ">
                    <div style="font-size: 3rem; margin-bottom: 16px;">📅</div>
                    <h3 style="color: #64748b; margin-bottom: 8px;">No Results Found</h3>
                    <p style="color: #94a3b8; margin: 0;">No results available for <strong>${monthName}</strong></p>
                    <p style="color: #94a3b8; font-size: 0.9rem; margin-top: 8px;">Try selecting a different month or use "All Months" to see all available data.</p>
                </div>
            `;
            
            // Insert message after the table container
            const tableContainer = document.querySelector('.results-table-container');
            if (tableContainer) {
                tableContainer.insertAdjacentHTML('afterend', messageHtml);
            }
        }
        
        // Helper function to remove "no results" message
        function removeNoResultsMessage() {
            const existingMessage = document.getElementById('noResultsMessage');
            if (existingMessage) {
                existingMessage.remove();
            }
        }
        
        // Auto-filter when month selection changes
        monthSearch.addEventListener('change', window.filterByMonth);
        
        // Load more functionality
        const loadMoreBtn = document.querySelector('.load-more-btn');
        
        if (loadMoreBtn && !allDataLoaded) {
            loadMoreBtn.addEventListener('click', function() {
                // Show loading state
                this.textContent = '⏳ Loading All Results...';
                this.disabled = true;
                
                // Redirect to load all results
                setTimeout(() => {
                    window.location.href = window.location.pathname + '?load_all=true';
                }, 500);
            });
        }
        
        // Auto refresh every 60 seconds
        setInterval(function() {
            // In a real application, this would fetch new data
            console.log('Auto-refreshing results...');
        }, 60000);
    });
    </script>

    <?php include 'footer.php'; ?>
</body>
</html>