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

// Define role constants
if (!defined('ROLE_SUPER_ADMIN')) define('ROLE_SUPER_ADMIN', 0);
if (!defined('ROLE_ADMIN')) define('ROLE_ADMIN', 1);
if (!defined('ROLE_TEACHER')) define('ROLE_TEACHER', 2);
if (!defined('ROLE_STUDENT')) define('ROLE_STUDENT', 3);

// Function to check user role and redirect if unauthorized
function check_role_access($required_role_code) {
    if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
        header("location: login.php");
        exit;
    }

    if ($_SESSION["role"] !== $required_role_code) {
        switch ($_SESSION["role"]) {
            case ROLE_ADMIN:
                header("location: admin_dashboard.php");
                break;
            case ROLE_TEACHER:
                header("location: teacher_dashboard.php");
                break;
            case ROLE_STUDENT:
                header("location: student_dashboard.php");
                break;
            default:
                header("location: login.php");
                break;
        }
        exit;
    }
}

// Check for Super Admin role
check_role_access(ROLE_SUPER_ADMIN);

// User details
$user_id = $_SESSION["id"];
$username = htmlspecialchars($_SESSION["username"]);
$user_role_code = $_SESSION["role"];
$phone_number = $photo = $status = "";

// Initialize dashboard stats for Super Admin
$totalSchools = 0;
$activeSchools = 0;
$suspendedSchools = 0;
$totalRevenue = 0;
$pendingPayments = 0;
$totalAdmins = 0;
$totalTeachers = 0;
$totalStudents = 0;

// Initialize arrays for charts
$schoolsList = [];
$revenueData = [];
$schoolsStatusData = [];
$usersDistribution = [];
$schoolsGrowthData = [];
$topSchoolsData = [];

// Ensure $conn is available from config.php
if (isset($conn) && $conn instanceof mysqli) {

    // Fetch Super Admin user details
    $sql = "SELECT phone_number, photo, status 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, $status_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';
            $status = htmlspecialchars($status_db ?? 'N/A');
        }
        $stmt->close();
    }

    // Total Schools
    $sql_total_schools = "SELECT COUNT(school_id) FROM schools";
    if ($result = $conn->query($sql_total_schools)) {
        $row = $result->fetch_row();
        $totalSchools = $row[0];
        $result->free();
    }

    // Active Schools (those with active subscription status)
    $sql_active_schools = "SELECT COUNT(school_id) FROM schools WHERE subscription_status = 'active'";
    if ($result = $conn->query($sql_active_schools)) {
        $row = $result->fetch_row();
        $activeSchools = $row[0];
        $result->free();
    }

    // Suspended Schools (those with suspended subscription status)
    $sql_suspended_schools = "SELECT COUNT(school_id) FROM schools WHERE subscription_status = 'suspended'";
    if ($result = $conn->query($sql_suspended_schools)) {
        $row = $result->fetch_row();
        $suspendedSchools = $row[0];
        $result->free();
    } else {
        $suspendedSchools = 0;
    }

    // Total Admins across all schools
    $sql_total_admins = "SELECT COUNT(id) FROM users WHERE role = 1";
    if ($result = $conn->query($sql_total_admins)) {
        $row = $result->fetch_row();
        $totalAdmins = $row[0];
        $result->free();
    }

    // Total Teachers across all schools
    $sql_total_teachers = "SELECT COUNT(id) FROM users WHERE role = 2 AND status = 'active'";
    if ($result = $conn->query($sql_total_teachers)) {
        $row = $result->fetch_row();
        $totalTeachers = $row[0];
        $result->free();
    }

    // Total Students across all schools
    $sql_total_students = "SELECT COUNT(id) FROM users WHERE role = 3 AND (status = 'active' OR status = '')";
    if ($result = $conn->query($sql_total_students)) {
        $row = $result->fetch_row();
        $totalStudents = $row[0];
        $result->free();
    }

    // Fetch all schools for management
    $sql_schools = "SELECT s.school_id, s.school_name, s.abbreviation, s.email, s.phone, s.address, s.logo, s.created_at, 
                    s.subscription_expiry_date,
                    s.subscription_status,
                    s.status as school_status,
                    (SELECT COUNT(id) FROM users WHERE school_id = s.school_id AND role = 1) as admin_count,
                    (SELECT COUNT(id) FROM users WHERE school_id = s.school_id AND role = 2) as teacher_count,
                    (SELECT COUNT(id) FROM users WHERE school_id = s.school_id AND role = 3) as student_count,
                    (SELECT status FROM users WHERE school_id = s.school_id AND role = 1 LIMIT 1) as admin_status,
                    CASE 
                        WHEN s.subscription_status = 'suspended' 
                             AND (s.subscription_expiry_date IS NOT NULL AND s.subscription_expiry_date < CURDATE())
                        THEN 'auto_suspended'
                        WHEN s.subscription_status = 'suspended'
                        THEN 'manually_suspended'
                        ELSE 'active'
                    END as suspension_type
                    FROM schools s ORDER BY s.created_at DESC";
    if ($result = $conn->query($sql_schools)) {
        while ($row = $result->fetch_assoc()) {
            $schoolsList[] = $row;
        }
        $result->free();
    }

    // Schools status for pie chart
    $schoolsStatusData = [
        ['status' => 'Active', 'count' => $activeSchools],
        ['status' => 'Suspended', 'count' => $suspendedSchools]
    ];

    // Users distribution by role for bar chart
    $usersDistribution = [
        ['role' => 'Admins', 'count' => $totalAdmins],
        ['role' => 'Teachers', 'count' => $totalTeachers],
        ['role' => 'Students', 'count' => $totalStudents]
    ];

    // Schools growth over last 6 months
    $sql_growth = "SELECT DATE_FORMAT(created_at, '%Y-%m') as month, COUNT(school_id) as count 
                   FROM schools 
                   WHERE created_at >= DATE_SUB(NOW(), INTERVAL 6 MONTH) 
                   GROUP BY month 
                   ORDER BY month ASC";
    if ($result = $conn->query($sql_growth)) {
        while ($row = $result->fetch_assoc()) {
            $schoolsGrowthData[] = $row;
        }
        $result->free();
    }

    // Top 5 schools by user count
    $sql_top_schools = "SELECT s.school_name, 
                        (SELECT COUNT(id) FROM users WHERE school_id = s.school_id) as total_users 
                        FROM schools s 
                        ORDER BY total_users DESC 
                        LIMIT 5";
    if ($result = $conn->query($sql_top_schools)) {
        while ($row = $result->fetch_assoc()) {
            $topSchoolsData[] = $row;
        }
        $result->free();
    }

    // Payment data for last 6 months (checking if invoices table exists)
    $paymentData = [];
    $check_invoices = "SHOW TABLES LIKE 'invoices'";
    if ($conn->query($check_invoices)->num_rows > 0) {
        $sql_payments = "SELECT DATE_FORMAT(payment_date, '%Y-%m') as month, 
                         SUM(total_amount) as amount 
                         FROM invoices 
                         WHERE payment_date IS NOT NULL 
                         AND payment_date >= DATE_SUB(NOW(), INTERVAL 6 MONTH) 
                         GROUP BY month 
                         ORDER BY month ASC";
        if ($result = $conn->query($sql_payments)) {
            while ($row = $result->fetch_assoc()) {
                $paymentData[] = $row;
            }
            $result->free();
        }
    }

    // Get subscription expiry date (earliest expiring active subscription)
    $subscriptionExpiryDate = null;
    $check_subscriptions = "SHOW TABLES LIKE 'school_subscriptions'";
    if ($conn->query($check_subscriptions)->num_rows > 0) {
        $sql_subscription = "SELECT subscription_end FROM school_subscriptions 
                             WHERE payment_status = 'paid' 
                             AND subscription_end >= CURDATE() 
                             ORDER BY subscription_end ASC 
                             LIMIT 1";
        if ($result = $conn->query($sql_subscription)) {
            if ($row = $result->fetch_assoc()) {
                $subscriptionExpiryDate = $row['subscription_end'];
            }
            $result->free();
        }
    }
    
    // If no subscription found in school_subscriptions, set a default (e.g., 30 days from now)
    if (!$subscriptionExpiryDate) {
        $subscriptionExpiryDate = date('Y-m-d', strtotime('+30 days'));
    }

} else {
    error_log("Database connection not available in super_admin_dashboard.php");
    $photo = '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';
}

$role_name = "Super Admin";

// Prepare data for Chart.js
$statusLabels = json_encode(array_column($schoolsStatusData, 'status'));
$statusData = json_encode(array_column($schoolsStatusData, 'count'));

$usersLabels = json_encode(array_column($usersDistribution, 'role'));
$usersData = json_encode(array_column($usersDistribution, 'count'));

$growthLabels = json_encode(array_column($schoolsGrowthData, 'month'));
$growthData = json_encode(array_column($schoolsGrowthData, 'count'));

$topSchoolsLabels = json_encode(array_column($topSchoolsData, 'school_name'));
$topSchoolsDataValues = json_encode(array_column($topSchoolsData, 'total_users'));

$paymentLabels = json_encode(array_column($paymentData, 'month'));
$paymentAmounts = json_encode(array_column($paymentData, 'amount'));
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $role_name; ?> Dashboard - Divine Reports</title>
    <link rel="stylesheet" href="style.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>
        /* Super Admin Color Scheme */
        :root {
            --super-admin-primary: #4f46e5;
            --super-admin-secondary: #7c3aed;
            --success-color: #10b981;
            --warning-color: #f59e0b;
            --danger-color: #ef4444;
        }

        /* Fixed Header and Sidebar Layout */
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
            height: 100vh;
        }

        .dashboard-container {
            display: flex;
            height: 100vh;
            overflow: hidden;
        }

        /* Fixed Sidebar */
        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            height: 100vh;
            width: 250px;
            overflow-y: auto;
            z-index: 1000;
            transition: transform 0.3s ease;
        }

        .sidebar.collapsed {
            transform: translateX(-250px);
        }

        /* Main Content Area */
        .main-content {
            flex: 1;
            margin-left: 250px;
            display: flex;
            flex-direction: column;
            height: 100vh;
            overflow: hidden;
            transition: margin-left 0.3s ease;
        }

        .sidebar-collapsed .main-content {
            margin-left: 0;
        }

        /* Fixed Header */
        .header {
            position: sticky;
            top: 0;
            z-index: 999;
            background: white;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        /* Scrollable Dashboard Content */
        .dashboard-content {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;
            padding: 20px;
            background: #f5f5f5;
        }

        /* Scrollbar Styling */
        .dashboard-content::-webkit-scrollbar {
            width: 8px;
        }

        .dashboard-content::-webkit-scrollbar-track {
            background: #f1f1f1;
        }

        .dashboard-content::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 4px;
        }

        .dashboard-content::-webkit-scrollbar-thumb:hover {
            background: #555;
        }

        .sidebar::-webkit-scrollbar {
            width: 6px;
        }

        .sidebar::-webkit-scrollbar-track {
            background: transparent;
        }

        .sidebar::-webkit-scrollbar-thumb {
            background: rgba(255, 255, 255, 0.3);
            border-radius: 3px;
        }

        .sidebar::-webkit-scrollbar-thumb:hover {
            background: rgba(255, 255, 255, 0.5);
        }

        .stat-card.schools { background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%); }
        .stat-card.active-schools { background: linear-gradient(135deg, #10b981 0%, #059669 100%); }
        .stat-card.revenue { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); }
        .stat-card.pending { background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); }
        .stat-card.admins { background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%); }
        .stat-card.teachers { background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%); }
        .stat-card.students { background: linear-gradient(135deg, #ec4899 0%, #db2777 100%); }
        .stat-card.suspended { background: linear-gradient(135deg, #64748b 0%, #475569 100%); }

        /* White text for all stat cards */
        .stat-card .icon,
        .stat-card .count,
        .stat-card .label {
            color: white !important;
        }

        /* Schools Management Table */
        .schools-table-card {
            background-color: #fff;
            border-radius: 12px;
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.08);
            padding: 25px;
            margin-top: 20px;
        }

        .schools-table-card h3 {
            color: #333;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .schools-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }

        .schools-table th,
        .schools-table td {
            border: 1px solid #eee;
            padding: 12px;
            text-align: left;
        }

        .schools-table th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #555;
        }

        .schools-table tbody tr:nth-child(even) {
            background-color: #fbfbfb;
        }

        .schools-table tbody tr:hover {
            background-color: #f0f0f0;
        }

        .status-badge {
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 0.85em;
            font-weight: 600;
        }

        .status-active {
            background-color: #d1fae5;
            color: #065f46;
        }

        .status-suspended {
            background-color: #fee2e2;
            color: #991b1b;
        }

        .status-auto-suspended {
            background-color: #fef3c7;
            color: #92400e;
            border: 1px solid #f59e0b;
            position: relative;
        }

        .status-auto-suspended::after {
            content: "⚠️";
            margin-left: 5px;
            font-size: 0.9em;
        }

        .status-auto-suspended:hover::after {
            content: "⚠️ (Auto-suspended due to expired subscription)";
            position: absolute;
            bottom: 100%;
            left: 0;
            background: #333;
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 0.8em;
            white-space: nowrap;
            z-index: 1000;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .btn {
            padding: 6px 12px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.85em;
            transition: all 0.2s ease;
            text-decoration: none;
            display: inline-block;
        }

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

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

        .btn-success {
            background-color: #10b981;
            color: white;
        }

        .btn-success:hover {
            background-color: #059669;
        }

        .btn-warning {
            background-color: #f59e0b;
            color: white;
        }

        .btn-warning:hover {
            background-color: #d97706;
        }

        .btn-danger {
            background-color: #ef4444;
            color: white;
        }

        .btn-danger:hover {
            background-color: #dc2626;
        }

        .btn-info {
            background-color: #3b82f6;
            color: white;
        }

        .btn-info:hover {
            background-color: #2563eb;
        }

        /* Quick Actions */
        .quick-actions {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }

        .quick-action-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            transition: transform 0.2s ease, box-shadow 0.2s ease;
            cursor: pointer;
            text-decoration: none;
            color: inherit;
        }

        .quick-action-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
        }

        .quick-action-card i {
            font-size: 2.5em;
            margin-bottom: 10px;
            color: #4f46e5;
        }

        .quick-action-card h4 {
            margin: 0;
            font-size: 1em;
            color: #333;
        }

        /* Chart Container */
        .chart-container {
            position: relative;
            height: 300px;
            width: 100%;
            margin-top: 20px;
        }

        /* Mobile Footer Navigation */
        #mobile-footer-nav {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            height: 70px;
            background: #ffffff;
            border-top: 1px solid #e0e0e0;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
            z-index: 1000;
            padding-bottom: env(safe-area-inset-bottom, 0px);
            display: none;
        }

        #mobile-footer-nav ul {
            display: flex;
            list-style: none;
            height: 100%;
            margin: 0;
            padding: 0;
        }

        #mobile-footer-nav li {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        #mobile-footer-nav a {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            text-decoration: none;
            color: #666666;
            font-size: 10px;
            font-weight: 500;
            width: 100%;
            height: 100%;
            transition: all 0.3s ease;
        }

        #mobile-footer-nav a i {
            font-size: 22px;
            margin-bottom: 4px;
        }

        #mobile-footer-nav a.active {
            color: #4f46e5;
        }

        /* Mobile Menu Items */
        .mobile-menu-item {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 15px;
            text-decoration: none;
            color: #333;
            border-radius: 8px;
            transition: background-color 0.3s ease;
            font-size: 16px;
            font-weight: 500;
        }

        .mobile-menu-item:hover {
            background-color: #f3f4f6;
        }

        .mobile-menu-item i {
            width: 20px;
            color: #6b7280;
        }

        .mobile-menu-item span {
            color: #333;
        }

        @media (max-width: 768px) {
            #mobile-footer-nav {
                display: block;
            }
            .main-content {
                margin-left: 0;
            }
            .dashboard-content {
                padding-bottom: 90px;
            }
            .sidebar {
                transform: translateX(-250px);
            }
            .sidebar.show {
                transform: translateX(0);
            }
        }

        /* 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;
        }

        .modal-header.warning i {
            color: #f59e0b;
        }

        .modal-header.success i {
            color: #10b981;
        }

        .modal-header.danger i {
            color: #ef4444;
        }

        .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;
        }

        .btn-confirm-warning {
            background-color: #f59e0b;
            color: white;
        }

        .btn-confirm-warning:hover {
            background-color: #d97706;
        }

        .btn-confirm-success {
            background-color: #10b981;
            color: white;
        }

        .btn-confirm-success:hover {
            background-color: #059669;
        }

        .btn-confirm-delete {
            background-color: #ef4444;
            color: white;
        }

        .btn-confirm-delete:hover {
            background-color: #dc2626;
        }

        /* 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: flex;
            align-items: center;
            gap: 15px;
            max-width: 400px;
            animation: slideInRight 0.3s;
            transition: opacity 0.5s;
        }

        @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;
        }

        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close:hover,
        .close:focus {
            color: #000;
        }

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

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

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

        .form-group input[type="file"] {
            padding: 8px;
        }

        /* Subscription Expiry Timer */
        .subscription-timer-container {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a6f 50%, #c92a2a 100%);
            border-radius: 12px;
            padding: 20px 30px;
            margin: 20px 0;
            box-shadow: 0 8px 25px rgba(255, 107, 107, 0.4);
            color: white;
            position: relative;
            overflow: hidden;
            animation: pulseWarning 2s infinite;
        }

        @keyframes pulseWarning {
            0%, 100% { box-shadow: 0 8px 25px rgba(255, 107, 107, 0.4); }
            50% { box-shadow: 0 8px 35px rgba(255, 107, 107, 0.6); }
        }

        .subscription-timer-container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(45deg, transparent 30%, rgba(255,255,255,0.1) 50%, transparent 70%);
            animation: shimmer 3s infinite;
        }

        @keyframes shimmer {
            0% { transform: translateX(-100%); }
            100% { transform: translateX(100%); }
        }

        .subscription-timer-header {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-bottom: 15px;
            position: relative;
            z-index: 1;
        }

        .subscription-timer-header i {
            font-size: 2.5em;
            animation: bell-ring 1s infinite;
        }

        @keyframes bell-ring {
            0%, 100% { transform: rotate(0deg); }
            10%, 30% { transform: rotate(-10deg); }
            20%, 40% { transform: rotate(10deg); }
            50% { transform: rotate(0deg); }
        }

        .subscription-timer-header h3 {
            margin: 0;
            font-size: 1.5em;
            font-weight: 700;
            text-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }

        .subscription-timer-content {
            position: relative;
            z-index: 1;
        }

        .subscription-timer-content p {
            margin: 0 0 15px 0;
            font-size: 1.1em;
            opacity: 0.95;
        }

        .countdown-display {
            display: flex;
            justify-content: center;
            gap: 15px;
            flex-wrap: wrap;
        }

        .countdown-unit {
            background: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(10px);
            border-radius: 10px;
            padding: 15px 20px;
            min-width: 90px;
            text-align: center;
            border: 2px solid rgba(255, 255, 255, 0.2);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
        }

        .countdown-number {
            display: block;
            font-size: 2.5em;
            font-weight: 700;
            line-height: 1;
            text-shadow: 0 2px 4px rgba(0,0,0,0.3);
        }

        .countdown-label {
            display: block;
            font-size: 0.9em;
            margin-top: 5px;
            opacity: 0.9;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .timer-expired {
            background: linear-gradient(135deg, #dc2626 0%, #991b1b 100%);
        }

        .timer-critical {
            animation: pulseWarning 1s infinite, critical-flash 0.5s infinite;
        }

        @keyframes critical-flash {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.8; }
        }

        @media (max-width: 768px) {
            .subscription-timer-container {
                padding: 15px 20px;
            }
            .subscription-timer-header h3 {
                font-size: 1.2em;
            }
            .countdown-unit {
                min-width: 70px;
                padding: 10px 15px;
            }
            .countdown-number {
                font-size: 2em;
            }
            .countdown-label {
                font-size: 0.75em;
            }
        }
    </style>
</head>
<body>
    <div class="dashboard-container" id="dashboardContainer">
        <!-- Sidebar -->
        <aside class="sidebar" id="sidebar">
            <div class="logo">
                <img src="images/logo.png" alt="Divine Logo">
               <br> <h8>DIVINE REPORTS</h8></br>
            </div>
            <nav>
                <ul>
                    <li class="active"><a href="super_admin_dashboard.php"><i class="fas fa-th-large"></i> Dashboard</a></li>
                    
                    <li><a href="super_admin_add_school.php"><i class="fas fa-plus-circle"></i> Add School</a></li>
                    <li><a href="super_admin_broadcast.php"><i class="fas fa-bullhorn"></i> Broadcast</a></li>
                    <li><a href="super_admin_invoices.php"><i class="fas fa-file-invoice-dollar"></i> Invoices</a></li>
                    <li><a href="super_admin_payments.php"><i class="fas fa-credit-card"></i> Payments</a></li>
                    <li><a href="super_admin_surveys.php"><i class="fas fa-poll"></i> Surveys</a></li>
                    <li><a href="super_admin_backups.php"><i class="fas fa-database"></i> Backups</a></li>
                    <li><a href="super_admin_reports.php"><i class="fas fa-chart-line"></i> Reports</a></li>
                    <li><a href="super_admin_settings.php"><i class="fas fa-cog"></i> Settings</a></li>
                    <li><a href="logout.php" class="logout-btn"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
                </ul>
            </nav>
        </aside>

        <div class="main-content">
            <header class="header">
                <button class="menu-toggle" id="menuToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="school-info">
                    <img src="images/logo.png" alt="Divine Reports Logo">
                    <h1>DIVINE REPORTS</h1>
                </div>
                <div class="header-right">
                    <div class="search-bar">
                        <i class="fas fa-search"></i>
                        <input type="text" placeholder="Search schools..." id="searchPlaceholder">
                    </div>
                    <div class="notifications">
                        <i class="fas fa-bell"></i>
                        <span class="badge">0</span>
                    </div>
                    <div class="user-profile">
                        <img src="<?php echo $photo; ?>" alt="User Photo">
                        <div>
                            <div class="user-name"><?php echo $username; ?></div>
                            <div class="user-email">Logged in as: <?php echo $role_name; ?></div>
                        </div>
                        <i class="fas fa-chevron-down"></i>
                    </div>
                </div>
            </header>

            <div class="dashboard-content">
                <div class="welcome-banner">
                    <img src="<?php echo $photo; ?>" alt="User Avatar" class="user-avatar">
                    <div class="welcome-text">
                        <h3>Welcome <?php echo $username; ?>!</h3>
                        <p>Manage all schools and system operations from your super admin dashboard.</p>
                    </div>
                    <a href="super_admin_add_school.php" class="action-button">Add New School</a>
                </div>

                <!-- Dashboard Statistics -->
                <div class="dashboard-stats">
                    <div class="stat-card schools">
                        <i class="fas fa-school icon"></i>
                        <div class="count"><?php echo $totalSchools; ?></div>
                        <div class="label">Total Schools</div>
                        <a href="super_admin_add_school.php" class="arrow"><i class="fas fa-arrow-right"></i></a>
                    </div>
                    <div class="stat-card active-schools">
                        <i class="fas fa-check-circle icon"></i>
                        <div class="count"><?php echo $activeSchools; ?></div>
                        <div class="label">Active Schools</div>
                        <a href="super_admin_dashboard.php?filter=active" class="arrow"><i class="fas fa-arrow-right"></i></a>
                    </div>
                    <div class="stat-card suspended">
                        <i class="fas fa-ban icon"></i>
                        <div class="count"><?php echo $suspendedSchools; ?></div>
                        <div class="label">Suspended Schools</div>
                        <a href="super_admin_dashboard.php?filter=suspended" class="arrow"><i class="fas fa-arrow-right"></i></a>
                    </div>
                    <div class="stat-card revenue">
                        <i class="fas fa-money-bill-wave icon"></i>
                        <div class="count">UGX <?php echo number_format($totalRevenue); ?></div>
                        <div class="label">Total Revenue</div>
                        <a href="super_admin_payments.php" class="arrow"><i class="fas fa-arrow-right"></i></a>
                    </div>
                    <div class="stat-card admins">
                        <i class="fas fa-user-shield icon"></i>
                        <div class="count"><?php echo $totalAdmins; ?></div>
                        <div class="label">Total Admins</div>
                    </div>
                    <div class="stat-card teachers">
                        <i class="fas fa-chalkboard-teacher icon"></i>
                        <div class="count"><?php echo $totalTeachers; ?></div>
                        <div class="label">Total Teachers</div>
                    </div>
                    <div class="stat-card students">
                        <i class="fas fa-user-graduate icon"></i>
                        <div class="count"><?php echo $totalStudents; ?></div>
                        <div class="label">Total Students</div>
                    </div>
                    <div class="stat-card pending">
                        <i class="fas fa-clock icon"></i>
                        <div class="count"><?php echo $pendingPayments; ?></div>
                        <div class="label">Pending Payments</div>
                        <a href="super_admin_payments.php?filter=pending" class="arrow"><i class="fas fa-arrow-right"></i></a>
                    </div>
                </div>

                <!-- Quick Actions -->
                <div class="schools-table-card">
                    <h3>Quick Actions</h3>
                    <div class="quick-actions">
                        <a href="#" class="quick-action-card" onclick="openAddSchoolModal(); return false;">
                            <i class="fas fa-plus-circle"></i>
                            <h4>Add New School</h4>
                        </a>
                        <a href="#" class="quick-action-card" onclick="openBroadcastModal(); return false;">
                            <i class="fas fa-bullhorn"></i>
                            <h4>Send Broadcast</h4>
                        </a>
                        <a href="#" class="quick-action-card" onclick="openInvoiceModal(); return false;">
                            <i class="fas fa-file-invoice-dollar"></i>
                            <h4>Generate Invoice</h4>
                        </a>
                        <a href="#" class="quick-action-card" onclick="openBackupModal(); return false;">
                            <i class="fas fa-database"></i>
                            <h4>Backup Data</h4>
                        </a>
                        <a href="super_admin_surveys.php" class="quick-action-card">
                            <i class="fas fa-poll"></i>
                            <h4>Create Survey</h4>
                        </a>
                        <a href="super_admin_reports.php" class="quick-action-card">
                            <i class="fas fa-chart-bar"></i>
                            <h4>View Reports</h4>
                        </a>
                    </div>
                </div>

                <!-- Schools Management Table -->
                <div class="schools-table-card">
                    <h3>
                        <span>Schools Management</span>
                        <input type="text" id="searchSchools" placeholder="Search schools..." style="padding: 8px; border: 1px solid #ddd; border-radius: 6px; width: 300px;">
                    </h3>
                    <div style="background-color: #f0f9ff; border: 1px solid #0ea5e9; border-radius: 8px; padding: 15px; margin-bottom: 20px; display: flex; align-items: center; gap: 10px;">
                        <i class="fas fa-info-circle" style="color: #0ea5e9; font-size: 1.2em;"></i>
                        <div>
                            <strong style="color: #0c4a6e;">Automatic Suspension System:</strong>
                            <span style="color: #075985;">Schools with expired subscriptions are automatically suspended. Super admins can reactivate them using the Activate button, which will also clear their subscription expiry dates.</span>
                        </div>
                    </div>
                    <div style="overflow-x: auto;">
                        <table class="schools-table" id="schoolsTable">
                            <thead>
                                <tr>
                                    <th>Logo</th>
                                    <th>School Name</th>
                                    <th>Abbreviation</th>
                                    <th>Contact</th>
                                    <th>Admins</th>
                                    <th>Teachers</th>
                                    <th>Students</th>
                                    <th>Subscription Expiry</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($schoolsList as $school): ?>
                                <tr data-school-id="<?php echo $school['school_id']; ?>">
                                    <td>
                                        <img src="<?php echo htmlspecialchars($school['logo'] ?? 'default_school_logo.php'); ?>" 
                                             alt="<?php echo htmlspecialchars($school['school_name']); ?>" 
                                             style="width: 40px; height: 40px; border-radius: 6px; object-fit: cover;">
                                    </td>
                                    <td><?php echo htmlspecialchars($school['school_name']); ?></td>
                                    <td><?php echo htmlspecialchars($school['abbreviation'] ?? 'N/A'); ?></td>
                                    <td>
                                        <?php echo htmlspecialchars($school['email'] ?? 'N/A'); ?><br>
                                        <small><?php echo htmlspecialchars($school['phone'] ?? 'N/A'); ?></small>
                                    </td>
                                    <td><?php echo $school['admin_count']; ?></td>
                                    <td><?php echo $school['teacher_count']; ?></td>
                                    <td><?php echo $school['student_count']; ?></td>
                                    <td>
                                        <?php if (!empty($school['subscription_expiry_date'])): ?>
                                            <small style="color: <?php echo (strtotime($school['subscription_expiry_date']) < strtotime('+7 days')) ? '#ef4444' : '#10b981'; ?>;">
                                                <?php echo date('M j, Y', strtotime($school['subscription_expiry_date'])); ?>
                                            </small>
                                        <?php else: ?>
                                            <small style="color: #999;">Not Set</small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="status-badge 
                                            <?php 
                                            if ($school['suspension_type'] === 'active') {
                                                echo 'status-active';
                                            } elseif ($school['suspension_type'] === 'auto_suspended') {
                                                echo 'status-auto-suspended';
                                            } else {
                                                echo 'status-suspended';
                                            }
                                            ?>
                                        ">
                                            <?php 
                                            if ($school['suspension_type'] === 'active') {
                                                echo 'Active';
                                            } elseif ($school['suspension_type'] === 'auto_suspended') {
                                                echo 'Auto-Suspended';
                                            } else {
                                                echo 'Suspended';
                                            }
                                            ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div class="action-buttons">
                                            <button class="btn btn-info" onclick="viewSchool(<?php echo $school['school_id']; ?>)" title="View Details">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            <?php if ($school['suspension_type'] === 'active'): ?>
                                                <button class="btn btn-warning" onclick="suspendSchool(<?php echo $school['school_id']; ?>, '<?php echo htmlspecialchars($school['school_name']); ?>')" title="Suspend">
                                                    <i class="fas fa-ban"></i>
                                                </button>
                                            <?php else: ?>
                                                <button class="btn btn-success" onclick="activateSchool(<?php echo $school['school_id']; ?>, '<?php echo htmlspecialchars($school['school_name']); ?>', '<?php echo $school['suspension_type']; ?>')" title="Activate">
                                                    <i class="fas fa-check"></i>
                                                </button>
                                            <?php endif; ?>
                                            <button class="btn btn-primary" onclick="sendMessage(<?php echo $school['school_id']; ?>, '<?php echo htmlspecialchars($school['school_name']); ?>')" title="Send Message">
                                                <i class="fas fa-envelope"></i>
                                            </button>
                                            <button class="btn" style="background-color: #8b5cf6; color: white;" onclick="setExpiry(<?php echo $school['school_id']; ?>, '<?php echo htmlspecialchars($school['school_name']); ?>', '<?php echo $school['subscription_expiry_date'] ?? ''; ?>')" title="Set Subscription Expiry">
                                                <i class="fas fa-calendar-alt"></i>
                                            </button>
                                            <?php if (!empty($school['subscription_expiry_date'])): ?>
                                            <button class="btn" style="background-color: #64748b; color: white;" onclick="clearExpiry(<?php echo $school['school_id']; ?>, '<?php echo htmlspecialchars($school['school_name']); ?>')" title="Clear Timer">
                                                <i class="fas fa-times-circle"></i>
                                            </button>
                                            <?php endif; ?>
                                            <button class="btn btn-danger" onclick="deleteSchool(<?php echo $school['school_id']; ?>, '<?php echo htmlspecialchars($school['school_name']); ?>')" title="Delete">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Schools Status Overview with Multiple Charts -->
                <div class="schools-table-card">
                    <h3><i class="fas fa-chart-pie"></i> Analytics Dashboard</h3>
                    
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 1fr)); gap: 30px; margin-top: 20px;">
                        <!-- Schools Status Chart -->
                        <div>
                            <h4 style="color: #333; margin-bottom: 15px; text-align: center;">Schools Status Overview</h4>
                            <div class="chart-container">
                                <canvas id="schoolsStatusChart"></canvas>
                            </div>
                        </div>

                        <!-- Users Distribution Chart -->
                        <div>
                            <h4 style="color: #333; margin-bottom: 15px; text-align: center;">Users Distribution by Role</h4>
                            <div class="chart-container">
                                <canvas id="usersDistributionChart"></canvas>
                            </div>
                        </div>

                        <!-- Schools Growth Chart -->
                        <div>
                            <h4 style="color: #333; margin-bottom: 15px; text-align: center;">Schools Growth (Last 6 Months)</h4>
                            <div class="chart-container">
                                <canvas id="schoolsGrowthChart"></canvas>
                            </div>
                        </div>

                        <!-- Top Schools Chart -->
                        <div>
                            <h4 style="color: #333; margin-bottom: 15px; text-align: center;">Top 5 Schools by Users</h4>
                            <div class="chart-container">
                                <canvas id="topSchoolsChart"></canvas>
                            </div>
                        </div>

                        <!-- Payment Trends Chart -->
                        <div>
                            <h4 style="color: #333; margin-bottom: 15px; text-align: center;">Payment Trends (Last 6 Months)</h4>
                            <div class="chart-container">
                                <canvas id="paymentTrendsChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Mobile Footer Navigation -->
        <div id="mobile-footer-nav">
            <ul>
                <li>
                    <a href="super_admin_dashboard.php" class="active">
                        <i class="fas fa-th-large"></i>
                        <span>Dashboard</span>
                    </a>
                </li>
                <li>
                    <a href="super_admin_schools.php">
                        <i class="fas fa-school"></i>
                        <span>Schools</span>
                    </a>
                </li>
                <li>
                    <a href="super_admin_broadcast.php">
                        <i class="fas fa-bullhorn"></i>
                        <span>Broadcast</span>
                    </a>
                </li>
                <li>
                    <a href="#" id="moreMenuButton">
                        <i class="fas fa-ellipsis-h"></i>
                        <span>More</span>
                    </a>
                </li>
            </ul>
        </div>
    </div>

    <!-- More Menu Modal -->
    <div id="moreMenuModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 400px; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 10000;">
            <div class="modal-header" style="background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%); color: white; margin: -20px -20px 20px -20px; padding: 20px; border-radius: 8px 8px 0 0;">
                <div style="display: flex; align-items: center; justify-content: space-between; width: 100%;">
                    <div style="display: flex; align-items: center; gap: 15px;">
                        <i class="fas fa-ellipsis-h" style="font-size: 1.5em;"></i>
                        <h3 style="margin: 0; color: white;">More Options</h3>
                    </div>
                    <button onclick="closeActionModal('moreMenuModal')" style="background: none; border: none; color: white; font-size: 1.2em; cursor: pointer; opacity: 0.8;" onmouseover="this.style.opacity='1'" onmouseout="this.style.opacity='0.8'">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
            <div class="modal-body">
                <div style="display: flex; flex-direction: column; gap: 10px;">
                    <a href="super_admin_reports.php" class="mobile-menu-item">
                        <i class="fas fa-chart-bar"></i>
                        <span>Reports</span>
                    </a>
                    <a href="super_admin_settings.php" class="mobile-menu-item">
                        <i class="fas fa-cog"></i>
                        <span>Settings</span>
                    </a>
                    <a href="super_admin_users.php" class="mobile-menu-item">
                        <i class="fas fa-users"></i>
                        <span>Manage Users</span>
                    </a>
                    <a href="super_admin_payments.php" class="mobile-menu-item">
                        <i class="fas fa-credit-card"></i>
                        <span>Payments</span>
                    </a>
                    <a href="super_admin_backup.php" class="mobile-menu-item">
                        <i class="fas fa-database"></i>
                        <span>Backup & Restore</span>
                    </a>
                    <a href="super_admin_logs.php" class="mobile-menu-item">
                        <i class="fas fa-list-alt"></i>
                        <span>System Logs</span>
                    </a>
                    <a href="logout.php" class="mobile-menu-item" style="color: #dc2626;">
                        <i class="fas fa-sign-out-alt"></i>
                        <span>Logout</span>
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- View School Details Modal -->
    <div id="viewSchoolModal" class="modal">
        <div class="modal-content" style="max-width: 800px;">
            <div class="modal-header" style="background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%); color: white; margin: -30px -30px 20px -30px; padding: 25px 30px; border-radius: 12px 12px 0 0;">
                <div style="display: flex; align-items: center; justify-content: space-between; width: 100%;">
                    <div style="display: flex; align-items: center; gap: 15px;">
                        <i class="fas fa-school" style="font-size: 2em;"></i>
                        <h3 style="margin: 0; color: white;">School Details</h3>
                    </div>
                    <button onclick="closeActionModal('viewSchoolModal')" style="background: none; border: none; color: white; font-size: 1.5em; cursor: pointer; opacity: 0.8;" onmouseover="this.style.opacity='1'" onmouseout="this.style.opacity='0.8'">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
            <div class="modal-body">
                <div style="display: grid; grid-template-columns: 150px 1fr; gap: 20px; margin-bottom: 30px;">
                    <div style="text-align: center;">
                        <img id="detail_logo" src="" alt="School Logo" style="width: 120px; height: 120px; border-radius: 12px; object-fit: cover; border: 3px solid #e5e7eb;">
                    </div>
                    <div>
                        <h2 id="detail_school_name" style="margin: 0 0 10px 0; color: #333;"></h2>
                        <p style="margin: 0; color: #666;"><strong>Abbreviation:</strong> <span id="detail_abbreviation"></span></p>
                        <p style="margin: 5px 0; color: #666;"><strong>Status:</strong> <span id="detail_status" class="status-badge"></span></p>
                    </div>
                </div>

                <div style="background: #f9fafb; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                    <h4 style="margin: 0 0 15px 0; color: #4f46e5;"><i class="fas fa-info-circle"></i> Contact Information</h4>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;">
                        <div>
                            <p style="margin: 0; color: #888; font-size: 0.9em;">Email Address</p>
                            <p id="detail_email" style="margin: 5px 0; color: #333; font-weight: 500;"></p>
                        </div>
                        <div>
                            <p style="margin: 0; color: #888; font-size: 0.9em;">Phone Number</p>
                            <p id="detail_phone" style="margin: 5px 0; color: #333; font-weight: 500;"></p>
                        </div>
                        <div style="grid-column: 1 / -1;">
                            <p style="margin: 0; color: #888; font-size: 0.9em;">Address</p>
                            <p id="detail_address" style="margin: 5px 0; color: #333; font-weight: 500;"></p>
                        </div>
                    </div>
                </div>

                <div style="background: #f0f9ff; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                    <h4 style="margin: 0 0 15px 0; color: #3b82f6;"><i class="fas fa-users"></i> User Statistics</h4>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 15px; text-align: center;">
                        <div style="background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 6px rgba(0,0,0,0.05);">
                            <div id="detail_admins" style="font-size: 2em; font-weight: bold; color: #6366f1;"></div>
                            <div style="color: #666; font-size: 0.9em; margin-top: 5px;">Admins</div>
                        </div>
                        <div style="background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 6px rgba(0,0,0,0.05);">
                            <div id="detail_teachers" style="font-size: 2em; font-weight: bold; color: #8b5cf6;"></div>
                            <div style="color: #666; font-size: 0.9em; margin-top: 5px;">Teachers</div>
                        </div>
                        <div style="background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 6px rgba(0,0,0,0.05);">
                            <div id="detail_students" style="font-size: 2em; font-weight: bold; color: #ec4899;"></div>
                            <div style="color: #666; font-size: 0.9em; margin-top: 5px;">Students</div>
                        </div>
                        <div style="background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 6px rgba(0,0,0,0.05);">
                            <div id="detail_total_users" style="font-size: 2em; font-weight: bold; color: #10b981;"></div>
                            <div style="color: #666; font-size: 0.9em; margin-top: 5px;">Total Users</div>
                        </div>
                    </div>
                </div>

                <div style="background: #fef3c7; padding: 15px; border-radius: 8px; border-left: 4px solid #f59e0b;">
                    <p style="margin: 0; color: #92400e;"><i class="fas fa-calendar-alt"></i> <strong>Created On:</strong> <span id="detail_created"></span></p>
                </div>
            </div>
            <div class="modal-footer">
                <button onclick="closeActionModal('viewSchoolModal')" class="btn-modal btn-primary" style="background-color: #4f46e5;">
                    <i class="fas fa-check"></i> Close
                </button>
            </div>
        </div>
    </div>

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

    <!-- Suspend Confirmation Modal -->
    <div id="suspendModal" class="modal">
        <div class="modal-content">
            <div class="modal-header warning">
                <i class="fas fa-exclamation-triangle"></i>
                <h3>Confirm Suspend School</h3>
            </div>
            <div class="modal-body">
                <p><strong>Warning:</strong> Are you sure you want to suspend <strong id="suspend_school_name"></strong>?</p>
                <p>The school will lose access to the system until reactivated.</p>
            </div>
            <div class="modal-footer">
                <button onclick="closeActionModal('suspendModal')" class="btn-modal btn-cancel">
                    <i class="fas fa-times"></i> Cancel
                </button>
                <form method="POST" style="display: inline;" id="suspendForm" onsubmit="event.preventDefault(); performAction('suspend', document.getElementById('suspend_school_id').value); closeActionModal('suspendModal');">
                    <input type="hidden" id="suspend_school_id" value="">
                    <button type="submit" class="btn-modal btn-confirm-warning">
                        <i class="fas fa-ban"></i> Yes, Suspend School
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- Activate Confirmation Modal -->
    <div id="activateModal" class="modal">
        <div class="modal-content">
            <div class="modal-header success">
                <i class="fas fa-check-circle"></i>
                <h3>Confirm Activate School</h3>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to activate <strong id="activate_school_name"></strong>?</p>
                <p>The school will regain access to the system.</p>
            </div>
            <div class="modal-footer">
                <button onclick="closeActionModal('activateModal')" class="btn-modal btn-cancel">
                    <i class="fas fa-times"></i> Cancel
                </button>
                <form method="POST" style="display: inline;" id="activateForm" onsubmit="event.preventDefault(); performActivation(document.getElementById('activate_school_id').value); closeActionModal('activateModal');">
                    <input type="hidden" id="activate_school_id" value="">
                    <button type="submit" class="btn-modal btn-confirm-success">
                        <i class="fas fa-check"></i> Yes, Activate School
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div id="deleteModal" class="modal">
        <div class="modal-content">
            <div class="modal-header danger">
                <i class="fas fa-trash-alt"></i>
                <h3>Confirm Delete School</h3>
            </div>
            <div class="modal-body">
                <p><strong>⚠️ CRITICAL WARNING:</strong> This will permanently delete <strong id="delete_school_name"></strong> and ALL associated data including:</p>
                <ul style="margin: 15px 0; padding-left: 25px;">
                    <li>All users (admins, teachers, students)</li>
                    <li>All invoices and payment records</li>
                    <li>All academic records</li>
                    <li>All school data</li>
                </ul>
                <p style="color: #ef4444; font-weight: bold;">This action CANNOT be undone!</p>
                <div style="background-color: #fee2e2; padding: 15px; border-radius: 6px; margin-top: 15px;">
                    <label style="display: flex; align-items: center; cursor: pointer;">
                        <input type="checkbox" id="deleteConfirmCheckbox" style="margin-right: 10px;">
                        <span>I understand this action is permanent and cannot be reversed</span>
                    </label>
                </div>
            </div>
            <div class="modal-footer">
                <button onclick="closeActionModal('deleteModal')" class="btn-modal btn-cancel">
                    <i class="fas fa-times"></i> Cancel
                </button>
                <form method="POST" style="display: inline;" id="deleteForm" onsubmit="event.preventDefault(); if(document.getElementById('deleteConfirmCheckbox').checked) { performAction('delete', document.getElementById('delete_school_id').value); closeActionModal('deleteModal'); } else { showNotification('Please confirm you understand this action is permanent', 'error'); }">
                    <input type="hidden" id="delete_school_id" value="">
                    <button type="submit" class="btn-modal btn-confirm-delete">
                        <i class="fas fa-trash"></i> Yes, Delete Permanently
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- Set Expiry Modal -->
    <div id="setExpiryModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeActionModal('setExpiryModal')">&times;</span>
            <div class="modal-header warning">
                <i class="fas fa-calendar-alt"></i>
                <h3>Set Subscription Expiry Date</h3>
            </div>
            <div class="modal-body">
                <p><strong>School:</strong> <span id="expiry_school_name"></span></p>
                <p>Set when this school's subscription will expire. A countdown timer will appear on their admin dashboard.</p>
                <input type="hidden" id="expiry_school_id" value="">
                <div class="form-group">
                    <label for="expiry_date">Expiry Date:</label>
                    <input type="date" id="expiry_date" class="form-control" required>
                    <small style="color: #666; display: block; margin-top: 5px;">Current: <span id="current_expiry">Not Set</span></small>
                </div>
            </div>
            <div class="modal-footer">
                <button onclick="closeActionModal('setExpiryModal')" class="btn-modal btn-cancel">
                    <i class="fas fa-times"></i> Cancel
                </button>
                <button onclick="saveExpiry()" class="btn-modal btn-confirm-warning">
                    <i class="fas fa-save"></i> Save Expiry Date
                </button>
            </div>
        </div>
    </div>

    <!-- Clear Timer Confirmation Modal -->
    <div id="clearTimerModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeActionModal('clearTimerModal')">&times;</span>
            <div class="modal-header warning">
                <i class="fas fa-times-circle"></i>
                <h3>Clear Subscription Timer</h3>
            </div>
            <div class="modal-body">
                <p><strong>School:</strong> <span id="clear_timer_school_name"></span></p>
                <p>Are you sure you want to clear the subscription timer for this school?</p>
                <p style="color: #666; margin-top: 10px;">The countdown timer will be removed from their dashboard.</p>
                <input type="hidden" id="clear_timer_school_id" value="">
            </div>
            <div class="modal-footer">
                <button onclick="closeActionModal('clearTimerModal')" class="btn-modal btn-cancel">
                    <i class="fas fa-times"></i> Cancel
                </button>
                <button onclick="confirmClearExpiry()" class="btn-modal btn-confirm-warning">
                    <i class="fas fa-check"></i> Yes, Clear Timer
                </button>
            </div>
        </div>
    </div>

    <script>
        // Log JavaScript errors to console
        window.addEventListener('error', function(e) {
            console.error('JavaScript Error:', e.message, 'at line', e.lineno, 'column', e.colno);
        });
        
        window.addEventListener('unhandledrejection', function(e) {
            console.error('Unhandled Promise Rejection:', e.reason);
        });
        
        console.log('Super Admin Dashboard JavaScript loaded');
        // Chart.js for Schools Status (Doughnut Chart)
        const statusLabels = <?php echo $statusLabels; ?>;
        const statusData = <?php echo $statusData; ?>;

        if (document.getElementById('schoolsStatusChart')) {
            const ctx1 = document.getElementById('schoolsStatusChart').getContext('2d');
            new Chart(ctx1, {
                type: 'doughnut',
                data: {
                    labels: statusLabels,
                    datasets: [{
                        data: statusData,
                        backgroundColor: ['#10b981', '#64748b'],
                        borderWidth: 2,
                        borderColor: '#fff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });
        }

        // Users Distribution Chart (Bar Chart)
        const usersLabels = <?php echo $usersLabels; ?>;
        const usersData = <?php echo $usersData; ?>;

        if (document.getElementById('usersDistributionChart')) {
            const ctx2 = document.getElementById('usersDistributionChart').getContext('2d');
            new Chart(ctx2, {
                type: 'bar',
                data: {
                    labels: usersLabels,
                    datasets: [{
                        label: 'Number of Users',
                        data: usersData,
                        backgroundColor: ['#6366f1', '#8b5cf6', '#ec4899'],
                        borderWidth: 0,
                        borderRadius: 8
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                stepSize: 1
                            }
                        }
                    }
                }
            });
        }

        // Schools Growth Chart (Line Chart)
        const growthLabels = <?php echo $growthLabels; ?>;
        const growthData = <?php echo $growthData; ?>;

        if (document.getElementById('schoolsGrowthChart')) {
            const ctx3 = document.getElementById('schoolsGrowthChart').getContext('2d');
            new Chart(ctx3, {
                type: 'line',
                data: {
                    labels: growthLabels,
                    datasets: [{
                        label: 'New Schools',
                        data: growthData,
                        borderColor: '#4f46e5',
                        backgroundColor: 'rgba(79, 70, 229, 0.1)',
                        borderWidth: 3,
                        fill: true,
                        tension: 0.4,
                        pointBackgroundColor: '#4f46e5',
                        pointBorderColor: '#fff',
                        pointBorderWidth: 2,
                        pointRadius: 5
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                stepSize: 1
                            }
                        }
                    }
                }
            });
        }

        // Top Schools Chart (Horizontal Bar Chart)
        const topSchoolsLabels = <?php echo $topSchoolsLabels; ?>;
        const topSchoolsData = <?php echo $topSchoolsDataValues; ?>;

        if (document.getElementById('topSchoolsChart')) {
            const ctx4 = document.getElementById('topSchoolsChart').getContext('2d');
            new Chart(ctx4, {
                type: 'bar',
                data: {
                    labels: topSchoolsLabels,
                    datasets: [{
                        label: 'Total Users',
                        data: topSchoolsData,
                        backgroundColor: '#10b981',
                        borderWidth: 0,
                        borderRadius: 8
                    }]
                },
                options: {
                    indexAxis: 'y',
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        x: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }

        // Payment Trends Chart (Area Chart)
        const paymentLabels = <?php echo $paymentLabels; ?>;
        const paymentAmounts = <?php echo $paymentAmounts; ?>;

        if (document.getElementById('paymentTrendsChart')) {
            const ctx5 = document.getElementById('paymentTrendsChart').getContext('2d');
            new Chart(ctx5, {
                type: 'line',
                data: {
                    labels: paymentLabels,
                    datasets: [{
                        label: 'Payment Amount (UGX)',
                        data: paymentAmounts,
                        borderColor: '#f59e0b',
                        backgroundColor: 'rgba(245, 158, 11, 0.1)',
                        borderWidth: 3,
                        fill: true,
                        tension: 0.4,
                        pointBackgroundColor: '#f59e0b',
                        pointBorderColor: '#fff',
                        pointBorderWidth: 2,
                        pointRadius: 6,
                        pointHoverRadius: 8
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: true,
                            position: 'bottom'
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    let label = context.dataset.label || '';
                                    if (label) {
                                        label += ': ';
                                    }
                                    if (context.parsed.y !== null) {
                                        label += 'UGX ' + context.parsed.y.toLocaleString();
                                    }
                                    return label;
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function(value) {
                                    return 'UGX ' + value.toLocaleString();
                                }
                            }
                        }
                    }
                }
            });
        }

        // Search functionality
        document.getElementById('searchSchools').addEventListener('keyup', function() {
            const searchTerm = this.value.toLowerCase();
            const tableRows = document.querySelectorAll('#schoolsTable tbody tr');
            
            tableRows.forEach(row => {
                const schoolName = row.cells[1].textContent.toLowerCase();
                const abbreviation = row.cells[2].textContent.toLowerCase();
                const email = row.cells[3].textContent.toLowerCase();
                
                if (schoolName.includes(searchTerm) || abbreviation.includes(searchTerm) || email.includes(searchTerm)) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        });

        // Action functions
        function viewSchool(schoolId) {
            // Fetch school details via AJAX
            fetch(`super_admin_get_school.php?school_id=${schoolId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        populateSchoolDetailsModal(data.school);
                        document.getElementById('viewSchoolModal').style.display = 'block';
                    } else {
                        showNotification('Error loading school details: ' + data.message, 'error');
                    }
                })
                .catch(error => {
                    showNotification('Error loading school details: ' + error, 'error');
                });
        }

        function populateSchoolDetailsModal(school) {
            document.getElementById('detail_school_name').textContent = school.school_name;
            document.getElementById('detail_abbreviation').textContent = school.abbreviation || 'N/A';
            document.getElementById('detail_email').textContent = school.email || 'N/A';
            document.getElementById('detail_phone').textContent = school.phone || 'N/A';
            document.getElementById('detail_address').textContent = school.address || 'N/A';
            document.getElementById('detail_created').textContent = school.created_at;
            document.getElementById('detail_admins').textContent = school.admin_count;
            document.getElementById('detail_teachers').textContent = school.teacher_count;
            document.getElementById('detail_students').textContent = school.student_count;
            document.getElementById('detail_total_users').textContent = school.total_users;
            document.getElementById('detail_status').textContent = school.status;
            if (school.status === 'Active') {
                document.getElementById('detail_status').className = 'status-badge status-active';
            } else if (school.suspension_type === 'auto_suspended') {
                document.getElementById('detail_status').className = 'status-badge status-auto-suspended';
            } else {
                document.getElementById('detail_status').className = 'status-badge status-suspended';
            }
            
            const logoImg = document.getElementById('detail_logo');
            if (school.logo) {
                logoImg.src = school.logo;
            } else {
                logoImg.src = 'default_school_logo.php';
            }
        }

        function suspendSchool(schoolId, schoolName) {
            // Safe DOM access with null checks
            const schoolIdElement = document.getElementById('suspend_school_id');
            const schoolNameElement = document.getElementById('suspend_school_name');
            const modalElement = document.getElementById('suspendModal');
            
            if (schoolIdElement) {
                schoolIdElement.value = schoolId;
            }
            
            if (schoolNameElement) {
                schoolNameElement.textContent = schoolName;
            }
            
            if (modalElement) {
                modalElement.style.display = 'block';
            }
        }

        function activateSchool(schoolId, schoolName, suspensionType = '') {
            console.log('activateSchool called with:', {schoolId, schoolName, suspensionType});
            
            // Safe DOM access with null checks
            const schoolIdElement = document.getElementById('activate_school_id');
            const schoolNameElement = document.getElementById('activate_school_name');
            const modalElement = document.getElementById('activateModal');
            
            if (schoolIdElement) {
                schoolIdElement.value = schoolId;
            }
            
            if (schoolNameElement) {
                schoolNameElement.textContent = schoolName;
            }
            
            // Update modal message based on suspension type
            if (modalElement) {
                const modalBody = modalElement.querySelector('.modal-body');
                if (modalBody) {
                    const messageElement = modalBody.querySelector('p');
                    if (messageElement) {
                        if (suspensionType === 'auto_suspended') {
                            messageElement.innerHTML = `Are you sure you want to activate <strong>${schoolName}</strong>?<br><br><small style="color: #f59e0b;"><i class="fas fa-info-circle"></i> This school was automatically suspended due to expired subscription. Activating will restore access and clear the suspension.</small>`;
                        } else {
                            messageElement.innerHTML = `Are you sure you want to activate <strong>${schoolName}</strong>?<br><br>The school will regain access to the system.`;
                        }
                    }
                }
                
                modalElement.style.display = 'block';
            }
        }

        function sendMessage(schoolId, schoolName) {
            window.location.href = 'super_admin_broadcast.php?school_id=' + schoolId;
        }

        function deleteSchool(schoolId, schoolName) {
            // Safe DOM access with null checks
            const schoolIdElement = document.getElementById('delete_school_id');
            const schoolNameElement = document.getElementById('delete_school_name');
            const modalElement = document.getElementById('deleteModal');
            
            if (schoolIdElement) {
                schoolIdElement.value = schoolId;
            }
            
            if (schoolNameElement) {
                schoolNameElement.textContent = schoolName;
            }
            
            if (modalElement) {
                modalElement.style.display = 'block';
            }
        }
        
        function setExpiry(schoolId, schoolName, currentExpiry) {
            // Safe DOM access with null checks
            const schoolIdElement = document.getElementById('expiry_school_id');
            const schoolNameElement = document.getElementById('expiry_school_name');
            const expiryDateElement = document.getElementById('expiry_date');
            const currentExpiryElement = document.getElementById('current_expiry');
            const modalElement = document.getElementById('setExpiryModal');
            
            if (schoolIdElement) {
                schoolIdElement.value = schoolId;
            }
            
            if (schoolNameElement) {
                schoolNameElement.textContent = schoolName;
            }
            
            if (expiryDateElement) {
                expiryDateElement.value = currentExpiry || '';
            }
            
            if (currentExpiryElement) {
                currentExpiryElement.textContent = currentExpiry ? new Date(currentExpiry).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }) : 'Not Set';
            }
            
            if (modalElement) {
                modalElement.style.display = 'block';
            }
        }
        
        function saveExpiry() {
            const schoolId = document.getElementById('expiry_school_id').value;
            const expiryDate = document.getElementById('expiry_date').value;
            
            if (!expiryDate) {
                showNotification('Please select an expiry date', 'error');
                return;
            }
            
            // Send AJAX request to save expiry date
            fetch('super_admin_set_expiry.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `school_id=${schoolId}&expiry_date=${expiryDate}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification(data.message, 'success');
                    closeActionModal('setExpiryModal');
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    showNotification('Error: ' + data.message, 'error');
                }
            })
            .catch(error => {
                showNotification('An error occurred: ' + error, 'error');
            });
        }
        
        function clearExpiry(schoolId, schoolName) {
            // Open modal instead of using confirm
            document.getElementById('clear_timer_school_id').value = schoolId;
            document.getElementById('clear_timer_school_name').textContent = schoolName;
            document.getElementById('clearTimerModal').style.display = 'block';
        }
        
        function confirmClearExpiry() {
            const schoolId = document.getElementById('clear_timer_school_id').value;
            
            // Send AJAX request to clear expiry date
            fetch('super_admin_set_expiry.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `school_id=${schoolId}&expiry_date=&clear=true`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification(data.message, 'success');
                    closeActionModal('clearTimerModal');
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    showNotification('Error: ' + data.message, 'error');
                }
            })
            .catch(error => {
                showNotification('An error occurred: ' + error, 'error');
            });
        }

        // More Menu Handler
        let moreMenuHandlerAttached = false;
        document.addEventListener('DOMContentLoaded', function() {
            if (!moreMenuHandlerAttached) {
                const moreMenuButton = document.getElementById('moreMenuButton');
                if (moreMenuButton) {
                    moreMenuButton.addEventListener('click', function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        const modal = document.getElementById('moreMenuModal');
                        if (modal) {
                            modal.style.display = 'block';
                        }
                    });
                    moreMenuHandlerAttached = true;
                }
            }
        });

        function closeActionModal(modalId) {
            const modalElement = document.getElementById(modalId);
            if (modalElement) {
                modalElement.style.display = 'none';
            }
        }
        
        function performAction(action, schoolId) {
            // Show loading
            const statusElement = document.querySelector(`[data-school-id="${schoolId}"] .status-badge`);
            const originalStatus = statusElement ? statusElement.textContent : '';
            if (statusElement) {
                statusElement.textContent = 'Processing...';
                statusElement.className = 'status-badge';
            }
            
            // Perform AJAX request
            fetch(`super_admin_actions.php?action=${action}&school_id=${schoolId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showNotification(data.message, 'success');
                        // Reload page to reflect changes after a short delay
                        setTimeout(() => {
                            window.location.reload();
                        }, 1500);
                    } else {
                        showNotification('Error: ' + data.message, 'error');
                        if (statusElement) {
                            statusElement.textContent = originalStatus;
                        }
                    }
                })
                .catch(error => {
                    showNotification('An error occurred: ' + error, 'error');
                    if (statusElement) {
                        statusElement.textContent = originalStatus;
                    }
                });
        }
        
        function performActivation(schoolId) {
            console.log('performActivation called with schoolId:', schoolId);
            
            // Validate schoolId
            if (!schoolId || schoolId === 'undefined' || schoolId === '') {
                console.error('Invalid schoolId:', schoolId);
                showNotification('Error: Invalid school ID', 'error');
                return;
            }
            
            // Show loading
            const statusElement = document.querySelector(`[data-school-id="${schoolId}"] .status-badge`);
            const originalStatus = statusElement ? statusElement.textContent : '';
            if (statusElement) {
                statusElement.textContent = 'Activating...';
                statusElement.className = 'status-badge';
            }
            
            // Perform AJAX request to activate school
            const url = `super_admin_actions.php?action=activate&school_id=${schoolId}&clear_expiry=true`;
            console.log('Making request to:', url);
            
            fetch(url)
                .then(response => {
                    console.log('Response status:', response.status);
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('Response data:', data);
                    if (data.success) {
                        showNotification(data.message, 'success');
                        // Reload page to reflect changes after a short delay
                        setTimeout(() => {
                            window.location.reload();
                        }, 1500);
                    } else {
                        showNotification('Error: ' + data.message, 'error');
                        if (statusElement) {
                            statusElement.textContent = originalStatus;
                            statusElement.className = 'status-badge';
                        }
                    }
                })
                .catch(error => {
                    console.error('Fetch error:', error);
                    showNotification('An error occurred: ' + error.message, 'error');
                    if (statusElement) {
                        statusElement.textContent = originalStatus;
                        statusElement.className = 'status-badge';
                    }
                });
        }
        
        function showNotification(message, type) {
            const notification = document.getElementById('notificationBox');
            const notificationMessage = document.getElementById('notificationMessage');
            const notificationIcon = document.getElementById('notificationIcon');
            
            notificationMessage.textContent = message;
            
            if (type === 'success') {
                notification.className = 'notification-box notification-success';
                notificationIcon.className = 'fas fa-check-circle';
            } else {
                notification.className = 'notification-box notification-error';
                notificationIcon.className = 'fas fa-exclamation-circle';
            }
            
            notification.style.display = 'block';
            
            // Auto-hide after 5 seconds
            setTimeout(() => {
                notification.style.opacity = '0';
                setTimeout(() => {
                    notification.style.display = 'none';
                    notification.style.opacity = '1';
                }, 500);
            }, 5000);
        }
        
        function closeNotification() {
            const notification = document.getElementById('notificationBox');
            notification.style.opacity = '0';
            setTimeout(() => {
                notification.style.display = 'none';
                notification.style.opacity = '1';
            }, 500);
        }

        function openAddSchoolModal() {
            window.location.href = 'super_admin_add_school.php';
        }

        function openBroadcastModal() {
            window.location.href = 'super_admin_broadcast.php';
        }

        function openInvoiceModal() {
            window.location.href = 'super_admin_invoices.php';
        }

        function openBackupModal() {
            window.location.href = 'super_admin_backups.php';
        }

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

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

        // Subscription Countdown Timer
        function updateCountdown() {
            const timerContainer = document.getElementById('subscriptionTimer');
            if (!timerContainer) return;

            const expiryDate = new Date(timerContainer.getAttribute('data-expiry') + ' 23:59:59').getTime();
            const now = new Date().getTime();
            const timeLeft = expiryDate - now;

            if (timeLeft <= 0) {
                // Subscription expired
                timerContainer.classList.add('timer-expired');
                document.querySelector('.subscription-timer-content p').innerHTML = '<strong>⚠️ YOUR SUBSCRIPTION HAS EXPIRED!</strong> Please renew immediately.';
                document.getElementById('weeks').textContent = '0';
                document.getElementById('days').textContent = '0';
                document.getElementById('hours').textContent = '0';
                document.getElementById('minutes').textContent = '0';
                document.getElementById('seconds').textContent = '0';
                return;
            }

            // Calculate time units
            const seconds = Math.floor((timeLeft / 1000) % 60);
            const minutes = Math.floor((timeLeft / 1000 / 60) % 60);
            const hours = Math.floor((timeLeft / (1000 * 60 * 60)) % 24);
            const totalDays = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
            const weeks = Math.floor(totalDays / 7);
            const days = totalDays % 7;

            // Update display
            document.getElementById('weeks').textContent = weeks;
            document.getElementById('days').textContent = days;
            document.getElementById('hours').textContent = hours.toString().padStart(2, '0');
            document.getElementById('minutes').textContent = minutes.toString().padStart(2, '0');
            document.getElementById('seconds').textContent = seconds.toString().padStart(2, '0');

            // Add critical warning if less than 7 days remaining
            if (totalDays < 7) {
                timerContainer.classList.add('timer-critical');
            }
        }

        // Update countdown every second
        updateCountdown();
        setInterval(updateCountdown, 1000);
    </script>
</body>
</html>
<?php
if (isset($conn) && $conn instanceof mysqli && $conn->ping()) {
    $conn->close();
}
?>