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

// Check if user is Super Admin
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"] !== 0) {
    header("location: login.php");
    exit;
}

$user_id = $_SESSION["id"];
$username = htmlspecialchars($_SESSION["username"]);
$phone_number = $photo = "";

// Fetch user details
if (isset($conn) && $conn instanceof mysqli) {
    $sql = "SELECT phone_number, photo FROM users WHERE id = ?";
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("i", $user_id);
        if ($stmt->execute()) {
            $stmt->bind_result($phone_number_db, $photo_db);
            $stmt->fetch();
            $phone_number = htmlspecialchars($phone_number_db ?? 'N/A');
            $photo = !empty($photo_db) ? htmlspecialchars($photo_db) : 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="80" height="80"%3E%3Crect width="80" height="80" fill="%234f46e5"/%3E%3Ctext x="50%25" y="50%25" dominant-baseline="middle" text-anchor="middle" font-family="Arial, sans-serif" font-size="32" font-weight="bold" fill="white"%3ESA%3C/text%3E%3C/svg%3E';
        }
        $stmt->close();
    }
}

// Fetch report statistics with error handling
$totalSchools = $totalUsers = $totalBackups = $totalRevenue = 0;
$error_message = "";

if (isset($conn) && $conn instanceof mysqli) {
    try {
        // Total schools
        $result = $conn->query("SELECT COUNT(*) as count FROM schools");
        if ($result) {
            $totalSchools = $result->fetch_assoc()['count'];
            $result->free();
        }
        
        // Total users
        $result = $conn->query("SELECT COUNT(*) as count FROM users");
        if ($result) {
            $totalUsers = $result->fetch_assoc()['count'];
            $result->free();
        }
        
        // Total backups - check if table exists
        $result = $conn->query("SHOW TABLES LIKE 'backup_logs'");
        if ($result && $result->num_rows > 0) {
            $result->free();
            $result = $conn->query("SELECT COUNT(*) as count FROM backup_logs WHERE status = 'completed'");
            if ($result) {
                $totalBackups = $result->fetch_assoc()['count'];
                $result->free();
            }
        }
        
        // Total revenue - check if table exists
        $result = $conn->query("SHOW TABLES LIKE 'invoices'");
        if ($result && $result->num_rows > 0) {
            $result->free();
            $result = $conn->query("SELECT SUM(amount) as total FROM invoices WHERE status = 'paid'");
            if ($result) {
                $totalRevenue = $result->fetch_assoc()['total'] ?? 0;
                $result->free();
            }
        }
    } catch (Exception $e) {
        $error_message = "Database error: " . $e->getMessage();
        error_log($error_message);
    }
} else {
    $error_message = "Database connection not available";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reports - Super Admin</title>
    <link rel="stylesheet" href="super_admin_layout.css">
    <link rel="icon" href="images/logo.png" type="image/png">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        .reports-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        .error-message {
            background: #fee2e2;
            color: #dc2626;
            padding: 15px;
            border-radius: 8px;
            border-left: 4px solid #dc2626;
            margin-bottom: 20px;
        }

        .report-card {
            background: white;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.08);
            margin-bottom: 30px;
        }

        .report-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .report-stat {
            padding: 25px;
            border-radius: 10px;
            color: white;
            text-align: center;
            position: relative;
            overflow: hidden;
        }

        .report-stat::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(45deg, rgba(255,255,255,0.1) 25%, transparent 25%, transparent 50%, rgba(255,255,255,0.1) 50%, rgba(255,255,255,0.1) 75%, transparent 75%, transparent);
            background-size: 20px 20px;
            animation: shimmer 2s linear infinite;
        }

        @keyframes shimmer {
            0% { background-position: 0 0; }
            100% { background-position: 20px 20px; }
        }

        .report-stat i {
            font-size: 2.5em;
            margin-bottom: 15px;
            position: relative;
            z-index: 1;
        }

        .report-stat h3 {
            font-size: 2em;
            margin: 10px 0;
            position: relative;
            z-index: 1;
        }

        .report-stat p {
            position: relative;
            z-index: 1;
            margin: 0;
        }

        .btn-export {
            background: #10b981;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s;
            text-decoration: none;
            display: inline-block;
            border: none;
        }

        .btn-export:hover {
            background: #059669;
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3);
        }

        .chart-container {
            position: relative;
            height: 350px;
            margin-top: 20px;
        }

        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 9999;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.5);
            animation: fadeIn 0.3s;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .modal-content {
            background-color: #fefefe;
            margin: 5% auto;
            padding: 30px;
            border: 1px solid #888;
            border-radius: 12px;
            width: 90%;
            max-width: 600px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
            animation: slideDown 0.3s;
        }

        @keyframes slideDown {
            from {
                transform: translateY(-50px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .modal-header {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }

        .modal-header i {
            font-size: 2.5em;
            margin-right: 15px;
            color: #4f46e5;
        }

        .modal-header h3 {
            margin: 0;
            color: #333;
        }

        .modal-body {
            margin-bottom: 25px;
            color: #666;
            line-height: 1.6;
        }

        .modal-footer {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
        }

        .btn-modal {
            padding: 10px 24px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 15px;
            font-weight: 600;
            transition: all 0.2s;
        }

        .btn-cancel {
            background-color: #e5e7eb;
            color: #333;
        }

        .btn-cancel:hover {
            background-color: #d1d5db;
        }

        .btn-primary {
            background-color: #4f46e5;
            color: white;
        }

        .btn-primary:hover {
            background-color: #4338ca;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }

        .form-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
        }

        /* Notification Box */
        .notification-box {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 20px 25px;
            border-radius: 8px;
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
            z-index: 10000;
            display: none;
            align-items: center;
            gap: 15px;
            max-width: 400px;
            animation: slideInRight 0.3s;
        }

        @keyframes slideInRight {
            from {
                transform: translateX(400px);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        .notification-success {
            background-color: #d1fae5;
            color: #065f46;
            border-left: 4px solid #10b981;
        }

        .notification-error {
            background-color: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }

        .notification-box i {
            font-size: 1.5em;
        }

        .notification-close {
            background: none;
            border: none;
            font-size: 1.2em;
            cursor: pointer;
            color: inherit;
            opacity: 0.7;
            margin-left: auto;
        }

        .notification-close:hover {
            opacity: 1;
        }

        /* Loading Animation */
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #4f46e5;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* Responsive */
        @media (max-width: 768px) {
            .reports-container {
                padding: 10px;
            }
            .report-grid {
                grid-template-columns: 1fr;
            }
            .modal-content {
                width: 95%;
                margin: 10% auto;
            }
        }
    </style>
</head>
<body>
    <div class="dashboard-container" id="dashboardContainer">
        <?php include 'includes/super_admin_sidebar.php'; ?>
        
        <div class="main-content">
            <?php include 'includes/super_admin_header.php'; ?>
            
            <div class="dashboard-content">
                <div class="reports-container">
                    <!-- Error Message Display -->
                    <?php if (!empty($error_message)): ?>
                        <div class="error-message">
                            <i class="fas fa-exclamation-triangle"></i>
                            <?php echo htmlspecialchars($error_message); ?>
                        </div>
                    <?php endif; ?>

                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; flex-wrap: wrap; gap: 15px;">
                        <h2><i class="fas fa-chart-line"></i> System Reports</h2>
                        <button class="btn-export" onclick="openExportModal()">
                            <i class="fas fa-download"></i> Export Reports
                        </button>
                    </div>

                    <!-- Report Statistics -->
                    <div class="report-grid">
                        <div class="report-stat" style="background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);">
                            <i class="fas fa-school"></i>
                            <h3><?php echo number_format($totalSchools); ?></h3>
                            <p>Total Schools</p>
                        </div>
                        <div class="report-stat" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
                            <i class="fas fa-users"></i>
                            <h3><?php echo number_format($totalUsers); ?></h3>
                            <p>Total Users</p>
                        </div>
                        <div class="report-stat" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);">
                            <i class="fas fa-database"></i>
                            <h3><?php echo number_format($totalBackups); ?></h3>
                            <p>Total Backups</p>
                        </div>
                        <div class="report-stat" style="background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);">
                            <i class="fas fa-money-bill-wave"></i>
                            <h3>UGX <?php echo number_format($totalRevenue); ?></h3>
                            <p>Total Revenue</p>
                        </div>
                    </div>

                    <!-- Available Reports -->
                    <div class="report-card">
                        <h3><i class="fas fa-file-alt"></i> Available Reports</h3>
                        <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; margin-top: 20px;">
                            <div style="background: #f9fafb; padding: 20px; border-radius: 10px; border-left: 4px solid #4f46e5; transition: transform 0.3s;" onmouseover="this.style.transform='translateY(-5px)'" onmouseout="this.style.transform='translateY(0)'">
                                <h4 style="margin: 0 0 10px 0; color: #333;"><i class="fas fa-school"></i> Schools Report</h4>
                                <p style="color: #666; margin: 10px 0;">Complete overview of all schools, their users, and status.</p>
                                <button class="btn-export" style="width: 100%; margin-top: 10px;" onclick="openReportModal('schools', 'pdf')">
                                    <i class="fas fa-file-pdf"></i> Generate PDF
                                </button>
                            </div>
                            <div style="background: #f9fafb; padding: 20px; border-radius: 10px; border-left: 4px solid #10b981; transition: transform 0.3s;" onmouseover="this.style.transform='translateY(-5px)'" onmouseout="this.style.transform='translateY(0)'">
                                <h4 style="margin: 0 0 10px 0; color: #333;"><i class="fas fa-money-bill-wave"></i> Financial Report</h4>
                                <p style="color: #666; margin: 10px 0;">Detailed financial breakdown of payments and revenue.</p>
                                <button class="btn-export" style="width: 100%; margin-top: 10px; background: #4f46e5;" onclick="openReportModal('financial', 'excel')" onmouseover="this.style.background='#4338ca'" onmouseout="this.style.background='#4f46e5'">
                                    <i class="fas fa-file-excel"></i> Generate Excel
                                </button>
                            </div>
                            <div style="background: #f9fafb; padding: 20px; border-radius: 10px; border-left: 4px solid #f59e0b; transition: transform 0.3s;" onmouseover="this.style.transform='translateY(-5px)'" onmouseout="this.style.transform='translateY(0)'">
                                <h4 style="margin: 0 0 10px 0; color: #333;"><i class="fas fa-users"></i> User Activity Report</h4>
                                <p style="color: #666; margin: 10px 0;">User registration trends and activity statistics.</p>
                                <button class="btn-export" style="width: 100%; margin-top: 10px; background: #f59e0b;" onclick="openReportModal('users', 'csv')" onmouseover="this.style.background='#d97706'" onmouseout="this.style.background='#f59e0b'">
                                    <i class="fas fa-file-csv"></i> Generate CSV
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- System Analytics -->
                    <div class="report-card">
                        <h3><i class="fas fa-chart-bar"></i> System Analytics</h3>
                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(500px, 1fr)); gap: 30px;">
                            <div>
                                <h4 style="color: #333; margin-bottom: 15px;">Monthly Overview</h4>
                                <div class="chart-container">
                                    <canvas id="monthlyChart"></canvas>
                                </div>
                            </div>
                            <div>
                                <h4 style="color: #333; margin-bottom: 15px;">User Distribution</h4>
                                <div class="chart-container">
                                    <canvas id="distributionChart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <?php include 'includes/super_admin_mobile_nav.php'; ?>
    </div>

    <!-- Generate Report Modal -->
    <div id="reportModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <i class="fas fa-file-export"></i>
                <h3>Generate Report</h3>
            </div>
            <form id="reportForm" onsubmit="event.preventDefault(); generateReport();">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="report_type">Report Type</label>
                        <input type="text" id="report_type" readonly style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; background: #f9fafb;">
                    </div>
                    <div class="form-group">
                        <label for="report_format">Export Format</label>
                        <input type="text" id="report_format" readonly style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; background: #f9fafb;">
                    </div>
                    <div class="form-group">
                        <label for="date_range">Date Range</label>
                        <select id="date_range">
                            <option value="today">Today</option>
                            <option value="week">Last 7 Days</option>
                            <option value="month" selected>Last 30 Days</option>
                            <option value="year">Last Year</option>
                            <option value="all">All Time</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" onclick="closeModal('reportModal')" class="btn-modal btn-cancel">
                        <i class="fas fa-times"></i> Cancel
                    </button>
                    <button type="submit" class="btn-modal btn-primary" id="generateBtn">
                        <i class="fas fa-download"></i> Generate Report
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Export All Modal -->
    <div id="exportModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <i class="fas fa-file-archive"></i>
                <h3>Export All Reports</h3>
            </div>
            <form id="exportForm" onsubmit="event.preventDefault(); exportAllReports();">
                <div class="modal-body">
                    <p>This will generate a comprehensive ZIP file containing all system reports.</p>
                    <div class="form-group">
                        <label for="export_date_range">Date Range</label>
                        <select id="export_date_range">
                            <option value="month" selected>Last 30 Days</option>
                            <option value="quarter">Last Quarter</option>
                            <option value="year">Last Year</option>
                            <option value="all">All Time</option>
                        </select>
                    </div>
                    <div style="background: #f0f9ff; padding: 15px; border-radius: 6px; margin-top: 15px;">
                        <p style="margin: 0; color: #0c4a6e; font-size: 0.9em;"><i class="fas fa-info-circle"></i> The export will include: Schools Report, Financial Report, User Activity Report, and Analytics Data.</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" onclick="closeModal('exportModal')" class="btn-modal btn-cancel">
                        <i class="fas fa-times"></i> Cancel
                    </button>
                    <button type="submit" class="btn-modal btn-primary" id="exportAllBtn">
                        <i class="fas fa-file-download"></i> Export All
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Notification Box -->
    <div id="notificationBox" class="notification-box notification-success" style="display: none;">
        <i class="fas fa-check-circle"></i>
        <span id="notificationMessage"></span>
        <button onclick="closeNotification()" class="notification-close"><i class="fas fa-times"></i></button>
    </div>

    <script>
        // Initialize charts with fallback data
        function initCharts() {
            // Monthly Chart
            const monthlyCtx = document.getElementById('monthlyChart');
            if (monthlyCtx) {
                new Chart(monthlyCtx.getContext('2d'), {
                    type: 'line',
                    data: {
                        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
                        datasets: [{
                            label: 'New Schools',
                            data: [2, 5, 3, 8, 4, 6],
                            borderColor: '#4f46e5',
                            backgroundColor: 'rgba(79, 70, 229, 0.1)',
                            tension: 0.4,
                            fill: true
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: { legend: { display: false } },
                        scales: {
                            y: { beginAtZero: true }
                        }
                    }
                });
            }

            // Distribution Chart
            const distributionCtx = document.getElementById('distributionChart');
            if (distributionCtx) {
                new Chart(distributionCtx.getContext('2d'), {
                    type: 'doughnut',
                    data: {
                        labels: ['Admins', 'Teachers', 'Students'],
                        datasets: [{
                            data: [<?php echo $totalSchools; ?>, <?php echo $totalUsers; ?>, <?php echo $totalUsers * 2; ?>],
                            backgroundColor: ['#6366f1', '#8b5cf6', '#ec4899']
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false
                    }
                });
            }
        }

        // Initialize charts when DOM is loaded
        document.addEventListener('DOMContentLoaded', initCharts);

        function openReportModal(type, format) {
            document.getElementById('report_type').value = type.charAt(0).toUpperCase() + type.slice(1) + ' Report';
            document.getElementById('report_format').value = format.toUpperCase();
            document.getElementById('reportModal').style.display = 'block';
        }

        function openExportModal() {
            document.getElementById('exportModal').style.display = 'block';
        }

        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }

        async function generateReport() {
            const type = document.getElementById('report_type').value;
            const format = document.getElementById('report_format').value;
            const dateRange = document.getElementById('date_range').value;
            
            // Show loading state
            const generateBtn = document.getElementById('generateBtn');
            generateBtn.innerHTML = '<div class="loading"></div> Generating...';
            generateBtn.disabled = true;
            
            closeModal('reportModal');
            showNotification(`Generating ${type} in ${format} format...`);
            
            try {
                // Generate the report based on format
                if (format === 'PDF') {
                    await generatePDFReport(type, dateRange);
                } else if (format === 'EXCEL') {
                    await generateExcelReport(type, dateRange);
                } else if (format === 'CSV') {
                    await generateCSVReport(type, dateRange);
                }
            } catch (error) {
                showErrorNotification('Failed to generate report: ' + error.message);
            } finally {
                // Reset button state
                generateBtn.innerHTML = '<i class="fas fa-download"></i> Generate Report';
                generateBtn.disabled = false;
            }
        }

        async function generatePDFReport(type, dateRange) {
            const data = await getReportData(type);
            
            // Generate HTML content for PDF
            const content = `
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>${type}</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        h1 { color: #4f46e5; border-bottom: 3px solid #4f46e5; padding-bottom: 10px; }
        .header { display: flex; justify-content: space-between; margin-bottom: 30px; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
        th { background-color: #4f46e5; color: white; }
        tr:nth-child(even) { background-color: #f9fafb; }
        .footer { margin-top: 40px; text-align: center; color: #666; font-size: 12px; }
    </style>
</head>
<body>
    <div class="header">
        <div>
            <h1>${type}</h1>
            <p>Date Range: ${dateRange}</p>
        </div>
        <div>
            <p>Generated: ${new Date().toLocaleDateString()}</p>
            <p>Super Admin Dashboard</p>
        </div>
    </div>
    
    ${getReportContent(data)}
    
    <div class="footer">
        <p>© 2025 Super Admin Dashboard - Confidential Report</p>
    </div>
</body>
</html>
            `;
            
            downloadFile(content, `${type.replace(/ /g, '_')}_${dateRange}.html`, 'text/html');
        }

        async function generateExcelReport(type, dateRange) {
            const data = await getReportData(type);
            let csv = data.headers.join(',') + '\n';
            
            data.rows.forEach(row => {
                csv += row.join(',') + '\n';
            });
            
            downloadFile(csv, `${type.replace(/ /g, '_')}_${dateRange}.csv`, 'text/csv');
        }

        async function generateCSVReport(type, dateRange) {
            const data = await getReportData(type);
            let csv = data.headers.join(',') + '\n';
            
            data.rows.forEach(row => {
                csv += row.join(',') + '\n';
            });
            
            downloadFile(csv, `${type.replace(/ /g, '_')}_${dateRange}.csv`, 'text/csv');
        }

        function getReportContent(data) {
            let html = '<table><thead><tr>';
            
            data.headers.forEach(header => {
                html += `<th>${header}</th>`;
            });
            
            html += '</tr></thead><tbody>';
            
            data.rows.forEach(row => {
                html += '<tr>';
                row.forEach(cell => {
                    html += `<td>${cell}</td>`;
                });
                html += '</tr>';
            });
            
            html += '</tbody></table>';
            return html;
        }

        async function getReportData(type) {
            // Fallback data for different report types
            const reportType = type.toLowerCase().includes('school') ? 'schools' : 
                              type.toLowerCase().includes('financial') ? 'financial' : 'users';
            
            const dateRange = document.getElementById('date_range') ? document.getElementById('date_range').value : 'all';
            
            try {
                const response = await fetch(`generate_report.php?type=${reportType}&range=${dateRange}`);
                if (response.ok) {
                    const data = await response.json();
                    if (data.headers && data.rows) {
                        return data;
                    }
                }
            } catch (error) {
                console.log('Using fallback data for report generation');
            }
            
            // Fallback data based on report type
            if (reportType === 'schools') {
                return {
                    headers: ['School Name', 'Administrator', 'Users Count', 'Status', 'Registration Date'],
                    rows: [
                        ['Divine High School', 'John Doe', '150', 'Active', '2024-01-15'],
                        ['St. Marys Academy', 'Jane Smith', '200', 'Active', '2024-02-20'],
                        ['Unity Primary', 'Mike Johnson', '120', 'Active', '2024-03-10']
                    ]
                };
            } else if (reportType === 'financial') {
                return {
                    headers: ['School', 'Amount', 'Status', 'Date', 'Invoice #'],
                    rows: [
                        ['Divine High School', 'UGX 500,000', 'Paid', '2024-10-01', 'INV-001'],
                        ['St. Marys Academy', 'UGX 750,000', 'Paid', '2024-10-05', 'INV-002'],
                        ['Unity Primary', 'UGX 300,000', 'Pending', '2024-10-10', 'INV-003']
                    ]
                };
            } else {
                return {
                    headers: ['Role', 'Count', 'Active', 'Inactive'],
                    rows: [
                        ['Super Admin', '1', '1', '0'],
                        ['Admin', '<?php echo $totalSchools; ?>', '<?php echo $totalSchools; ?>', '0'],
                        ['Teachers', '<?php echo $totalUsers; ?>', '<?php echo $totalUsers; ?>', '0'],
                        ['Students', '<?php echo $totalUsers * 2; ?>', '<?php echo $totalUsers * 2; ?>', '0']
                    ]
                };
            }
        }

        async function exportAllReports() {
            const dateRange = document.getElementById('export_date_range').value;
            
            // Show loading state
            const exportBtn = document.getElementById('exportAllBtn');
            exportBtn.innerHTML = '<div class="loading"></div> Exporting...';
            exportBtn.disabled = true;
            
            closeModal('exportModal');
            showNotification('Exporting all reports...');
            
            try {
                // Export each report type with delays
                await generatePDFReport('Schools Report', dateRange);
                await delay(1000);
                
                await generateExcelReport('Financial Report', dateRange);
                await delay(1000);
                
                await generateCSVReport('User Activity Report', dateRange);
                
                showNotification('All reports exported successfully!');
            } catch (error) {
                showErrorNotification('Failed to export reports: ' + error.message);
            } finally {
                // Reset button state
                exportBtn.innerHTML = '<i class="fas fa-file-download"></i> Export All';
                exportBtn.disabled = false;
            }
        }

        function delay(ms) {
            return new Promise(resolve => setTimeout(resolve, ms));
        }

        function downloadFile(content, filename, mimeType) {
            const blob = new Blob([content], { type: mimeType });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
            
            showNotification(`Report downloaded: ${filename}`);
        }

        function showNotification(message) {
            const notification = document.getElementById('notificationBox');
            const messageEl = document.getElementById('notificationMessage');
            const icon = notification.querySelector('i');
            
            // Reset classes
            notification.className = 'notification-box notification-success';
            icon.className = 'fas fa-check-circle';
            
            messageEl.textContent = message;
            notification.style.display = 'flex';
            
            setTimeout(() => {
                closeNotification();
            }, 5000);
        }

        function showErrorNotification(message) {
            const notification = document.getElementById('notificationBox');
            const messageEl = document.getElementById('notificationMessage');
            const icon = notification.querySelector('i');
            
            // Set error classes
            notification.className = 'notification-box notification-error';
            icon.className = 'fas fa-exclamation-circle';
            
            messageEl.textContent = message;
            notification.style.display = 'flex';
            
            setTimeout(() => {
                closeNotification();
            }, 7000);
        }

        function closeNotification() {
            const notification = document.getElementById('notificationBox');
            notification.style.opacity = '0';
            setTimeout(() => {
                notification.style.display = 'none';
                notification.style.opacity = '1';
            }, 500);
        }

        // Mobile sidebar functionality
        const menuToggle = document.getElementById('menuToggle');
        const sidebar = document.getElementById('sidebar');
        const dashboardContainer = document.getElementById('dashboardContainer');
        
        if (menuToggle && sidebar) {
            menuToggle.addEventListener('click', function() {
                sidebar.classList.toggle('collapsed');
                dashboardContainer.classList.toggle('sidebar-collapsed');
            });
        }

        // Close modals when clicking outside
        window.onclick = function(event) {
            if (event.target.classList.contains('modal')) {
                event.target.style.display = 'none';
            }
        }

        // Handle escape key for modals
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                const modals = document.querySelectorAll('.modal');
                modals.forEach(modal => {
                    if (modal.style.display === 'block') {
                        modal.style.display = 'none';
                    }
                });
            }
        });
    </script>
</body>
</html>
<?php
if (isset($conn) && $conn instanceof mysqli && $conn->ping()) {
    $conn->close();
}
?>