<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();

// Check if staff is logged in
if (!isset($_SESSION['email'])) {
    header("location:../index.php");
    exit();
}

// Include config
include "../include/config.php";

$staff_email = $_SESSION['email'];
$staff_name = $_SESSION['staffname'] ?? 'Staff';

// Handle Excel export
if (isset($_POST['export_excel'])) {
    // Get filter values
    $filter_program = mysqli_real_escape_string($conn, $_POST['program']);
    $filter_intake = mysqli_real_escape_string($conn, $_POST['intake']);
    $filter_year = mysqli_real_escape_string($conn, $_POST['year']);
    $filter_course = mysqli_real_escape_string($conn, $_POST['course']);
    
    // Build WHERE conditions
    $where_conditions = ["1"];
    
    if (!empty($filter_program) && $filter_program != 'all') {
        $where_conditions[] = "s.program = '$filter_program'";
    }
    
    if (!empty($filter_intake) && $filter_intake != 'all') {
        $where_conditions[] = "r.intake = '$filter_intake'";
    }
    
    if (!empty($filter_year) && $filter_year != 'all') {
        $where_conditions[] = "r.year = '$filter_year'";
    }
    
    if (!empty($filter_course) && $filter_course != 'all') {
        $where_conditions[] = "r.course = '$filter_course'";
    }
    
    $where_sql = implode(' AND ', $where_conditions);
    
    // Query to get results with student details
    $query = "SELECT 
                r.id,
                r.studentid,
                CONCAT(s.firstname, ' ', s.surname) AS student_name,
                s.program,
                s.intake AS student_intake,
                r.course,
                r.term,
                r.year,
                r.intake AS result_intake,
                r.ca,
                r.ca1,
                r.ca2,
                r.exam,
                r.email,
                CASE 
                    WHEN r.exam >= 40 THEN 'PASS'
                    ELSE 'FAIL'
                END AS status,
                (r.ca + r.ca1 + r.ca2 + r.exam) AS total_score,
                ROUND(((r.ca + r.ca1 + r.ca2 + r.exam) / 100) * 100, 2) AS percentage
              FROM results r
              LEFT JOIN students s ON r.studentid = s.studentid
              WHERE $where_sql
              ORDER BY s.program, r.intake, r.year, r.course, r.studentid";
    
    $result = mysqli_query($conn, $query);
    
    if (!$result) {
        die("Query failed: " . mysqli_error($conn));
    }
    
    // Set headers for Excel download
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="student_results_' . date('Y-m-d') . '.xls"');
    
    // Start Excel content
    echo '<!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Student Results Export</title>
        <style>
            table { border-collapse: collapse; width: 100%; }
            th { background-color: #202342; color: white; font-weight: bold; padding: 8px; border: 1px solid #ddd; }
            td { padding: 6px; border: 1px solid #ddd; }
            .pass { background-color: #d4edda; }
            .fail { background-color: #f8d7da; }
        </style>
    </head>
    <body>';
    
    echo '<h2>Student Results Export</h2>';
    echo '<h4>Generated on: ' . date('Y-m-d H:i:s') . '</h4>';
    
    if (!empty($filter_program) && $filter_program != 'all') {
        echo '<p><strong>Program:</strong> ' . htmlspecialchars($filter_program) . '</p>';
    }
    if (!empty($filter_intake) && $filter_intake != 'all') {
        echo '<p><strong>Intake:</strong> ' . htmlspecialchars($filter_intake) . '</p>';
    }
    if (!empty($filter_year) && $filter_year != 'all') {
        echo '<p><strong>Year:</strong> ' . htmlspecialchars($filter_year) . '</p>';
    }
    if (!empty($filter_course) && $filter_course != 'all') {
        echo '<p><strong>Course:</strong> ' . htmlspecialchars($filter_course) . '</p>';
    }
    
    echo '<table border="1">
        <thead>
            <tr>
                <th>No.</th>
                <th>Student ID</th>
                <th>Student Name</th>
                <th>Program</th>
                <th>Intake</th>
                <th>Course</th>
                <th>Term</th>
                <th>Year</th>
                <th>CA</th>
                <th>CA1</th>
                <th>CA2</th>
                <th>Exam</th>
                <th>Total</th>
                <th>Percentage</th>
                <th>Status</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>';
    
    $counter = 1;
    $total_students = 0;
    $pass_count = 0;
    $fail_count = 0;
    
    while ($row = mysqli_fetch_assoc($result)) {
        $status_class = ($row['exam'] >= 40) ? 'pass' : 'fail';
        if ($row['exam'] >= 40) $pass_count++;
        else $fail_count++;
        
        echo '<tr class="' . $status_class . '">
            <td>' . $counter . '</td>
            <td>' . htmlspecialchars($row['studentid']) . '</td>
            <td>' . htmlspecialchars($row['student_name']) . '</td>
            <td>' . htmlspecialchars($row['program']) . '</td>
            <td>' . htmlspecialchars($row['result_intake']) . '</td>
            <td>' . htmlspecialchars($row['course']) . '</td>
            <td>' . htmlspecialchars($row['term']) . '</td>
            <td>' . htmlspecialchars($row['year']) . '</td>
            <td>' . htmlspecialchars($row['ca']) . '</td>
            <td>' . htmlspecialchars($row['ca1']) . '</td>
            <td>' . htmlspecialchars($row['ca2']) . '</td>
            <td>' . htmlspecialchars($row['exam']) . '</td>
            <td>' . htmlspecialchars($row['total_score']) . '</td>
            <td>' . htmlspecialchars($row['percentage']) . '%</td>
            <td>' . htmlspecialchars($row['status']) . '</td>
            <td>' . htmlspecialchars($row['email']) . '</td>
        </tr>';
        
        $counter++;
        $total_students++;
    }
    
    echo '</tbody>
        <tfoot>
            <tr>
                <td colspan="16" style="text-align: right; font-weight: bold;">Total Students:</td>
                <td>' . $total_students . '</td>
            </tr>
            <tr>
                <td colspan="16" style="text-align: right; font-weight: bold;">Passed:</td>
                <td>' . $pass_count . '</td>
            </tr>
            <tr>
                <td colspan="16" style="text-align: right; font-weight: bold;">Failed:</td>
                <td>' . $fail_count . '</td>
            </tr>
            <tr>
                <td colspan="16" style="text-align: right; font-weight: bold;">Pass Rate:</td>
                <td>' . ($total_students > 0 ? round(($pass_count / $total_students) * 100, 2) : 0) . '%</td>
            </tr>
        </tfoot>
    </table>';
    
    echo '</body></html>';
    exit();
}

// Get filter values for display
$filter_program = $_GET['program'] ?? '';
$filter_intake = $_GET['intake'] ?? '';
$filter_year = $_GET['year'] ?? '';
$filter_course = $_GET['course'] ?? '';

// Get unique values for dropdowns
$programs_query = "SELECT DISTINCT program FROM students WHERE program IS NOT NULL AND program != '' ORDER BY program";
$programs_result = mysqli_query($conn, $programs_query);

$intakes_query = "SELECT DISTINCT intake FROM results WHERE intake IS NOT NULL AND intake != '' ORDER BY intake DESC";
$intakes_result = mysqli_query($conn, $intakes_query);

$years_query = "SELECT DISTINCT year FROM results WHERE year IS NOT NULL AND year != '' ORDER BY year DESC";
$years_result = mysqli_query($conn, $years_query);

$courses_query = "SELECT DISTINCT course FROM results WHERE course IS NOT NULL AND course != '' ORDER BY course";
$courses_result = mysqli_query($conn, $courses_query);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Export Student Results - Teaching Platform</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --primary: #202342;
            --secondary: #2c3e50;
            --success: #28a745;
            --info: #17a2b8;
            --warning: #ffc107;
            --danger: #dc3545;
        }
        
        body {
            font-family: Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            margin: 0;
            padding: 0;
        }
        
        .content {
            margin-left: 210px;
            padding: 20px;
            min-height: 100vh;
        }
        
        .glass-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        }
        
        .header-section {
            background: var(--primary);
            color: white;
            padding: 25px;
            border-radius: 15px;
            margin-bottom: 25px;
            position: relative;
            overflow: hidden;
        }
        
        .header-section::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"><path fill="rgba(255,255,255,0.1)" d="M0,96L48,112C96,128,192,160,288,160C384,160,480,128,576,112C672,96,768,96,864,112C960,128,1056,160,1152,160C1248,160,1344,128,1392,112L1440,96L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"></path></svg>');
            background-size: cover;
            opacity: 0.3;
        }
        
        .btn-primary {
            background: var(--primary) !important;
            border: none;
            padding: 10px 20px;
            border-radius: 8px;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(32, 35, 66, 0.3);
        }
        
        .btn-success {
            background: var(--success) !important;
            border: none;
        }
        
        .btn-excel {
            background: #1d6f42 !important;
            border: none;
            color: white !important;
        }
        
        .btn-excel:hover {
            background: #155d37 !important;
        }
        
        .filter-section {
            background: white;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 3px 15px rgba(0,0,0,0.08);
        }
        
        .filter-section h4 {
            color: var(--primary);
            margin-bottom: 20px;
            border-bottom: 2px solid var(--primary);
            padding-bottom: 10px;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 0.2rem rgba(32, 35, 66, 0.25);
        }
        
        .stats-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            margin-bottom: 20px;
            box-shadow: 0 3px 10px rgba(0,0,0,0.08);
            transition: all 0.3s;
        }
        
        .stats-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }
        
        .stats-number {
            font-size: 32px;
            font-weight: bold;
            color: var(--primary);
            margin: 10px 0;
        }
        
        .info-box {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin-top: 20px;
            border-left: 4px solid var(--info);
            box-shadow: 0 3px 10px rgba(0,0,0,0.08);
        }
        
        @media (max-width: 768px) {
            .content {
                margin-left: 0;
                padding: 15px;
            }
            
            .header-section {
                padding: 20px 15px;
            }
        }
    </style>
</head>
<body>
    <?php include "../include/nav.php"; ?>
    
    <div class="content">
        <div class="container-fluid">
            <!-- Header Section -->
            <div class="header-section">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <h1 class="mb-2"><i class="fas fa-file-excel me-2"></i>Export Student Results</h1>
                        <p class="mb-0">Export student results to Excel format with advanced filtering options. Welcome, <?php echo htmlspecialchars($staff_name); ?></p>
                    </div>
                    <div class="col-md-4 text-end">
                        <a href="results.php" class="btn btn-light">
                            <i class="fas fa-arrow-left me-2"></i>Back to Results
                        </a>
                    </div>
                </div>
            </div>

            <!-- Statistics Section -->
            <div class="row mb-4">
                <?php
                // Get statistics
                $total_students_query = "SELECT COUNT(DISTINCT studentid) as total FROM results";
                $total_students_result = mysqli_query($conn, $total_students_query);
                $total_students = $total_students_result ? mysqli_fetch_assoc($total_students_result)['total'] ?? 0 : 0;
                
                $total_results_query = "SELECT COUNT(*) as total FROM results";
                $total_results_result = mysqli_query($conn, $total_results_query);
                $total_results = $total_results_result ? mysqli_fetch_assoc($total_results_result)['total'] ?? 0 : 0;
                
                $pass_count_query = "SELECT COUNT(*) as passed FROM results WHERE exam >= 40";
                $pass_count_result = mysqli_query($conn, $pass_count_query);
                $passed_results = $pass_count_result ? mysqli_fetch_assoc($pass_count_result)['passed'] ?? 0 : 0;
                
                $fail_count_query = "SELECT COUNT(*) as failed FROM results WHERE exam < 40";
                $fail_count_result = mysqli_query($conn, $fail_count_query);
                $failed_results = $fail_count_result ? mysqli_fetch_assoc($fail_count_result)['failed'] ?? 0 : 0;
                ?>
                
                <div class="col-md-3">
                    <div class="stats-card">
                        <i class="fas fa-users fa-2x text-primary mb-2"></i>
                        <h5>Total Students</h5>
                        <div class="stats-number"><?php echo number_format($total_students); ?></div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stats-card">
                        <i class="fas fa-file-alt fa-2x text-info mb-2"></i>
                        <h5>Total Results</h5>
                        <div class="stats-number"><?php echo number_format($total_results); ?></div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stats-card">
                        <i class="fas fa-check-circle fa-2x text-success mb-2"></i>
                        <h5>Passed</h5>
                        <div class="stats-number"><?php echo number_format($passed_results); ?></div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stats-card">
                        <i class="fas fa-times-circle fa-2x text-danger mb-2"></i>
                        <h5>Failed</h5>
                        <div class="stats-number"><?php echo number_format($failed_results); ?></div>
                    </div>
                </div>
            </div>

            <!-- Filter Section -->
            <div class="filter-section">
                <h4><i class="fas fa-filter me-2"></i>Filter Results for Export</h4>
                <form method="POST" action="" id="exportForm">
                    <div class="row g-4">
                        <!-- Program Filter -->
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Program</label>
                            <select name="program" class="form-select form-select-lg">
                                <option value="all">All Programs</option>
                                <?php 
                                if ($programs_result && mysqli_num_rows($programs_result) > 0):
                                    while ($program = mysqli_fetch_assoc($programs_result)): 
                                ?>
                                    <option value="<?php echo htmlspecialchars($program['program']); ?>"
                                        <?php echo (isset($_POST['program']) && $_POST['program'] == $program['program']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($program['program']); ?>
                                    </option>
                                <?php 
                                    endwhile;
                                endif; 
                                ?>
                            </select>
                        </div>
                        
                        <!-- Intake Filter -->
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Intake</label>
                            <select name="intake" class="form-select form-select-lg">
                                <option value="all">All Intakes</option>
                                <?php 
                                if ($intakes_result && mysqli_num_rows($intakes_result) > 0):
                                    while ($intake = mysqli_fetch_assoc($intakes_result)): 
                                ?>
                                    <option value="<?php echo htmlspecialchars($intake['intake']); ?>"
                                        <?php echo (isset($_POST['intake']) && $_POST['intake'] == $intake['intake']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($intake['intake']); ?>
                                    </option>
                                <?php 
                                    endwhile;
                                endif; 
                                ?>
                            </select>
                        </div>
                        
                        <!-- Year Filter -->
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Academic Year</label>
                            <select name="year" class="form-select form-select-lg">
                                <option value="all">All Years</option>
                                <?php 
                                if ($years_result && mysqli_num_rows($years_result) > 0):
                                    while ($year = mysqli_fetch_assoc($years_result)): 
                                ?>
                                    <option value="<?php echo htmlspecialchars($year['year']); ?>"
                                        <?php echo (isset($_POST['year']) && $_POST['year'] == $year['year']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($year['year']); ?>
                                    </option>
                                <?php 
                                    endwhile;
                                endif; 
                                ?>
                            </select>
                        </div>
                        
                        <!-- Course Filter -->
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Course</label>
                            <select name="course" class="form-select form-select-lg">
                                <option value="all">All Courses</option>
                                <?php 
                                if ($courses_result && mysqli_num_rows($courses_result) > 0):
                                    while ($course = mysqli_fetch_assoc($courses_result)): 
                                ?>
                                    <option value="<?php echo htmlspecialchars($course['course']); ?>"
                                        <?php echo (isset($_POST['course']) && $_POST['course'] == $course['course']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($course['course']); ?>
                                    </option>
                                <?php 
                                    endwhile;
                                endif; 
                                ?>
                            </select>
                        </div>
                        
                        <!-- Export Options -->
                        <div class="col-12">
                            <div class="card mt-3">
                                <div class="card-header bg-light">
                                    <h5 class="mb-0"><i class="fas fa-cog me-2"></i>Export Options</h5>
                                </div>
                                <div class="card-body">
                                    <div class="form-check mb-2">
                                        <input class="form-check-input" type="checkbox" name="include_stats" id="includeStats" checked>
                                        <label class="form-check-label" for="includeStats">
                                            Include statistics and summary
                                        </label>
                                    </div>
                                    <div class="form-check mb-2">
                                        <input class="form-check-input" type="checkbox" name="color_coding" id="colorCoding" checked>
                                        <label class="form-check-label" for="colorCoding">
                                            Apply color coding for pass/fail status
                                        </label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="include_headers" id="includeHeaders" checked>
                                        <label class="form-check-label" for="includeHeaders">
                                            Include column headers
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Action Buttons -->
                        <div class="col-12 mt-4">
                            <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                <button type="button" class="btn btn-secondary btn-lg me-2" onclick="previewExport()">
                                    <i class="fas fa-eye me-2"></i>Preview Export
                                </button>
                                <button type="submit" name="export_excel" class="btn btn-excel btn-lg">
                                    <i class="fas fa-file-excel me-2"></i>Export to Excel
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>

            <!-- Information Section -->
            <div class="info-box">
                <h5><i class="fas fa-info-circle me-2"></i>Export Information</h5>
                <p class="mb-2"><strong>File Format:</strong> Microsoft Excel (.xls)</p>
                <p class="mb-2"><strong>Columns Included:</strong> Student ID, Name, Program, Intake, Course, Term, Year, CA, CA1, CA2, Exam, Total, Percentage, Status, Email</p>
                <p class="mb-2"><strong>Filtering:</strong> You can filter by any combination of Program, Intake, Year, and Course</p>
                <p class="mb-0"><strong>Note:</strong> The export file will automatically download when you click "Export to Excel". Make sure pop-ups are not blocked.</p>
            </div>

            <!-- Preview Section (Hidden by default) -->
            <div class="filter-section mt-4" id="previewSection" style="display: none;">
                <h4><i class="fas fa-eye me-2"></i>Export Preview</h4>
                <div class="table-responsive">
                    <table class="table table-bordered table-striped" id="previewTable">
                        <thead class="table-dark">
                            <tr>
                                <th>No.</th>
                                <th>Student ID</th>
                                <th>Student Name</th>
                                <th>Program</th>
                                <th>Intake</th>
                                <th>Course</th>
                                <th>Term</th>
                                <th>Year</th>
                                <th>CA</th>
                                <th>CA1</th>
                                <th>CA2</th>
                                <th>Exam</th>
                                <th>Total</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody id="previewBody">
                            <!-- Preview data will be loaded here via AJAX -->
                        </tbody>
                    </table>
                </div>
                <div class="text-center mt-3">
                    <button type="button" class="btn btn-secondary" onclick="hidePreview()">
                        <i class="fas fa-times me-2"></i>Close Preview
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // Form submission handler
        document.getElementById('exportForm').addEventListener('submit', function(e) {
            const submitBtn = document.querySelector('button[name="export_excel"]');
            if (submitBtn) {
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Preparing Export...';
                submitBtn.disabled = true;
            }
        });
        
        // Preview export function
        function previewExport() {
            const form = document.getElementById('exportForm');
            const formData = new FormData(form);
            formData.append('preview', 'true');
            
            // Show loading in preview section
            document.getElementById('previewBody').innerHTML = `
                <tr>
                    <td colspan="14" class="text-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-2">Loading preview data...</p>
                    </td>
                </tr>
            `;
            
            // Show preview section
            document.getElementById('previewSection').style.display = 'block';
            
            // Scroll to preview section
            document.getElementById('previewSection').scrollIntoView({ behavior: 'smooth' });
            
            // Send AJAX request for preview
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(data => {
                // Parse the HTML response
                const parser = new DOMParser();
                const doc = parser.parseFromString(data, 'text/html');
                
                // Extract table rows from the response
                const rows = doc.querySelectorAll('table tbody tr');
                let previewHTML = '';
                
                // Show only first 10 rows for preview
                let count = 0;
                rows.forEach(row => {
                    if (count < 10) {
                        previewHTML += row.outerHTML;
                        count++;
                    }
                });
                
                // Add a note if there are more rows
                if (rows.length > 10) {
                    previewHTML += `
                        <tr>
                            <td colspan="14" class="text-center text-muted">
                                <i class="fas fa-info-circle me-2"></i>
                                Showing 10 of ${rows.length} records. Full data will be included in the export.
                            </td>
                        </tr>
                    `;
                }
                
                document.getElementById('previewBody').innerHTML = previewHTML;
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('previewBody').innerHTML = `
                    <tr>
                        <td colspan="14" class="text-center text-danger">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            Error loading preview. Please try again.
                        </td>
                    </tr>
                `;
            });
        }
        
        // Hide preview function
        function hidePreview() {
            document.getElementById('previewSection').style.display = 'none';
        }
        
        // Auto-select filters from URL parameters
        document.addEventListener('DOMContentLoaded', function() {
            const urlParams = new URLSearchParams(window.location.search);
            
            // Set filter values if they exist in URL
            const filters = ['program', 'intake', 'year', 'course'];
            filters.forEach(filter => {
                if (urlParams.has(filter)) {
                    const value = urlParams.get(filter);
                    const select = document.querySelector(`select[name="${filter}"]`);
                    if (select) {
                        for (let i = 0; i < select.options.length; i++) {
                            if (select.options[i].value === value) {
                                select.options[i].selected = true;
                                break;
                            }
                        }
                    }
                }
            });
            
            // Show message if redirected from results page
            const url = window.location.href;
            if (url.includes('export=success')) {
                showAlert('success', 'Export completed successfully!');
            }
        });
        
        // Show alert function
        function showAlert(type, message) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            document.querySelector('.container-fluid').insertBefore(alertDiv, document.querySelector('.header-section').nextSibling);
            
            // Auto-remove after 5 seconds
            setTimeout(() => {
                alertDiv.remove();
            }, 5000);
        }
    </script>
</body>
</html>