<?php
/**
 * Admin Dashboard - TutorKita System
 * Version: Fixed Add Teacher Functionality
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Start session if not started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Use absolute path from current file location
$db_path = dirname(__DIR__) . '/db.php';
require_once $db_path;

// Check admin session
if (!isset($_SESSION['user_type']) || $_SESSION['user_type'] !== 'admin') {
    header('Location: ../index.php');
    exit;
}

// Get admin settings
$admin = [];
$portalName = 'TutorKita';
$portalTagline = 'Platform Pembelajaran Terbaik';
$portalLogo = '';
$portalFavicon = '';
$themeColor = '#667eea';
$fontType = 'Segoe UI';
$fontSize = '14px';
$footerText = 'Hak Cipta Terpelihara 2026';

try {
    $stmt = $pdo->prepare("SELECT * FROM admin WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $admin = $stmt->fetch() ?: [];

    if ($admin) {
        $portalName = $admin['portal_name'] ?: 'TutorKita';
        $portalTagline = $admin['portal_tagline'] ?: 'Platform Pembelajaran Terbaik';
        $profileName = $admin['profile_name'] ?: 'Admin';
        $portalLogo = $admin['portal_logo'] ?: '';
        $portalFavicon = $admin['portal_favicon'] ?: '';
        $portalBackground = $admin['portal_background'] ?: '';
        $themeColor = $admin['theme_color'] ?: '#667eea';
        $fontType = $admin['font_type'] ?: 'Segoe UI';
        $fontSize = $admin['font_size'] ?: '14px';
        $footerText = $admin['footer_text'] ?: 'Hak Cipta Terpelihara 2026';
    }
} catch (Exception $e) {
    // Use defaults
}

// Get stats (No Subject Count)
$teacherCount = 0;
$studentCount = 0;

try {
    $teacherCount = $pdo->query("SELECT COUNT(*) FROM teachers WHERE status = 'Active'")->fetchColumn() ?: 0;
    $studentCount = $pdo->query("SELECT COUNT(*) FROM students WHERE status = 'Active'")->fetchColumn() ?: 0;
} catch (Exception $e) {
    // Use defaults
}

// Get OPR settings
$oprInfo = [
    'title' => 'One Page Report (OPR)',
    'description' => 'One Page Report merupakan dokumentasi ringkas yang menerangkan penggunaan One Page Report sebagai medium pelaporan utama dalam pengurusan.',
    'link' => 'https://www.canva.com/design/DAG6y7UmBKU/view'
];

try {
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'opr_info'");
    $stmt->execute();
    $oprData = $stmt->fetch();
    if ($oprData && $oprData['setting_value']) {
        $decoded = json_decode($oprData['setting_value'], true);
        if ($decoded) {
            $oprInfo = array_merge($oprInfo, $decoded);
        }
    }
} catch (Exception $e) {
    // Use default
}

// Get maintenance logs
$maintenanceLogs = [];

try {
    $stmt = $pdo->query("SELECT * FROM maintenance_logs ORDER BY created_at DESC LIMIT 20");
    $maintenanceLogs = $stmt->fetchAll() ?: [];
} catch (Exception $e) {
    // Empty array
}

// Build favicon link
$faviconLink = !empty($portalFavicon) ? $portalFavicon : '../favicon.ico';

$profileEmoji = $admin['profile_emoji'] ?? '👨‍💻';
$profileName = $_SESSION['profile_name'] ?? $_SESSION['username'] ?? 'Admin';
?>
<!DOCTYPE html>
<html lang="ms">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Admin - <?php echo htmlspecialchars($portalName); ?></title>

    <!-- ============================================
         CDN LINKS - BOOTSTRAP, SWEETALERT2, ANIMATE.CSS
         ============================================ -->
    <!-- Bootstrap 5 CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">

    <!-- Animate.css for animations -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">

    <!-- SweetAlert2 Theme & Script -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bootstrap-4/bootstrap-4.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <!-- Favicon -->
    <link rel="icon" type="image/x-icon" href="<?php echo htmlspecialchars($faviconLink); ?>">

    <!-- Custom Styles -->
    <link rel="stylesheet" href="../css/style.css">
    <style>
        :root {
            --primary-color:
                <?php echo $themeColor; ?>
            ;
            --font-family:
                <?php echo $fontType; ?>
                , sans-serif;
            --font-size:
                <?php echo $fontSize; ?>
            ;
            --gradient-primary: linear-gradient(90deg, var(--primary-color) 0%, #764ba2 100%);
        }

        /* ============================================
           ANIMATIONS & MICRO-INTERACTIONS
           ============================================ */

        /* Page Load Animation */
        .dashboard-layout {
            animation: fadeInUp 0.6s ease-out;
        }

        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* Sidebar Animation */
        .sidebar {
            animation: slideInLeft 0.5s ease-out;
        }

        @keyframes slideInLeft {
            from {
                opacity: 0;
                transform: translateX(-30px);
            }

            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        /* Main Content Animation */
        .main-content {
            animation: slideInRight 0.5s ease-out 0.1s both;
        }

        @keyframes slideInRight {
            from {
                opacity: 0;
                transform: translateX(30px);
            }

            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        /* Stats Cards Stagger Animation */
        .stats-grid {
            animation: fadeInUp 0.6s ease-out 0.3s both;
        }

        .stats-grid .stat-card {
            animation: scaleIn 0.5s ease-out both;
        }

        .stats-grid .stat-card:nth-child(1) {
            animation-delay: 0.4s;
        }

        .stats-grid .stat-card:nth-child(2) {
            animation-delay: 0.5s;
        }

        @keyframes scaleIn {
            from {
                opacity: 0;
                transform: scale(0.8);
            }

            to {
                opacity: 1;
                transform: scale(1);
            }
        }

        /* Card Hover Effects */
        .card {
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            transform: translateY(0);
        }

        .card:hover {
            transform: translateY(-4px);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
        }

        /* Button Animations */
        .btn {
            transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            overflow: hidden;
        }

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

        .btn:active {
            transform: translateY(0);
            transition-duration: 0.1s;
        }

        /* Button Ripple Effect */
        .btn::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            background: rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            transform: translate(-50%, -50%);
            transition: width 0.4s ease, height 0.4s ease, opacity 0.4s ease;
            opacity: 0;
        }

        .btn:active::after {
            width: 300px;
            height: 300px;
            opacity: 1;
            transition: width 0s, height 0s, opacity 0s;
        }

        /* Tab Animation */
        .tab-content {
            display: none;
            opacity: 0;
            transform: translateY(20px);
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .tab-content.active {
            display: block;
            opacity: 1;
            transform: translateY(0);
        }

        /* Navigation Item Hover */
        .nav-item {
            transition: all 0.2s ease;
            position: relative;
            overflow: hidden;
        }

        .nav-item::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: left 0.5s ease;
        }

        .nav-item:hover::before {
            left: 100%;
        }

        .nav-item.active {
            animation: pulse 2s infinite;
        }

        @keyframes pulse {

            0%,
            100% {
                transform: scale(1);
            }

            50% {
                transform: scale(1.02);
            }
        }

        /* Table Row Animation */
        .table tbody tr {
            animation: fadeInUp 0.4s ease-out both;
        }

        .table tbody tr:nth-child(1) {
            animation-delay: 0.1s;
        }

        .table tbody tr:nth-child(2) {
            animation-delay: 0.15s;
        }

        .table tbody tr:nth-child(3) {
            animation-delay: 0.2s;
        }

        .table tbody tr:nth-child(4) {
            animation-delay: 0.25s;
        }

        .table tbody tr:nth-child(5) {
            animation-delay: 0.3s;
        }

        .table tbody tr:nth-child(6) {
            animation-delay: 0.35s;
        }

        .table tbody tr:nth-child(7) {
            animation-delay: 0.4s;
        }

        .table tbody tr:nth-child(8) {
            animation-delay: 0.45s;
        }

        .table tbody tr:nth-child(9) {
            animation-delay: 0.5s;
        }

        .table tbody tr:nth-child(10) {
            animation-delay: 0.55s;
        }

        /* Loading Animation */
        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(102, 126, 234, 0.3);
            border-radius: 50%;
            border-top-color: var(--primary-color);
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        /* Badge Animation */
        .badge {
            animation: bounceIn 0.5s ease-out;
        }

        @keyframes bounceIn {
            0% {
                opacity: 0;
                transform: scale(0.3);
            }

            50% {
                opacity: 1;
                transform: scale(1.05);
            }

            70% {
                transform: scale(0.9);
            }

            100% {
                opacity: 1;
                transform: scale(1);
            }
        }

        /* Notification Bell Animation */
        .notification-bell-btn {
            transition: all 0.3s ease;
            position: relative;
        }

        .notification-bell-btn:hover {
            transform: scale(1.1);
        }

        .notification-bell-pulse {
            position: absolute;
            top: -2px;
            right: -2px;
            width: 12px;
            height: 12px;
            background: #ff4757;
            border-radius: 50%;
            animation: pulse-red 2s infinite;
        }

        @keyframes pulse-red {

            0%,
            100% {
                transform: scale(1);
                opacity: 1;
            }

            50% {
                transform: scale(1.2);
                opacity: 0.7;
            }
        }

        /* Form Input Focus Animation */

        /* Form Input Focus Animation */
        .form-control {
            transition: all 0.3s ease;
            position: relative;
        }

        .form-control:focus {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15);
        }

        /* Emoji Picker Animation */
        .emoji-picker {
            animation: slideInUp 0.3s ease-out;
        }

        @keyframes slideInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .emoji-option {
            transition: all 0.2s ease;
        }

        .emoji-option:hover {
            transform: scale(1.2) rotate(5deg);
        }

        .emoji-option.selected {
            animation: selectedEmoji 0.5s ease-out;
        }

        @keyframes selectedEmoji {
            0% {
                transform: scale(1);
            }

            50% {
                transform: scale(1.3) rotate(10deg);
            }

            100% {
                transform: scale(1.1) rotate(0deg);
            }
        }

        /* Progress Bar Animation */
        .progress-bar {
            animation: progressFill 1s ease-out;
        }

        @keyframes progressFill {
            from {
                width: 0%;
            }

            to {
                width: var(--progress-width);
            }
        }

        /* Floating Action Button */
        .fab {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 60px;
            height: 60px;
            background: var(--primary-color);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
            transition: all 0.3s ease;
            z-index: 1000;
        }

        .fab:hover {
            transform: scale(1.1);
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.4);
        }

        /* Mobile Menu Animation */
        .mobile-menu-toggle {
            transition: all 0.3s ease;
        }

        .mobile-menu-toggle.active span:nth-child(1) {
            transform: rotate(45deg) translate(5px, 5px);
        }

        .mobile-menu-toggle.active span:nth-child(2) {
            opacity: 0;
        }

        .mobile-menu-toggle.active span:nth-child(3) {
            transform: rotate(-45deg) translate(7px, -6px);
        }

        .sidebar-overlay {
            animation: fadeIn 0.3s ease-out;
        }

        .sidebar.open {
            animation: slideInLeft 0.3s ease-out;
        }

        /* Quick Actions Grid Animation */
        .quick-actions-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            animation: fadeInUp 0.6s ease-out 0.8s both;
        }

        .quick-actions-grid button {
            animation: scaleIn 0.4s ease-out both;
        }

        .quick-actions-grid button:nth-child(1) {
            animation-delay: 0.9s;
        }

        .quick-actions-grid button:nth-child(2) {
            animation-delay: 1.0s;
        }

        .quick-actions-grid button:nth-child(3) {
            animation-delay: 1.1s;
        }

        .quick-actions-grid button:nth-child(4) {
            animation-delay: 1.2s;
        }

        /* Notification Bell Styles */
        .notification-bell-btn {
            background: rgba(255, 255, 255, 0.15);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 12px;
            width: 45px;
            height: 45px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            color: white;
            font-size: 1.2rem;
        }

        .notification-bell-btn:hover {
            background: rgba(255, 255, 255, 0.25);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        .notification-bell-btn:active {
            transform: translateY(0);
        }

        .notification-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background: #ff4757;
            color: white;
            font-size: 0.7rem;
            font-weight: 700;
            padding: 2px 6px;
            border-radius: 10px;
            border: 2px solid #fff;
            min-width: 18px;
            height: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            animation: badgeIn 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
        }

        @keyframes badgeIn {
            from {
                transform: scale(0);
            }

            to {
                transform: scale(1);
            }
        }

        .notification-dropdown {
            transform-origin: top right;
            animation: dropdownIn 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
        }

        @keyframes dropdownIn {
            from {
                opacity: 0;
                transform: scale(0.95) translateY(-10px);
            }

            to {
                opacity: 1;
                transform: scale(1) translateY(0);
            }
        }

        .quick-actions-grid button:nth-child(5) {
            animation-delay: 1.3s;
        }

        /* Dashboard Info Cards Animation */
        .dashboard-info-cards .card {
            animation: slideInUp 0.5s ease-out both;
        }

        .dashboard-info-cards .card:nth-child(1) {
            animation-delay: 1.0s;
        }

        .dashboard-info-cards .card:nth-child(2) {
            animation-delay: 1.1s;
        }

        .dashboard-info-cards .card:nth-child(3) {
            animation-delay: 1.2s;
        }

        /* Real-time Clock Animation */
        .realtime-clock {
            animation: glow 2s ease-in-out infinite alternate;
        }

        @keyframes glow {
            from {
                text-shadow: 0 0 5px rgba(102, 126, 234, 0.5);
            }

            to {
                text-shadow: 0 0 20px rgba(102, 126, 234, 0.8), 0 0 30px rgba(102, 126, 234, 0.6);
            }
        }

        /* Status Toggle Animation */
        .toggle-switch {
            transition: all 0.3s ease;
        }

        .toggle-switch.active {
            background: #28a745;
        }

        .toggle-slider {
            transition: all 0.3s ease;
        }

        .toggle-knob {
            transition: all 0.3s ease;
        }

        /* Alert Animation */
        .alert {
            animation: slideInDown 0.4s ease-out;
        }

        @keyframes slideInDown {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* Search Input Animation */
        .form-control:focus {
            animation: inputFocus 0.3s ease-out;
        }

        @keyframes inputFocus {
            0% {
                transform: scale(1);
            }

            50% {
                transform: scale(1.02);
            }

            100% {
                transform: scale(1);
            }
        }

        /* Reduced Motion Support */
        @media (prefers-reduced-motion: reduce) {

            *,
            *::before,
            *::after {
                animation-duration: 0.01ms !important;
                animation-iteration-count: 1 !important;
                transition-duration: 0.01ms !important;
            }
        }

        .favicon-preview {
            width: 32px;
            height: 32px;
            object-fit: contain;
            border-radius: 4px;
            border: 1px solid #ddd;
        }

        .realtime-clock {
            font-size: 1.5rem;
            font-weight: bold;
            color: var(--primary-color);
        }

        .realtime-date {
            color: var(--text-secondary);
            font-size: 0.9rem;
        }

        .page-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 20px;
        }

        /* --- ANIMATION & TAB STYLES --- */
        .tab-content {
            display: none;
            /* Hidden by default */
            opacity: 0;
            transition: opacity 0.3s ease, transform 0.3s ease;
            transform: translateY(10px);
        }

        /* --- PENGURUSAN WARNA BUTANG BAHAYA (TONG SAMPAH) --- */


        .tab-content.active {
            display: block;
            /* Visible when active */
            opacity: 1;
            transform: translateY(0);
        }

        .nav-item {
            cursor: pointer;
            transition: all 0.2s ease;
            user-select: none;
        }

        .nav-item:active {
            transform: scale(0.95);
        }

        /* Custom Subject Styles */
        .custom-subject-wrapper {
            display: none;
            margin-top: 10px;
            padding: 10px;
            background: #f8f9fa;
            border-left: 3px solid var(--primary-color);
            border-radius: 4px;
        }

        /* Tambah class yang lebih spesifik untuk paksa perubahan */
        .btn-danger.btn-icon,
        .table .btn-danger {
            background-color: #fec5d4 !important;
            border-color: #c9302c !important;
            color: white !important;
        }

        .custom-subject-wrapper.show {
            display: block;
            animation: fadeIn 0.3s;
        }

        .form-check {
            margin-bottom: 5px;
            cursor: pointer;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            }

            to {
                opacity: 1;
            }
        }

        /* ============================================
           MOBILE RESPONSIVE DESIGN (480px)
           Clean, Responsive, Animated, User-Friendly
           ============================================ */

        /* Mobile Navigation Toggle */
        .mobile-menu-toggle {
            display: none;
            position: fixed;
            top: 15px;
            left: 15px;
            z-index: 1001;
            background: var(--primary-color);
            border: none;
            border-radius: 10px;
            padding: 12px 14px;
            cursor: pointer;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
        }

        .mobile-menu-toggle span {
            display: block;
            width: 22px;
            height: 3px;
            background: white;
            margin: 4px 0;
            border-radius: 3px;
            transition: all 0.3s ease;
        }

        .sidebar-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 999;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .sidebar-overlay.show {
            display: block;
            opacity: 1;
        }

        /* Mobile UI - Hidden by default on Desktop */
        .mobile-header,
        .sidebar-overlay,
        .mobile-bottom-nav {
            display: none !important;
        }

        /* === TABLET BREAKPOINT (1024px) === */
        /* === PREMIUM MOBILE STYLE (1024px) === */
        @media (max-width: 1024px) {
            .mobile-header {
                display: flex !important;
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                height: calc(75px + env(safe-area-inset-top, 0));
                background: rgba(255, 255, 255, 0.85);
                backdrop-filter: blur(20px);
                -webkit-backdrop-filter: blur(20px);
                border-bottom: 1px solid rgba(0, 0, 0, 0.05);
                z-index: 1001;
                align-items: center;
                justify-content: space-between;
                padding: env(safe-area-inset-top, 0) 15px 0 15px;
                box-shadow: 0 2px 10px rgba(0, 0, 0, 0.02);
            }

            .mobile-toggle-btn {
                background: #f1f5f9;
                border: none;
                width: 42px;
                height: 42px;
                border-radius: 12px;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 1.3rem;
                cursor: pointer;
                color: var(--primary-color);
                -webkit-appearance: none;
            }

            .mobile-portal-name {
                font-weight: 800;
                font-size: 1.1rem;
                color: #1e293b;
                letter-spacing: -0.5px;
            }

            .mobile-user-chip {
                display: flex;
                align-items: center;
                gap: 8px;
                background: white;
                padding: 4px 12px 4px 6px;
                border-radius: 20px;
                border: 1px solid rgba(0, 0, 0, 0.05);
                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
            }

            .user-emoji {
                font-size: 1.1rem;
                background: #f8fafc;
                width: 28px;
                height: 28px;
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 50%;
            }

            .user-first-name {
                font-weight: 700;
                font-size: 0.75rem;
                color: #1e293b;
            }

            .sidebar {
                position: fixed;
                left: -280px;
                top: 0;
                bottom: 0;
                width: 280px;
                z-index: 3000;
                transition: left 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            }

            .sidebar.open {
                left: 0;
            }

            .sidebar-overlay {
                display: none;
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(15, 23, 42, 0.5);
                backdrop-filter: blur(4px);
                z-index: 1999;
            }

            .sidebar-overlay.show {
                display: block;
                animation: fadeIn 0.3s ease-out;
            }

            .main-content {
                margin-left: 0 !important;
                padding: calc(30px + env(safe-area-inset-top, 0)) 15px 120px 15px !important;
            }

            .mobile-bottom-nav {
                display: flex !important;
                position: fixed;
                bottom: 20px;
                left: 20px;
                right: 20px;
                height: 70px;
                background: rgba(255, 255, 255, 0.9);
                backdrop-filter: blur(20px);
                -webkit-backdrop-filter: blur(20px);
                border: 1px solid rgba(255, 255, 255, 0.3);
                border-radius: 25px;
                z-index: 1000;
                justify-content: space-around;
                align-items: center;
                padding-bottom: 0;
                box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
                transition: all 0.3s ease;
            }

            .nav-tab-item {
                display: flex;
                flex-direction: column;
                align-items: center;
                gap: 4px;
                color: #94a3b8;
                font-size: 0.7rem;
                font-weight: 600;
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                flex: 1;
                text-decoration: none !important;
            }

            .nav-tab-item.active {
                color: var(--primary-color);
            }

            .nav-tab-item .nav-icon {
                font-size: 1.4rem;
                transition: transform 0.3s ease;
            }

            .nav-tab-item.active .nav-icon {
                transform: scale(1.15) translateY(-2px);
            }

            .page-header {
                flex-direction: column !important;
                align-items: flex-start !important;
                gap: 15px !important;
            }
        }

        /* === MOBILE BREAKPOINT (480px) === */
        @media (max-width: 480px) {

            /* Dashboard Layout */
            .main-content {
                padding: 65px 10px 15px 10px !important;
            }

            /* Page Header - Mobile Optimized */
            .page-header {
                padding: 10px 0;
            }

            .page-title {
                font-size: 1.2rem !important;
                line-height: 1.3;
            }

            .page-subtitle {
                font-size: 0.85rem;
            }

            /* Real-time Clock - Compact */
            .realtime-clock {
                font-size: 1.1rem !important;
            }

            .realtime-date {
                font-size: 0.75rem !important;
            }

            /* Profile Section - Compact */
            .page-header>div:last-child>div:last-child {
                padding-left: 10px !important;
                gap: 10px !important;
            }

            .page-header>div:last-child>div:last-child>div:first-child {
                font-size: 2rem !important;
            }

            /* Welcome Banner - Mobile */
            .welcome-banner {
                padding: 20px !important;
                border-radius: 15px !important;
                margin-bottom: 20px !important;
            }

            .welcome-banner h1 {
                font-size: 1.3rem !important;
                margin-bottom: 8px !important;
            }

            .welcome-banner p {
                font-size: 0.9rem !important;
            }

            /* Stats Cards - Full Width */
            .stats-grid {
                grid-template-columns: 1fr !important;
                gap: 12px;
            }

            .stat-card {
                padding: 18px;
                border-radius: 15px;
                flex-direction: row;
                align-items: center;
                gap: 15px;
            }

            .stat-icon {
                font-size: 2rem;
                margin-bottom: 0;
            }

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

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

            /* Quick Actions - Mobile Grid */
            .card-body>div[style*="grid-template-columns"] {
                grid-template-columns: 1fr 1fr !important;
                gap: 10px !important;
            }

            .card-body>div[style*="grid-template-columns"]>button {
                padding: 15px 10px !important;
                font-size: 0.85rem;
            }

            .card-body>div[style*="grid-template-columns"]>button span:first-child {
                font-size: 1.8rem !important;
            }

            /* Card Styles */
            .card {
                border-radius: 15px !important;
                margin-bottom: 15px;
            }

            .card-header {
                padding: 15px !important;
                flex-direction: column !important;
                align-items: flex-start !important;
                gap: 10px !important;
            }

            .card-header .btn {
                width: 100%;
            }

            .card-title {
                font-size: 1.1rem !important;
            }

            .card-body {
                padding: 15px !important;
            }

            /* Tables - Mobile Friendly */
            .table-responsive,
            .table-container {
                margin: 0 -15px;
                padding: 0 15px;
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
            }

            .table {
                min-width: 600px;
                font-size: 0.85rem;
            }

            .table th,
            .table td {
                padding: 10px 8px;
                white-space: nowrap;
            }

            /* Forms - Mobile Optimized */
            .form-group {
                margin-bottom: 15px;
            }

            .form-label {
                font-size: 0.9rem;
                margin-bottom: 5px;
            }

            .form-control {
                padding: 12px;
                font-size: 1rem;
                border-radius: 10px;
            }

            .form-select {
                padding: 12px;
                font-size: 1rem;
            }

            /* Buttons - Touch Friendly */
            .btn {
                padding: 12px 16px;
                font-size: 0.9rem;
                border-radius: 10px;
                min-height: 44px;
            }

            .btn-sm {
                padding: 8px 12px;
                font-size: 0.8rem;
                min-height: 36px;
            }

            .modal {
                max-width: 95vw !important;
                margin: auto;
            }

            .modal-header {
                padding: 15px !important;
            }

            .modal-title {
                font-size: 1.1rem !important;
            }

            .modal-body {
                padding: 15px !important;
                max-height: 70vh;
                overflow-y: auto;
            }

            .modal-close {
                font-size: 1.5rem;
                padding: 5px 10px;
            }

            /* Checkbox Grid - Mobile */
            .form-group div[style*="grid-template-columns: 1fr 1fr"] {
                grid-template-columns: 1fr !important;
            }

            /* Notification Dropdown - Full Width */
            .notification-dropdown {
                position: fixed !important;
                left: 5px !important;
                right: 5px !important;
                top: 70px !important;
                width: auto !important;
                max-height: 70vh !important;
                border-radius: 15px !important;
            }

            .notification-dropdown-header {
                padding: 12px 15px !important;
            }

            .notification-dropdown-header h4 {
                font-size: 1rem !important;
            }

            /* Notification Bell */
            .notification-bell-btn {
                width: 40px !important;
                height: 40px !important;
                font-size: 1rem !important;
            }

            /* Badge Styling */
            .badge {
                padding: 4px 8px;
                font-size: 0.7rem;
            }

            /* Sidebar Mobile */
            .sidebar {
                width: 85vw !important;
                max-width: 300px;
            }

            .sidebar-header {
                padding: 15px 10px !important;
            }

            .sidebar-logo img {
                width: 60px !important;
                height: 60px !important;
            }

            .sidebar-title {
                font-size: 1.1rem !important;
            }

            .nav-item {
                padding: 12px 15px !important;
                font-size: 0.95rem !important;
            }

            /* Info Cards Grid */
            .card-body>div[style*="grid-template-columns: repeat(auto-fit"] {
                grid-template-columns: 1fr 1fr !important;
                gap: 10px !important;
            }

            .card-body>div[style*="grid-template-columns: repeat(auto-fit"]>div {
                padding: 12px !important;
                border-radius: 10px !important;
            }

            .card-body>div[style*="grid-template-columns: repeat(auto-fit"]>div>div:first-child {
                font-size: 1.5rem !important;
                margin-bottom: 5px !important;
            }

            .card-body>div[style*="grid-template-columns: repeat(auto-fit"]>div p {
                font-size: 0.7rem !important;
            }

            .card-body>div[style*="grid-template-columns: repeat(auto-fit"]>div strong {
                font-size: 0.85rem !important;
            }

            /* Emoji Picker */
            .emoji-picker {
                gap: 8px;
            }

            .emoji-option {
                font-size: 1.5rem;
                padding: 8px;
            }

            /* Toggle Switch */
            .toggle-switch {
                width: 50px !important;
                height: 26px !important;
            }

            /* Maintenance Toggle Box */
            .form-group>div[style*="display: flex; align-items: center"] {
                flex-direction: column !important;
                align-items: flex-start !important;
                gap: 15px !important;
            }

            /* Floating Bubbles - Smaller on Mobile */
            .bubble {
                display: none;
            }

            /* Search Input */
            input[type="search"],
            input[id*="Search"] {
                width: 100% !important;
                margin-bottom: 10px;
            }

            /* Page Header - Compact */
            .page-header {
                padding: 15px;
                gap: 10px;
            }

            .page-title {
                font-size: 1.1rem !important;
                /* Smaller size */
            }

            .page-subtitle {
                font-size: 0.8rem !important;
            }

            /* Add smooth scroll for iOS */
            * {
                -webkit-tap-highlight-color: transparent;
            }

            /* Ensure touch targets are large enough */
            a,
            button,
            input,
            select,
            textarea {
                min-height: 44px;
            }
        }

        /* === EXTRA SMALL DEVICES (360px) === */
        @media (max-width: 360px) {
            .main-content {
                padding: 60px 8px 15px 8px !important;
            }

            .welcome-banner h1 {
                font-size: 1.1rem !important;
            }

            .stat-value {
                font-size: 1.5rem;
            }

            .card-body>div[style*="grid-template-columns"]>button {
                padding: 12px 8px !important;
            }

            .card-body>div[style*="grid-template-columns: repeat(auto-fit"] {
                grid-template-columns: 1fr !important;
            }
        }

        /* === ANIMATION CLASSES FOR MOBILE === */
        .animate__animated {
            --animate-duration: 0.5s;
        }

        @media (prefers-reduced-motion: reduce) {
            .animate__animated {
                animation: none !important;
                transition: none !important;
            }
        }

        /* Mobile touch feedback */
        @media (hover: none) and (pointer: coarse) {

            .btn:active,
            .nav-item:active,
            .card:active {
                transform: scale(0.98);
                opacity: 0.9;
            }
        }
    </style>
</head>


<div class="dashboard-layout">
    <aside class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <div class="sidebar-logo">
                <?php if (!empty($portalLogo)): ?>
                    <img src="<?php echo htmlspecialchars($portalLogo); ?>" alt="Logo"
                        style="width: 80px; height: 80px; object-fit: contain;">
                <?php else: ?>
                    <span style="font-size: 1.5rem;">📚</span>
                <?php endif; ?>
            </div>
            <h2 class="sidebar-title"><?php echo htmlspecialchars($portalName); ?></h2>
            <p class="sidebar-subtitle">Panel Admin</p>
        </div>

        <nav class="sidebar-nav">
            <a href="#" onclick="switchTab(event, 'dashboard')" class="nav-item active" id="nav-dashboard">
                <span class="nav-icon">📊</span> Dashboard
            </a>
            <a href="#" onclick="switchTab(event, 'notifications'); loadNotifications();" class="nav-item"
                id="nav-notifications">
                <span class="nav-icon">🔔</span> Notifikasi <span id="sidebarNotificationBadge"
                    class="notification-badge"
                    style="display: none; position: static; transform: none; margin-left: auto; background: #ff4757; color: white; padding: 2px 6px; border-radius: 10px; font-size: 11px;">0</span>
            </a>
            <a href="#" onclick="switchTab(event, 'teachers')" class="nav-item" id="nav-teachers">
                <span class="nav-icon">👨‍🏫</span> Pengurusan Guru
            </a>
            
            <a href="#" onclick="switchTab(event, 'announcements')" class="nav-item" id="nav-announcements">
                <span class="nav-icon">📢</span> Pengumuman
            </a>
            <a href="#" onclick="switchTab(event, 'opr')" class="nav-item" id="nav-opr">
                <span class="nav-icon">📄</span> OPR
            </a>
            <a href="#" onclick="switchTab(event, 'maintenance')" class="nav-item" id="nav-maintenance">
                <span class="nav-icon">🔧</span> Penyelenggaraan
            </a>
            <a href="#" onclick="switchTab(event, 'footer')" class="nav-item" id="nav-footer">
                <span class="nav-icon">📝</span> Footer
            </a>
            <a href="#" onclick="switchTab(event, 'settings')" class="nav-item" id="nav-settings">
                <span class="nav-icon">⚙️</span> Tetapan
            </a>
            <!-- Logout button placed after Tetapan tab -->
            <div style="padding: 20px 10px;">
                <button class="btn btn-secondary" style="width: 100%;" onclick="logout()">
                    <span>🚪</span> Log Keluar
                </button>
            </div>
        </nav>
    </aside>

    <main class="main-content">
        <!-- Mobile Menu Toggle -->
        <button class="mobile-menu-toggle" id="mobileMenuToggle" onclick="toggleMobileMenu()">
            <span></span>
            <span></span>
            <span></span>
        </button>

        <!-- Sidebar Overlay for Mobile -->
        <div class="sidebar-overlay" id="sidebarOverlay" onclick="toggleMobileMenu()"></div>

        <div class="page-header">
            <div style="flex: 1;">
                <h1 class="page-title">Selamat sejahtera Admin <?php echo htmlspecialchars($profileName); ?>!</h1>
                <p class="page-subtitle">Panel pentadbiran <?php echo htmlspecialchars($portalName); ?></p>
            </div>

            <div style="display: flex; align-items: center; gap: 20px;">
                <div style="text-align: right;">
                    <div id="realtimeClock" class="realtime-clock">00:00:00</div>
                    <div id="realtimeDate" class="realtime-date">Mengira...</div>
                </div>



                <div
                    style="display: flex; align-items: center; gap: 15px; border-left: 2px solid #ddd; padding-left: 20px;">
                    <div style="font-size: 2.5rem;"><?php echo htmlspecialchars($profileEmoji); ?></div>
                    <div>
                        <strong><?php echo htmlspecialchars($profileName); ?></strong>
                        <p style="margin: 0; color: #666; font-size: 0.9rem;">Admin</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Announcements Tab -->

        <!-- Notifications Tab -->
        <div id="notifications" class="tab-content">
            <div class="welcome-banner premium-gradient animate__animated animate__fadeIn"
                style="position: relative; overflow: hidden; padding: 30px; border-radius: 16px; margin-bottom: 30px; color: white;">
                <div class="reveal-up" style="position: relative; z-index: 2;">
                    <h1 style="color: white; margin-bottom: 5px;">Pusat Notifikasi 🔔</h1>
                    <p style="font-size: 1rem; opacity: 0.9;">Semua pemberitahuan sistem dan aktiviti penting anda
                        di sini.</p>
                </div>
            </div>

            <div class="section-container"
                style="background: white; border-radius: 16px; padding: 25px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); border: 1px solid #eee;">
                <div
                    style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; border-bottom: 2px solid #f0f0f0; padding-bottom: 15px;">
                    <h3 style="margin: 0; color: var(--primary-color);">Garis Masa Notifikasi</h3>
                    <div style="display: flex; gap: 10px;">
                        <button class="btn btn-outline-primary"
                            style="padding: 8px 16px; border-radius: 10px; font-weight: 600;"
                            onclick="markAllNotificationsRead()">Tandakan Semua Dibaca</button>
                        <button class="btn btn-outline-danger"
                            style="padding: 8px 16px; border-radius: 10px; font-weight: 600;"
                            onclick="deleteAllNotifications()">Padam Semua Notifikasi</button>
                    </div>
                </div>

                <div id="notificationTabList" class="notification-timeline" style="min-height: 300px;">
                    <!-- Content will be injected by JS -->
                </div>
            </div>
        </div>

        <div id="dashboard" class="tab-content active">
            <!-- Animated Welcome Banner -->
            <div class="welcome-banner premium-gradient animate__animated animate__fadeIn"
                style="position: relative; overflow: hidden; padding: 40px; border-radius: var(--radius-xl); margin-bottom: 30px; color: white;">
                <div class="floating-bubbles">
                    <div class="bubble"
                        style="width: 40px; height: 40px; left: 10%; bottom: -10%; animation-delay: 0s;"></div>
                    <div class="bubble"
                        style="width: 20px; height: 20px; left: 30%; bottom: -10%; animation-delay: 2s;"></div>
                    <div class="bubble"
                        style="width: 60px; height: 60px; left: 50%; bottom: -10%; animation-delay: 4s;"></div>
                    <div class="bubble"
                        style="width: 30px; height: 30px; left: 70%; bottom: -10%; animation-delay: 1s;"></div>
                    <div class="bubble"
                        style="width: 50px; height: 50px; left: 90%; bottom: -10%; animation-delay: 3s;"></div>
                </div>
                <div class="reveal-up" style="position: relative; z-index: 2;">
                    <h1 style="color: white; margin-bottom: 10px;">Selamat Sejahtera,
                        <?php echo htmlspecialchars($profileName); ?>! 🌟
                    </h1>
                    <p style="font-size: 1.2rem; opacity: 0.9;">Selamat datang kembali ke Panel Kawalan TutorKita.
                        Jom uruskan sistem hari ini!</p>
                    <div style="margin-top: 20px; font-weight: 500;">
                        <span id="bannerDay">...</span>, <span id="bannerDate">...</span> | <span
                            id="bannerTime">00:00:00</span>
                    </div>
                </div>
            </div>

            <div class="stats-grid">
                <div class="stat-card lift-on-hover glow-on-hover animate__animated animate__zoomIn">
                    <div class="stat-icon">👨‍🏫</div>
                    <div class="stat-content">
                        <div class="stat-value" id="countTeachers">0</div>
                        <div class="stat-label">Jumlah Guru Aktif</div>
                    </div>
                </div>
                <div class="stat-card success lift-on-hover glow-on-hover animate__animated animate__zoomIn"
                    style="animation-delay: 0.1s;">
                    <div class="stat-icon">👨‍🎓</div>
                    <div class="stat-content">
                        <div class="stat-value" id="countStudents">0</div>
                        <div class="stat-label">Jumlah Pelajar Aktif</div>
                    </div>
                </div>
            </div>

            <div class="card animate__animated animate__fadeInUp"
                style="margin-top: 25px; border-radius: var(--radius-xl);">
                <div class="card-header">
                    <h3 class="card-title">🚀 Tindakan Pantas</h3>
                </div>
                <div class="card-body">
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px;">
                        <button class="btn btn-primary lift-on-hover" onclick="openModal('addTeacherModal')"
                            style="padding: 25px; flex-direction: column; gap: 10px;">
                            <span style="font-size: 2.5rem;">👤</span>
                            <span>Tambah Guru Baru</span>
                        </button>
                        <button class="btn lift-on-hover premium-gradient-info" onclick="switchTab(event, 'settings')"
                            style="padding: 25px; flex-direction: column; gap: 10px; color: white; border: none;">
                            <span style="font-size: 2.5rem;">⚙️</span>
                            <span>Tetapan Portal</span>
                        </button>
                        <button class="btn lift-on-hover premium-gradient-warning" onclick="switchTab(event, 'opr')"
                            style="padding: 25px; flex-direction: column; gap: 10px; color: white; border: none;">
                            <span style="font-size: 2.5rem;">📄</span>
                            <span>Tetapan OPR</span>
                        </button>
                        <button class="btn lift-on-hover premium-gradient-danger"
                            onclick="switchTab(event, 'announcements')"
                            style="padding: 25px; flex-direction: column; gap: 10px; color: white; border: none;">
                            <span style="font-size: 2.5rem;">📢</span>
                            <span>Pengumuman</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <?php require_once '../components/admin/tab-teacher-management.php'; ?>

        <div id="settings" class="tab-content">
            <!-- Account Info Section (Teacher Style) -->
            <div class="card"
                style="margin-bottom: 25px; border-radius: 20px; overflow: hidden; box-shadow: 0 10px 40px rgba(0,0,0,0.08); border: none;">
                <div style="height: 6px; background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);"></div>
                <div class="card-body" style="padding: 25px;">
                    <h4
                        style="margin: 0 0 20px 0; color: #1a1a2e; font-size: 1.1rem; display: flex; align-items: center; gap: 10px;">
                        <span
                            style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 10px; border-radius: 12px; font-size: 1.2rem;">ℹ️</span>
                        Maklumat Pentadbir
                    </h4>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px;">
                        <div
                            style="background: #f8f9ff; padding: 20px; border-radius: 15px; text-align: center; border: 1px solid #eef0f7;">
                            <div style="font-size: 2rem; margin-bottom: 10px;">👤</div>
                            <p style="margin: 0; color: #666; font-size: 0.85rem;">Nama Pengguna</p>
                            <strong
                                style="font-size: 1.1rem; color: #1a1a2e;"><?php echo htmlspecialchars($admin['username'] ?? 'admin'); ?></strong>
                        </div>

                        <div
                            style="background: #f8f9ff; padding: 20px; border-radius: 15px; text-align: center; border: 1px solid #eef0f7;">
                            <div style="font-size: 2rem; margin-bottom: 10px;">📅</div>
                            <p style="margin: 0; color: #666; font-size: 0.85rem;">Tarikh Daftar</p>
                            <strong
                                style="font-size: 1.1rem; color: #1a1a2e;"><?php echo isset($admin['created_at']) ? date('d/m/Y', strtotime($admin['created_at'])) : date('d/m/Y'); ?></strong>
                        </div>

                        <div
                            style="background: #f8f9ff; padding: 20px; border-radius: 15px; text-align: center; border: 1px solid #eef0f7;">
                            <div style="font-size: 2rem; margin-bottom: 10px;">🛡️</div>
                            <p style="margin: 0; color: #666; font-size: 0.85rem;">Status Akaun</p>
                            <span class="badge badge-success"
                                style="font-size: 0.9rem; padding: 5px 15px; border-radius: 20px; background: #28a745; color: white;">Aktif</span>
                        </div>

                        <div
                            style="background: #f8f9ff; padding: 20px; border-radius: 15px; text-align: center; border: 1px solid #eef0f7;">
                            <div style="font-size: 2rem; margin-bottom: 10px;">🔑</div>
                            <p style="margin: 0; color: #666; font-size: 0.85rem;">Log Masuk Terakhir</p>
                            <strong style="font-size: 1.1rem; color: #1a1a2e;"><?php echo date('d/m/Y H:i'); ?></strong>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card" style="border-radius: var(--radius-xl); overflow: hidden;">
                <div class="card-header">
                    <h3 class="card-title">⚙️ Tetapan Profil & Portal</h3>
                </div>
                <div class="card-body">
                    <form id="settingsForm" onsubmit="updateAdminSettings(event)">
                        <div class="form-group">
                            <label class="form-label">Emoji Profil</label>
                            <div class="emoji-picker" id="adminEmojiPicker">
                                <?php
                                $emojis = ['👨‍💻', '👩‍💻', '👨‍💼', '👩‍💼', '🧑‍💻', '💻', '🚀', '🔥', '🌟', '🛠️'];
                                $currentEmoji = $admin['profile_emoji'] ?? '👨‍💻';
                                foreach ($emojis as $emoji):
                                    ?>
                                    <div class="emoji-option <?php echo $emoji === $currentEmoji ? 'selected' : ''; ?>"
                                        data-emoji="<?php echo $emoji; ?>" onclick="selectAdminEmoji(this)">
                                        <?php echo $emoji; ?>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            <input type="hidden" name="profile_emoji" id="adminSelectedEmoji"
                                value="<?php echo htmlspecialchars($currentEmoji); ?>">
                        </div>

                        <div class="form-group" style="margin-top: 20px;">
                            <label class="form-label">Nama dalam Dashboard</label>
                            <input type="text" class="form-control" name="profile_name"
                                value="<?php echo htmlspecialchars($profileName); ?>" required>
                            <small class="text-muted">Nama ini akan dipaparkan pada ucapan di Dashboard.</small>
                        </div>

                        <div class="form-group">
                            <label class="form-label">Tukar Kata Laluan</label>
                            <input type="password" class="form-control" name="new_password"
                                placeholder="Biarkan kosong jika tidak mahu tukar">
                            <small class="text-muted" style="color: #dc3545 !important;">⚠️ Hanya isi jika anda mahu
                                menukar kata laluan semasa.</small>
                        </div>

                        <div class="form-group">
                            <label class="form-label">Nama Portal</label>
                            <input type="text" class="form-control" name="portal_name"
                                value="<?php echo htmlspecialchars($portalName); ?>">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Tagline Portal</label>
                            <input type="text" class="form-control" name="portal_tagline"
                                value="<?php echo htmlspecialchars($portalTagline); ?>">
                        </div>
                        <div class="form-group">
                            <label class="form-label">URL Logo Portal</label>
                            <input type="url" class="form-control" name="portal_logo" id="portalLogo"
                                value="<?php echo htmlspecialchars($portalLogo); ?>"
                                placeholder="https://contoh.com/logo.png">
                            <?php if (!empty($portalLogo)): ?>
                                <img src="<?php echo htmlspecialchars($portalLogo); ?>" alt="Logo"
                                    style="width: 10px; height: 10px; object-fit: contain; margin-top: 10px; border-radius: 4px;">
                            <?php endif; ?>
                        </div>
                        <div class="form-group">
                            <label class="form-label">URL Favicon Portal</label>
                            <input type="url" class="form-control" name="portal_favicon" id="portalFavicon"
                                value="<?php echo htmlspecialchars($portalFavicon); ?>"
                                placeholder="https://contoh.com/favicon.ico">
                            <p class="form-text">Masukkan URL favicon (format .ico, .png, atau .svg)</p>
                            <?php if (!empty($portalFavicon)): ?>
                                <img src="<?php echo htmlspecialchars($portalFavicon); ?>" alt="Favicon"
                                    class="favicon-preview" style="margin-top: 10px;">
                            <?php else: ?>
                                <img src="../favicon.ico" alt="Default Favicon" class="favicon-preview"
                                    style="margin-top: 10px;">
                            <?php endif; ?>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Warna Tema</label>
                            <input type="color" class="form-control" name="theme_color"
                                value="<?php echo $themeColor; ?>">
                        </div>

                        <div class="form-group">
                            <label class="form-label">URL Latar Belakang Login</label>
                            <input type="url" class="form-control" name="portal_background" id="portalBackground"
                                value="<?php echo htmlspecialchars($admin['portal_background'] ?? ''); ?>"
                                placeholder="https://contoh.com/images/bg-login.jpg">
                            <p class="form-text">Masukkan URL imej untuk latar belakang halaman log masuk. Biarkan
                                kosong untuk guna warna gradient.</p>
                            <?php if (!empty($admin['portal_background'])): ?>
                                <div style="margin-top: 10px;">
                                    <img src="<?php echo htmlspecialchars($admin['portal_background']); ?>"
                                        alt="Background Preview"
                                        style="width: 100%; max-width: 300px; height: 150px; object-fit: cover; border-radius: 8px; border: 2px solid #ddd;"
                                        onerror="this.style.display='none'; this.parentElement.innerHTML='<p style=\'color: #dc3545;\'>⚠️ Ijek gagal dimuatkan. Sila semak URL.</p>';">
                                </div>
                            <?php endif; ?>
                        </div>

                        <button type="submit" class="btn btn-primary" style="width: 100%;">Simpan Tetapan</button>
                    </form>
                </div>
            </div>
        </div>

        <div id="opr" class="tab-content">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">Tetapan One Page Report (OPR)</h3>
                </div>
                <div class="card-body">
                    <form id="oprSettingsForm" onsubmit="saveOprSettings(event)">
                        <div class="form-group">
                            <label class="form-label">Penerangan OPR</label>
                            <textarea class="form-control" name="description" id="oprDescription" rows="6"
                                required><?php echo htmlspecialchars($oprInfo['description']); ?></textarea>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Pautan Dokumentasi</label>
                            <input type="url" class="form-control" name="link" id="oprLink"
                                value="<?php echo htmlspecialchars($oprInfo['link']); ?>" required>
                        </div>
                        <button type="submit" class="btn btn-primary">Simpan Tetapan OPR</button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Announcements Tab - Added Missing Content -->
        <div id="announcements" class="tab-content">
            <div class="card" style="border-radius: var(--radius-xl); overflow: hidden;">
                <div class="card-header"
                    style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px;">
                    <h3 class="card-title">📢 Pengumuman</h3>
                    <button class="btn btn-primary" onclick="showAddAnnouncementModal()">
                        <span>➕</span> Buat Pengumuman
                    </button>
                </div>
                <div class="card-body">
                    <p class="text-muted" style="margin-bottom: 20px;">
                        Urus pengumuman untuk semua guru dan pelajar dalam sistem.
                    </p>
                    <div id="announcementsList" style="display: flex; flex-direction: column; gap: 15px;">
                        <div style="text-align: center; padding: 40px 20px; color: #888;">
                            <div style="font-size: 3rem; margin-bottom: 10px;">📢</div>
                            <p>Memuatkan pengumuman...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div id="maintenance" class="tab-content">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">🔧 Penyelenggaraan Sistem</h3>
                </div>
                <div class="card-body">
                    <!-- Maintenance Mode Setting -->
                    <div class="form-group">
                        <label class="form-label">Mod Penyelenggaraan</label>
                        <div
                            style="display: flex; align-items: center; gap: 15px; padding: 15px; background: #f8f9fa; border-radius: 8px; border: 1px solid #ddd;">
                            <div style="flex: 1;">
                                <strong>🔧 Sistem Sedang Diperbaharui</strong>
                                <p style="margin: 5px 0 0 0; color: #666; font-size: 0.9rem;">
                                    Aktifkan untuk menunjukkan mesej penyelenggaraan dan menyekat log masuk semua
                                    pengguna.
                                </p>
                            </div>
                            <label class="toggle-switch"
                                style="display: inline-block; width: 60px; height: 30px; position: relative; cursor: pointer;">
                                <input type="checkbox" id="maintenanceMode" name="maintenance_mode" value="1" <?php echo (isset($admin['maintenance_mode']) && $admin['maintenance_mode'] == '1') ? 'checked' : ''; ?> onchange="toggleMaintenanceMode(this.checked)">
                                <span class="toggle-slider"
                                    style="position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: <?php echo (isset($admin['maintenance_mode']) && $admin['maintenance_mode'] == '1') ? '#dc3545' : '#6c757d'; ?>; transition: .4s; border-radius: 34px; display: block;">
                                    <span class="toggle-knob"
                                        style="position: absolute; height: 22px; width: 22px; left: <?php echo (isset($admin['maintenance_mode']) && $admin['maintenance_mode'] == '1') ? '32px' : '4px'; ?>; bottom: 4px; background-color: white; transition: .4s; border-radius: 50%;"></span>
                                </span>
                            </label>
                        </div>
                        <div id="maintenanceWarning"
                            style="display: <?php echo (isset($admin['maintenance_mode']) && $admin['maintenance_mode'] == '1') ? 'block' : 'none'; ?>; margin-top: 10px; padding: 10px; background: #fff3cd; border-radius: 8px; border-left: 4px solid #ffc107;">
                            <p style="margin: 0; color: #856404; font-size: 0.9rem;">
                                <strong>⚠️ Mod Penyelenggaraan Aktif:</strong><br>
                                • Semua pengguna tidak boleh log masuk<br>
                                • Halaman log masuk akan menunjukkan mesej penyelenggaraan<br>
                                • Hanya admin boleh log masuk untuk menyahaktifkan
                            </p>
                        </div>
                    </div>

                    <form id="maintenanceForm" onsubmit="addMaintenanceLog(event)"
                        style="background: #f5f5f5; padding: 20px; border-radius: 10px; margin-bottom: 20px;">
                        <h4 style="margin-bottom: 15px;">Tambah Log Baru</h4>
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                            <div class="form-group">
                                <label class="form-label">Aktiviti</label>
                                <input type="text" class="form-control" name="activity" required
                                    placeholder="cth: Kemas kini sistem">
                            </div>
                            <div class="form-group">
                                <label class="form-label">Status</label>
                                <select class="form-control form-select" name="status">
                                    <option value="Aktif">Aktif</option>
                                    <option value="Maintenance">Maintenance</option>
                                    <option value="Selesai">Selesai</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Keterangan</label>
                            <textarea class="form-control" name="details" rows="2"
                                placeholder="Keterangan lanjut..."></textarea>
                        </div>
                        <button type="submit" class="btn btn-primary btn-sm">Tambah Log</button>
                    </form>

                    <div class="table-container">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Tarikh</th>
                                    <th>Aktiviti</th>
                                    <th>Status</th>
                                    <th>Keterangan</th>
                                    <th>Tindakan</th>
                                </tr>
                            </thead>
                            <tbody id="maintenanceLogsTable">
                                <?php if (empty($maintenanceLogs)): ?>
                                    <tr>
                                        <td colspan="5" class="text-center">Tiada log penyelenggaraan</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($maintenanceLogs as $log): ?>
                                        <tr>
                                            <td><?php echo date('d/m/Y H:i', strtotime($log['created_at'])); ?></td>
                                            <td><?php echo htmlspecialchars($log['activity']); ?></td>
                                            <td><span
                                                    class="badge badge-<?php echo $log['status'] === 'Aktif' ? 'success' : ($log['status'] === 'Maintenance' ? 'warning' : 'info'); ?>"><?php echo $log['status']; ?></span>
                                            </td>
                                            <td><?php echo htmlspecialchars($log['details'] ?? '-'); ?></td>
                                            <td>
                                                <button class="btn btn-secondary btn-sm"
                                                    onclick="editMaintenanceLog(<?php echo $log['id']; ?>, '<?php echo htmlspecialchars($log['activity']); ?>', '<?php echo htmlspecialchars($log['status']); ?>', '<?php echo htmlspecialchars($log['details'] ?? ''); ?>')"
                                                    title="Edit">✏️</button>
                                                <button class="btn btn-danger btn-sm btn-icon"
                                                    onclick="deleteMaintenanceLog(<?php echo $log['id']; ?>)">🗑️</button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <div id="footer" class="tab-content">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">Tetapan Footer</h3>
                </div>
                <div class="card-body">
                    <form id="footerSettingsForm" onsubmit="saveFooterSettings(event)">
                        <div class="form-group">
                            <label class="form-label">Teks Hak Cipta</label>
                            <input type="text" class="form-control" name="footer_text" id="footerText"
                                value="<?php echo htmlspecialchars($footerText); ?>">
                            <p class="form-text">Teks ini akan muncul di footer semua halaman</p>
                        </div>
                        <button type="submit" class="btn btn-primary">Simpan</button>
                    </form>
                </div>
            </div>
        </div>
    </main>
</div>

<!-- Mobile Bottom Navigation (iPhone Modern App Style) -->
<nav class="mobile-bottom-nav">
    <a href="#" onclick="switchTab(event, 'dashboard')" class="nav-tab-item active" id="mob-nav-dashboard">
        <span class="nav-icon">📊</span>
        <span>Home</span>
    </a>
    <a href="#" onclick="switchTab(event, 'notifications')" class="nav-tab-item" id="mob-nav-notifications">
        <span class="nav-icon">🔔</span>
        <span>Berita</span>
    </a>
    <a href="#" onclick="switchTab(event, 'teachers')" class="nav-tab-item" id="mob-nav-teachers">
        <span class="nav-icon">👨‍🏫</span>
        <span>Guru</span>
    </a>
    <a href="#" onclick="switchTab(event, 'settings')" class="nav-tab-item" id="mob-nav-settings">
        <span class="nav-icon">⚙️</span>
        <span>Tetapan</span>
    </a>
    <a href="#" onclick="event.preventDefault(); event.stopPropagation(); toggleMobileMenu()" class="nav-tab-item">
        <span class="nav-icon">☰</span>
        <span>Menu</span>
    </a>
</nav>

<div class="modal-overlay" id="addTeacherModal">
    <div class="modal">
        <div class="modal-header">
            <h3 class="modal-title">Tambah Guru Baru</h3>
            <button class="modal-close" onclick="closeModal('addTeacherModal')">×</button>
        </div>
        <div class="modal-body">
            <form id="addTeacherForm" onsubmit="submitAddTeacher(event)">
                <div class="form-group">
                    <label class="form-label">Nama Penuh <span class="required">*</span></label>
                    <input type="text" class="form-control" name="full_name" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Telefon <span class="required">*</span></label>
                    <input type="tel" class="form-control" name="phone" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Tahap Mengajar <span class="required">*</span></label>
                    <select class="form-control form-select" name="education_level" required>
                        <option value="">Pilih</option>
                        <option value="Sekolah Rendah">Sekolah Rendah</option>
                        <option value="Sekolah Menengah">Sekolah Menengah</option>
                        <option value="Sekolah Rendah dan Sekolah Menengah">Sekolah Rendah dan Sekolah Menengah
                        </option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Pilih Tahun / Tingkatan <span class="required">*</span></label>
                    <div
                        style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; background: #f8f9fa; padding: 15px; border-radius: 8px; border: 1px solid #ddd;">

                        <div>
                            <h5
                                style="font-size:14px; font-weight:bold; color:#667eea; border-bottom:1px solid #ccc; padding-bottom:5px;">
                                Sekolah Rendah</h5>
                            <label class="form-check"><input type="checkbox" name="grades[]" value="Tahun 1"> Tahun
                                1</label>
                            <label class="form-check"><input type="checkbox" name="grades[]" value="Tahun 2"> Tahun
                                2</label>
                            <label class="form-check"><input type="checkbox" name="grades[]" value="Tahun 3"> Tahun
                                3</label>
                            <label class="form-check"><input type="checkbox" name="grades[]" value="Tahun 4"> Tahun
                                4</label>
                            <label class="form-check"><input type="checkbox" name="grades[]" value="Tahun 5"> Tahun
                                5</label>
                            <label class="form-check"><input type="checkbox" name="grades[]" value="Tahun 6"> Tahun
                                6</label>
                        </div>

                        <div>
                            <h5
                                style="font-size:14px; font-weight:bold; color:#667eea; border-bottom:1px solid #ccc; padding-bottom:5px;">
                                Sekolah Menengah</h5>
                            <label class="form-check"><input type="checkbox" name="grades[]" value="Peralihan">
                                Peralihan</label>
                            <label class="form-check"><input type="checkbox" name="grades[]" value="Tingkatan 1">
                                Tingkatan 1</label>
                            <label class="form-check"><input type="checkbox" name="grades[]" value="Tingkatan 2">
                                Tingkatan 2</label>
                            <label class="form-check"><input type="checkbox" name="grades[]" value="Tingkatan 3">
                                Tingkatan 3</label>
                            <label class="form-check"><input type="checkbox" name="grades[]" value="Tingkatan 4">
                                Tingkatan 4</label>
                            <label class="form-check"><input type="checkbox" name="grades[]" value="Tingkatan 5">
                                Tingkatan 5</label>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">Subjek Yang Diajar <span class="required">*</span></label>
                    <div id="subjectChecklist" class="subject-checklist">
                        <p class="text-muted">Memuatkan subjek...</p>
                    </div>

                    <div id="customSubjectWrapper" class="custom-subject-wrapper">
                        <label class="form-label" style="font-size: 0.9em;">Nyatakan subjek lain:</label>
                        <input type="text" class="form-control" id="customSubjectInput"
                            placeholder="cth: Sains Komputer, Pendidikan Muzik">
                    </div>
                </div>
                <button type="submit" class="btn btn-primary" style="width: 100%; margin-top: 10px;">Tambah
                    Guru</button>
            </form>
        </div>
    </div>
</div>

<!-- Announcement Modal -->
<div class="modal-overlay" id="announcementModal">
    <div class="modal" style="max-width: 650px;">
        <div class="modal-header">
            <h3 class="modal-title">📢 Buat Pengumuman</h3>
            <button class="modal-close" onclick="closeModal('announcementModal')">×</button>
        </div>
        <div class="modal-body">
            <form id="announcementForm" onsubmit="saveAnnouncement(event)">
                <input type="hidden" name="id" id="announcementId">

                <div class="form-group">
                    <label class="form-label">Tajuk <span class="required">*</span></label>
                    <input type="text" class="form-control" name="title" id="announcementTitle" required
                        placeholder="cth: Pengumuman Penting">
                </div>

                <div class="form-row" style="grid-template-columns: 1fr 1fr;">
                    <div class="form-group">
                        <label class="form-label">Kategori <span class="required">*</span></label>
                        <select class="form-control form-select" name="category" id="announcementCategory" required>
                            <option value="Umum">Umum</option>
                            <option value="Akademik">Akademik</option>
                            <option value="Aktiviti">Aktiviti</option>
                            <option value="Lain-lain">Lain-lain</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Sasaran <span class="required">*</span></label>
                        <select class="form-control form-select" name="target_audience" id="announcementTarget"
                            required>
                            <option value="all_teachers">Semua Guru</option>
                            <option value="my_students">Pelajar Saya Sahaja</option>
                        </select>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Priority</label>
                    <select class="form-control form-select" name="priority" id="announcementPriority">
                        <option value="Normal">Normal</option>
                        <option value="Penting">Penting</option>
                        <option value="Urgent">Urgent</option>
                    </select>
                </div>

                <div class="form-group">
                    <label class="form-label">Kandungan <span class="required">*</span></label>
                    <textarea class="form-control" name="content" id="announcementContent" rows="5" required
                        placeholder="Tulis pengumuman..."></textarea>
                </div>

                <div class="form-group">
                    <label class="form-label">Pautan Lampiran (Optional)</label>
                    <input type="url" class="form-control" name="attachment_link" id="announcementAttachment"
                        placeholder="https://...">
                    <small class="text-muted">Pautan ke dokumen, imej, atau video berkaitan</small>
                </div>

                <div class="form-group">
                    <label class="form-label">Tarikh Tamat (Optional)</label>
                    <input type="date" class="form-control" name="expiry_date" id="announcementExpiry">
                    <small class="text-muted">Pengumuman akan hilang secara automatik selepas tarikh ini</small>
                </div>

                <div style="margin-top: 20px; display: flex; gap: 10px;">
                    <button type="button" class="btn btn-secondary" style="flex: 1;"
                        onclick="closeModal('announcementModal')">Batal</button>
                    <button type="submit" class="btn btn-primary" style="flex: 1;">📢 Hantar Pengumuman</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Maintenance Log Modal -->
<div class="modal-overlay" id="editMaintenanceModal">
    <div class="modal">
        <div class="modal-header">
            <h3 class="modal-title">Kemaskini Log Penyelenggaraan</h3>
            <button class="modal-close" onclick="closeModal('editMaintenanceModal')">×</button>
        </div>
        <div class="modal-body">
            <form id="editMaintenanceForm" onsubmit="submitEditMaintenanceLog(event)">
                <input type="hidden" name="log_id" id="editLogId">
                <div class="form-group">
                    <label class="form-label">Aktiviti <span class="required">*</span></label>
                    <input type="text" class="form-control" name="activity" id="editActivity" required
                        placeholder="cth: Kemas kini sistem">
                </div>
                <div class="form-group">
                    <label class="form-label">Status</label>
                    <select class="form-control form-select" name="status" id="editStatus">
                        <option value="Aktif">Aktif</option>
                        <option value="Maintenance">Maintenance</option>
                        <option value="Selesai">Selesai</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Keterangan</label>
                    <textarea class="form-control" name="details" id="editDetails" rows="3"
                        placeholder="Keterangan lanjut..."></textarea>
                </div>
                <button type="submit" class="btn btn-primary" style="width: 100%;">Simpan Perubahan</button>
            </form>
        </div>
    </div>
</div>


<script src="../js/main.js"></script>
<script>
    // Mobile Menu Toggle
    function switchTab(event, tabId) {
        if (event) event.preventDefault();

        // 1. Remove active class from all nav items
        document.querySelectorAll('.nav-item').forEach(item => {
            item.classList.remove('active');
        });

        // 2. Sync with mobile bottom navigation
        document.querySelectorAll('.nav-tab-item').forEach(el => el.classList.remove('active'));
        const mobNav = document.getElementById('mob-nav-' + tabId);
        if (mobNav) mobNav.classList.add('active');

        // 3. Add active class to clicked nav
        const activeNav = document.getElementById('nav-' + tabId);
        if (activeNav) activeNav.classList.add('active');

        // 4. Hide all tab contents
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.remove('active');
            if (content.id !== tabId) {
                content.style.display = 'none';
            }
        });

        // 5. Show selected tab content
        const activeTab = document.getElementById(tabId);
        if (activeTab) {
            activeTab.style.display = 'block';
            activeTab.style.opacity = '1';
            activeTab.classList.add('active');

            // Load data based on tabId
            switch (tabId) {
                case 'dashboard':
                    loadTeachers();
                    break;
                case 'teachers':
                    loadTeachers();
                    loadSubjectsList();
                    break;
                case 'announcements':
                    loadAnnouncements();
                    break;
                case 'notifications':
                    loadNotifications();
                    break;
            }

            // Save state
            localStorage.setItem('activeTab', tabId);
        }

        // Auto close mobile menu if open
        closeMobileMenu();
    }

    function toggleMobileMenu() {
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('sidebarOverlay');
        if (sidebar && overlay) {
            sidebar.classList.toggle('open');
            overlay.classList.toggle('show');
            document.body.style.overflow = sidebar.classList.contains('open') ? 'hidden' : '';
        }
    }

    function closeMobileMenu() {
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('sidebarOverlay');
        if (sidebar) sidebar.classList.remove('open');
        if (overlay) overlay.classList.remove('show');
        document.body.style.overflow = '';
    }

    // --- PREMIUM UI UTILITIES ---
    function animateValue(id, start, end, duration) {
        if (start === end) {
            document.getElementById(id).textContent = end;
            return;
        }
        var obj = document.getElementById(id);
        if (!obj) return;
        var range = end - start;
        var current = start;
        var increment = end > start ? 1 : -1;
        var stepTime = Math.abs(Math.floor(duration / (range === 0 ? 1 : range)));
        stepTime = Math.max(stepTime, 20); // Smoothness limit

        var timer = setInterval(function () {
            current += increment;
            obj.textContent = current;
            if (current == end) {
                clearInterval(timer);
            }
        }, stepTime);
    }

    function updateBannerTime() {
        var now = new Date();
        var days = ['Ahad', 'Isnin', 'Selasa', 'Rabu', 'Khamis', 'Jumaat', 'Sabtu'];
        var months = ['Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ogos', 'Sep', 'Okt', 'Nov', 'Dis'];

        var timeStr = String(now.getHours()).padStart(2, '0') + ':' +
            String(now.getMinutes()).padStart(2, '0') + ':' +
            String(now.getSeconds()).padStart(2, '0');

        var dayEl = document.getElementById('bannerDay');
        var dateEl = document.getElementById('bannerDate');
        var timeEl = document.getElementById('bannerTime');

        if (dayEl) dayEl.textContent = days[now.getDay()];
        if (dateEl) dateEl.textContent = now.getDate() + ' ' + months[now.getMonth()] + ' ' + now.getFullYear();
        if (timeEl) timeEl.textContent = timeStr;
    }

    // --- CLOCK & INITIALIZATION ---
    function updateRealtimeClock() {
        var now = new Date();
        var days = ['Ahad', 'Isnin', 'Selasa', 'Rabu', 'Khamis', 'Jumaat', 'Sabtu'];
        var months = ['Januari', 'Februari', 'Mac', 'April', 'Mei', 'Jun', 'Julai', 'Ogos', 'September', 'Oktober', 'November', 'Disember'];

        var hours24 = now.getHours();
        var minutes = String(now.getMinutes()).padStart(2, '0');
        var seconds = String(now.getSeconds()).padStart(2, '0');

        var suffix = 'Pagi';
        if (hours24 >= 19) suffix = 'Malam';
        else if (hours24 >= 14) suffix = 'Petang';
        else if (hours24 >= 12) suffix = 'Tengah Hari';
        else suffix = 'Pagi';

        var hours12 = hours24 % 12;
        hours12 = hours12 ? hours12 : 12;
        var timeStr = hours12 + ':' + minutes + ':' + seconds + ' ' + suffix;

        var clockEl = document.getElementById('realtimeClock');
        var dateEl = document.getElementById('realtimeDate');
        if (clockEl) clockEl.textContent = timeStr;
        if (dateEl) dateEl.textContent = days[now.getDay()] + ', ' + now.getDate() + ' ' + months[now.getMonth()] + ' ' + now.getFullYear();
    }

    document.addEventListener('DOMContentLoaded', function () {
        updateRealtimeClock();
        setInterval(updateRealtimeClock, 1000);
        updateBannerTime();
        setInterval(updateBannerTime, 1000);

        // Trigger CountUp for stats
        setTimeout(() => {
            animateValue('countTeachers', 0, <?php echo $teacherCount; ?>, 1500);
            animateValue('countStudents', 0, <?php echo $studentCount; ?>, 1500);

            // REALTIME SYNC: Refresh admin stats every 60 seconds
            setInterval(refreshAdminStats, 60000);
        }, 500);

        function refreshAdminStats() {
            fetch('../api.php?action=admin_stats')
                .then(res => res.json())
                .then(res => {
                    if (res.success) {
                        const tc = document.getElementById('countTeachers');
                        const sc = document.getElementById('countStudents');

                        if (tc) tc.textContent = res.stats.teachers;
                        if (sc) sc.textContent = res.stats.students;
                    }
                })
                .catch(err => console.error('Error refreshing admin stats:', err));
        }

        loadTeachers();
        loadSubjects();
        loadSubjectsList();

        // Restore last open tab
        // const savedTab = localStorage.getItem('activeTab') || 'dashboard';
        // switchTab(null, savedTab);
        switchTab(null, 'dashboard'); // Always load dashboard

        // Load announcements on page load
        loadAnnouncements();
        // Load notifications on page load
        if (typeof loadNotifications === 'function') {
            loadNotifications();
        }
    });

    // --- API CALLS ---

    function showCredentials(username) {
        // Ambil warna tema semasa dari CSS Variable
        const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim();
        const loginInfo = `Maklumat Login TutorKita\n\nUsername: ${username}\nPassword: tutor123`;

        Swal.fire({
            title: '🔐 Maklumat Login Guru',
            html: `
                    <div style="text-align: left; background: #fdfdfd; padding: 18px; border-radius: 12px; border: 2px dashed ${themeColor}; margin-top: 15px; position: relative;">
                        <p style="margin-bottom: 10px; font-size: 0.95rem;">
                            <strong>Nama Pengguna:</strong> 
                            <code style="color: ${themeColor}; font-size: 1.15em; font-weight: bold; background: #f0f2ff; padding: 2px 6px; border-radius: 4px;">${username}</code>
                        </p>
                        <p style="margin-bottom: 0; font-size: 0.95rem;">
                            <strong>Kata Laluan:</strong> 
                            <code style="color: ${themeColor}; font-size: 1.15em; font-weight: bold; background: #f0f2ff; padding: 2px 6px; border-radius: 4px;">tutor123</code>
                        </p>
                    </div>
                    <p style="margin-top: 15px; font-size: 0.85rem; color: #666; line-height: 1.4;">
                        Sila berikan maklumat ini kepada guru untuk log masuk ke portal.
                    </p>
                `,
            icon: 'info',
            iconColor: themeColor,
            showCancelButton: true,
            confirmButtonText: '📋 Salin Maklumat',
            cancelButtonText: 'Tutup',
            confirmButtonColor: themeColor,
            cancelButtonColor: '#6c757d',
            borderRadius: '15px',
            reverseButtons: true,
            focusConfirm: false
        }).then((result) => {
            if (result.isConfirmed) {
                // Fungsi salin ke clipboard
                navigator.clipboard.writeText(loginInfo).then(() => {
                    const Toast = Swal.mixin({
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 2500,
                        timerProgressBar: true
                    });
                    Toast.fire({
                        icon: 'success',
                        title: 'Maklumat berjaya disalin!'
                    });
                });
            }
        });
    }


    function loadSubjects() {
        fetch('../api.php?action=get_subjects')
            .then(r => r.json())
            .then(result => {
                var container = document.getElementById('subjectChecklist');
                if (result.success && result.subjects && result.subjects.length > 0) {
                    var html = '';
                    result.subjects.forEach(s => {
                        html += `<label class="form-check"><input type="checkbox" name="subjects[]" value="${s.subject_name}"><span class="form-check-label">${s.subject_name}</span></label>`;
                    });
                    // Add "Lain-Lain" option
                    html += `<label class="form-check">
                                    <input type="checkbox" id="chkLainLain" onchange="toggleCustomSubject(this)">
                                    <span class="form-check-label">✏️ Lain-Lain</span>
                                 </label>`;
                    container.innerHTML = html;
                } else {
                    container.innerHTML = '<p class="text-muted">Tiada subjek tersedia</p>';
                }
            })
            .catch(err => console.error(err));
    }

    function toggleCustomSubject(checkbox) {
        var wrapper = document.getElementById('customSubjectWrapper');
        if (checkbox.checked) {
            wrapper.classList.add('show');
            document.getElementById('customSubjectInput').focus();
        } else {
            wrapper.classList.remove('show');
            document.getElementById('customSubjectInput').value = '';
        }
    }

    function submitAddTeacher(e) {
        if (e) e.preventDefault();

        var form = document.getElementById('addTeacherForm');
        var formData = new FormData(form);
        formData.append('action', 'add_teacher');

        // Proses Checkbox Gred
        formData.delete('grades[]');
        var checkedGrades = form.querySelectorAll('input[name="grades[]"]:checked');

        var hasRendah = false;
        var hasMenengah = false;

        checkedGrades.forEach(cb => {
            formData.append('grades[]', cb.value);
            if (cb.value.includes('Tahun')) hasRendah = true;
            if (cb.value.includes('Tingkatan') || cb.value.includes('Peralihan')) hasMenengah = true;
        });

        // AUTO-DETECT TAHAP PENDIDIKAN
        var eduLevel = "";
        if (hasRendah && hasMenengah) {
            eduLevel = "Sekolah Rendah & Sekolah Menengah (SR & SM)";
        } else if (hasMenengah) {
            eduLevel = "Sekolah Menengah";
        } else {
            eduLevel = "Sekolah Rendah";
        }

        // Set nilai ini supaya masuk ke database tanpa ralat truncated
        formData.set('education_level', eduLevel);

        fetch('../api.php', { method: 'POST', body: formData })
            .then(r => r.json())
            .then(res => {
                if (res.success) {
                    showNotification('Guru berjaya ditambah!', 'success');
                    closeModal('addTeacherModal');
                    loadTeachers();
                } else {
                    showNotification('❌ ' + res.message, 'error');
                }
            })
            .catch(err => {
                showNotification('❌ Ralat sambungan', 'error');
            })
            .finally(() => {
                btn.disabled = false;
                btn.innerHTML = 'Tambah Guru';
            });
    }

    function deleteTeacher(id) {
        Swal.fire({
            title: 'Padam Guru Ini?',
            text: "Tindakan ini akan memadam rekod secara kekal.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ffcdd2', // Merah cair pilihan anda
            cancelButtonColor: '#6c757d',
            confirmButtonText: '<span style="color: #c62828">Ya, Padam</span>',
            cancelButtonText: 'Batal',
            borderRadius: '15px',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                var formData = new FormData();
                formData.append('action', 'delete_teacher');
                formData.append('id', id);

                fetch('../api.php', { method: 'POST', body: formData })
                    .then(r => r.json())
                    .then(res => {
                        if (res.success) {
                            Swal.fire({
                                title: '✅ Berjaya!',
                                text: 'Rekod guru telah dipadam.',
                                icon: 'success',
                                confirmButtonColor: 'var(--primary-color)'
                            });
                            loadTeachers();
                        } else {
                            Swal.fire('Ralat!', res.message, 'error');
                        }
                    })
                    .catch(err => {
                        Swal.fire('Ralat!', 'Masalah sambungan server.', 'error');
                    });
            }
        });
    }
    function updateAdminSettings(e) {
        e.preventDefault();

        // 1. Tukar status butang kepada loading
        const btn = e.target.querySelector('button[type="submit"]');
        const originalBtnText = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '⏳ Menyelaraskan...';

        var formData = new FormData(document.getElementById('settingsForm'));
        formData.append('action', 'update_admin_settings');

        fetch('../api.php', { method: 'POST', body: formData })
            .then(r => r.json())
            .then(res => {
                if (res.success) {
                    // 2. Notifikasi Toast Berjaya
                    const Toast = Swal.mixin({
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 1500,
                        timerProgressBar: true
                    });

                    Toast.fire({
                        icon: 'success',
                        title: 'Tetapan berjaya dikemaskini'
                    }).then(() => {
                        // 3. Reload untuk apply perubahan warna/nama portal
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: 'Gagal!',
                        text: res.message,
                        icon: 'error',
                        confirmButtonColor: 'var(--primary-color)',
                        borderRadius: '15px'
                    });
                    btn.disabled = false;
                    btn.innerHTML = originalBtnText;
                }
            })
            .catch(err => {
                console.error(err);
                Swal.fire('Ralat!', 'Masalah sambungan server.', 'error');
                btn.disabled = false;
                btn.innerHTML = originalBtnText;
            });
    }

    function toggleMaintenanceMode(isEnabled) {
        const warningDiv = document.getElementById('maintenanceWarning');
        const toggleSlider = document.querySelector('#maintenanceMode + .toggle-slider');
        const toggleKnob = document.querySelector('#maintenanceMode + .toggle-slider .toggle-knob');

        if (isEnabled) {
            warningDiv.style.display = 'block';
            if (toggleSlider) toggleSlider.style.backgroundColor = '#dc3545';
            if (toggleKnob) toggleKnob.style.transform = 'translateX(32px)';

            // Show confirmation for enabling maintenance mode
            Swal.fire({
                title: 'Aktifkan Mod Penyelenggaraan?',
                html: '<div style="text-align: left;">' +
                    '<p>⚠️ <strong>PERINGATAN:</strong> Semua pengguna tidak boleh log masuk semasa mod penyelenggaraan aktif.</p>' +
                    '<ul style="text-align: left; margin: 15px 0;">' +
                    '<li>• Pelajar tidak boleh log masuk</li>' +
                    '<li>• Guru tidak boleh log masuk</li>' +
                    '<li>• Hanya admin boleh log masuk</li>' +
                    '<li>• Halaman log masuk akan menunjukkan mesej penyelenggaraan</li>' +
                    '</ul>' +
                    '<p>Adakah anda pasti mahu meneruskan?</p>' +
                    '</div>',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Ya, Aktifkan',
                cancelButtonText: 'Batal',
                borderRadius: '15px',
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed) {
                    saveMaintenanceStatus(true);
                } else {
                    // User cancelled - revert toggle
                    document.getElementById('maintenanceMode').checked = false;
                    warningDiv.style.display = 'none';
                    if (toggleSlider) toggleSlider.style.backgroundColor = '#6c757d';
                    if (toggleKnob) toggleKnob.style.transform = 'translateX(4px)';
                }
            });
        } else {
            warningDiv.style.display = 'none';
            if (toggleSlider) toggleSlider.style.backgroundColor = '#6c757d';
            if (toggleKnob) toggleKnob.style.transform = 'translateX(4px)';

            // Show confirmation for disabling maintenance mode
            Swal.fire({
                title: 'Nyahaktifkan Mod Penyelenggaraan?',
                text: 'Sistem akan kembali normal dan semua pengguna boleh log masuk.',
                icon: 'info',
                showCancelButton: true,
                confirmButtonColor: 'var(--primary-color)',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Ya, Nyahaktifkan',
                cancelButtonText: 'Batal',
                borderRadius: '15px',
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed) {
                    saveMaintenanceStatus(false);
                } else {
                    // User cancelled - revert toggle
                    document.getElementById('maintenanceMode').checked = true;
                    warningDiv.style.display = 'block';
                    if (toggleSlider) toggleSlider.style.backgroundColor = '#dc3545';
                    if (toggleKnob) toggleKnob.style.transform = 'translateX(32px)';
                }
            });
        }
    }

    function saveMaintenanceStatus(isEnabled) {
        const formData = new FormData();
        formData.append('action', 'toggle_maintenance_mode');
        formData.append('enabled', isEnabled);

        fetch('../api.php', {
            method: 'POST',
            body: formData
        })
            .then(r => r.json())
            .then(res => {
                if (res.success) {
                    showNotification(res.message, 'success');
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showNotification(res.message, 'error');
                    location.reload();
                }
            })
            .catch(err => {
                console.error(err);
                showNotification('Ralat sambungan', 'error');
                location.reload();
            });
    }


    function saveOprSettings(e) {
        e.preventDefault();

        // 1. Ambil butang dan tukar status kepada loading
        const btn = e.target.querySelector('button[type="submit"]');
        const originalBtnText = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '<span style="opacity: 0.8;">💾 Menyimpan...</span>';

        var formData = new FormData();
        formData.append('action', 'save_opr_settings');
        formData.append('description', document.getElementById('oprDescription').value);
        formData.append('link', document.getElementById('oprLink').value);

        fetch('../api.php', { method: 'POST', body: formData })
            .then(r => r.json())
            .then(res => {
                if (res.success) {
                    // 2. Paparan Toast kejayaan
                    const Toast = Swal.mixin({
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 2000,
                        timerProgressBar: true
                    });

                    Toast.fire({
                        icon: 'success',
                        title: 'Tetapan OPR berjaya disimpan!'
                    });
                } else {
                    // 3. Paparan ralat jika gagal
                    Swal.fire({
                        title: 'Ralat!',
                        text: res.message || 'Gagal menyimpan tetapan.',
                        icon: 'error',
                        confirmButtonColor: 'var(--primary-color)',
                        borderRadius: '15px'
                    });
                }
            })
            .catch(err => {
                console.error(err);
                Swal.fire('Ralat!', 'Masalah sambungan server.', 'error');
            })
            .finally(() => {
                // 4. Kembalikan butang ke asal
                btn.disabled = false;
                btn.innerHTML = originalBtnText;
            });
    }

    function addMaintenanceLog(e) {
        e.preventDefault();

        // Ambil butang hantar untuk tukar status loading
        const btn = e.target.querySelector('button[type="submit"]');
        const originalBtnText = btn.innerHTML;

        btn.disabled = true;
        btn.innerHTML = '📌 Menyimpan...';

        var formData = new FormData(e.target);
        formData.append('action', 'add_maintenance_log');

        fetch('../api.php', { method: 'POST', body: formData })
            .then(r => r.json())
            .then(res => {
                if (res.success) {
                    // Notifikasi Toast yang selaras dengan tema
                    const Toast = Swal.mixin({
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 1500,
                        timerProgressBar: true
                    });

                    Toast.fire({
                        icon: 'success',
                        title: 'Log berjaya ditambah!'
                    }).then(() => {
                        e.target.reset();
                        location.reload(); // Reload hanya selepas toast selesai
                    });
                } else {
                    Swal.fire({
                        title: 'Gagal!',
                        text: res.message,
                        icon: 'error',
                        confirmButtonColor: 'var(--primary-color)',
                        borderRadius: '15px'
                    });
                    btn.disabled = false;
                    btn.innerHTML = originalBtnText;
                }
            })
            .catch(err => {
                console.error(err);
                Swal.fire('Ralat!', 'Masalah sambungan server.', 'error');
                btn.disabled = false;
                btn.innerHTML = originalBtnText;
            });
    }

    function deleteMaintenanceLog(id) {
        // Ambil warna tema utama jika perlu untuk konsistensi butang
        const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim();

        Swal.fire({
            title: 'Padam Log?',
            text: "Rekod ini akan dipadamkan secara kekal dari sistem.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ffcdd2', // Merah cair tema portal anda
            cancelButtonColor: '#6c757d',
            confirmButtonText: '<span style="color: #c62828; font-weight: bold;">Ya, Padam</span>',
            cancelButtonText: 'Batal',
            borderRadius: '15px',
            reverseButtons: true,
            focusCancel: true
        }).then((result) => {
            if (result.isConfirmed) {
                var formData = new FormData();
                formData.append('action', 'delete_maintenance_log');
                formData.append('id', id);

                fetch('../api.php', { method: 'POST', body: formData })
                    .then(r => r.json())
                    .then(res => {
                        if (res.success) {
                            // Menggunakan Toast supaya lebih moden sebelum reload
                            const Toast = Swal.mixin({
                                toast: true,
                                position: 'top-end',
                                showConfirmButton: false,
                                timer: 1500,
                                timerProgressBar: true
                            });

                            Toast.fire({
                                icon: 'success',
                                title: 'Log telah dipadam'
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire({
                                title: 'Ralat!',
                                text: res.message,
                                icon: 'error',
                                confirmButtonColor: themeColor
                            });
                        }
                    })
                    .catch(err => {
                        console.error(err);
                        Swal.fire('Ralat!', 'Masalah sambungan server.', 'error');
                    });
            }
        });
    }

    function saveFooterSettings(e) {
        e.preventDefault();
        var formData = new FormData();
        formData.append('action', 'save_footer_settings');
        formData.append('footer_text', document.getElementById('footerText').value);
        fetch('../api.php', { method: 'POST', body: formData })
            .then(r => r.json())
            .then(res => showNotification(res.success ? 'Footer dikemaskini' : res.message, res.success ? 'success' : 'error'));

    }
    // FUNGSI UNTUK KEMASKINI STATUS GURU (TOGGLE)
    function toggleTeacherStatus(teacherId, newStatus) {
        const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

        Swal.fire({
            title: newStatus === 'Active' ? 'Aktifkan Guru?' : 'Nyahaktifkan Guru?',
            html: newStatus === 'Active'
                ? 'Guru ini akan dapat log masuk dan menerima pelajar baharu.'
                : '<div style="background: #fff3cd; padding: 10px; border-radius: 8px; border-left: 4px solid #ffc107; text-align: left;">' +
                '<strong>⚠️ Peringatan:</strong><br>' +
                '• Guru tidak akan dapat log masuk<br>' +
                '• Guru tidak akan menerima pelajar baharu<br>' +
                '• Pelajar sedia ada tidak akan terjejas' +
                '</div>',
            icon: newStatus === 'Active' ? 'success' : 'warning',
            showCancelButton: true,
            confirmButtonColor: newStatus === 'Active' ? themeColor : '#6c757d',
            cancelButtonColor: '#6c757d',
            confirmButtonText: newStatus === 'Active' ? 'Ya, Aktifkan' : 'Ya, Nyahaktifkan',
            cancelButtonText: 'Batal',
            borderRadius: '15px',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                var formData = new FormData();
                formData.append('action', 'update_teacher_status_by_admin');
                formData.append('teacher_id', teacherId);
                formData.append('status', newStatus);

                fetch('../api.php', { method: 'POST', body: formData })
                    .then(r => r.json())
                    .then(res => {
                        if (res.success) {
                            showNotification(res.message, 'success');
                            loadTeachers(); // Reload untuk update UI
                        } else {
                            loadTeachers();
                            showNotification(res.message, 'error');
                        }
                    })
                    .catch(err => {
                        loadTeachers();
                        showNotification('Ralat sambungan', 'error');
                    });
            }
        });
    }
    // FUNGSI UNTUK PAPARKAN TOGGLE STATUS DALAM JADUAL
    function renderStatusToggle(teacher) {
        var isActive = teacher.status === 'Active';
        var teacherId = teacher.id;

        return `
            <label class="toggle-switch" style="display: inline-block; width: 50px; height: 26px; position: relative; cursor: pointer;">
                <input type="checkbox" ${isActive ? 'checked' : ''} 
                       onchange="toggleTeacherStatus(${teacherId}, this.checked ? 'Active' : 'Inactive')"
                       style="opacity: 0; width: 0; height: 0;">
                <span class="toggle-slider" style="position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: ${isActive ? '#28a745' : '#6c757d'}; transition: .4s; border-radius: 34px; display: block;">
                    <span class="toggle-knob" style="position: absolute; content: ''; height: 20px; width: 20px; left: ${isActive ? '26px' : '4px'}; bottom: 3px; background-color: white; transition: .4s; border-radius: 50%;"></span>
                </span>
            </label>
            <span class="badge badge-${isActive ? 'success' : 'secondary'}" style="margin-left: 8px; font-size: 0.75rem;">
                ${isActive ? 'Aktif' : 'Tidak Aktif'}
            </span>
        `;
    }

    // FUNGSI UNTUK PAPARKAN TOGGLE STATUS (DIGUNA DALAM JADUAL)
    function renderStatusToggleForRow(teacherId, currentStatus) {
        var isActive = currentStatus === 'Active';
        return `
            <label class="toggle-switch" style="display: inline-block; width: 50px; height: 26px; position: relative; cursor: pointer; vertical-align: middle;">
                <input type="checkbox" ${isActive ? 'checked' : ''} 
                       onchange="toggleTeacherStatus(${teacherId}, this.checked ? 'Active' : 'Inactive')"
                       style="opacity: 0; width: 0; height: 0;">
                <span class="toggle-slider" style="position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: ${isActive ? '#28a745' : '#6c757d'}; transition: .4s; border-radius: 34px; display: block;">
                    <span class="toggle-knob" style="position: absolute; content: ''; height: 20px; width: 20px; left: ${isActive ? '26px' : '4px'}; bottom: 3px; background-color: white; transition: .4s; border-radius: 50%;"></span>
                </span>
            </label>
        `;
    }

    // Memuatkan data dari server
    function loadTeachers() {
        fetch('../api.php?action=get_all_teachers')
            .then(r => r.json())
            .then(result => {
                if (result.success && result.teachers) {
                    allTeachersData = result.teachers; // Simpan ke global variable
                    renderTeachersTable(allTeachersData); // Paparkan
                } else {
                    document.getElementById('teachersList').innerHTML = '<tr><td colspan="7" class="text-center">Tiada guru berdaftar</td></tr>';
                }
            })
            .catch(err => console.error(err));
    }

    // Fungsi untuk melukis jadual (Reusable)
    function renderTeachersTable(data) {
        var tbody = document.getElementById('teachersList');
        var html = '';

        if (data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="7" class="text-center">Tiada padanan ditemui</td></tr>';
            return;
        }

        data.forEach((teacher, i) => {
            let subjectsArray = [];
            try { subjectsArray = JSON.parse(teacher.subjects || '[]'); } catch (e) { subjectsArray = []; }

            let subjectsHTML = subjectsArray.length > 0
                ? subjectsArray.map(s => `<span style="display: inline-block; background: #fff; border: 1px solid #ddd; padding: 2px 10px; border-radius: 6px; margin: 3px; font-size: 0.8rem; color: #444;">${s}</span>`).join('')
                : '<span style="color:#999; font-style:italic;">Tiada subjek</span>';

            html += `
            <tr>
                <td style="vertical-align: middle; text-align: center;">${i + 1}</td>
                <td style="vertical-align: middle;">
                    <div style="font-weight: 600; color: #333;">${teacher.full_name}</div>
                    <div style="font-size: 0.8rem; color: var(--primary-color);">@${teacher.username}</div>
                </td>
                <td style="vertical-align: middle;">${teacher.phone}</td>
                <td style="vertical-align: middle;">${teacher.email}</td>
                <td style="vertical-align: middle;">${teacher.education_level}</td>
                <td style="vertical-align: middle;">
                    <div style="background: #f8f9fa; border: 1px dashed #ccc; padding: 10px; border-radius: 10px; max-width: 280px;">
                        ${subjectsHTML}
                    </div>
                </td>
                <td style="vertical-align: middle; text-align: center;">
                    ${renderStatusToggleForRow(teacher.id, teacher.status)}
                </td>
                <td style="vertical-align: middle;">
                    <div style="display: flex; gap: 8px; justify-content: center;">
                        <button class="btn btn-info btn-sm" onclick="showCredentials('${teacher.username}')" title="Paparan Login" style="padding: 6px 10px; border-radius: 8px;">ℹ️</button>
                        <button class="btn btn-warning btn-sm" onclick="resetTeacherPassword('${teacher.username}')" title="Reset Kata Laluan" style="padding: 6px 10px; border-radius: 8px;">🔑</button>
                        <button class="btn btn-danger btn-sm btn-icon" onclick="deleteTeacher(${teacher.id})" style="padding: 6px 10px; border-radius: 8px;">🗑️</button>
                    </div>
                </td>
            </tr>`;
        });
        tbody.innerHTML = html;
    }

    // FUNGSI CARIAN (LIVE SEARCH)
    function filterTeachers() {
        const searchTerm = document.getElementById('teacherSearchInput').value.toLowerCase();
        const filtered = allTeachersData.filter(t =>
            t.full_name.toLowerCase().includes(searchTerm) ||
            t.username.toLowerCase().includes(searchTerm)
        );
        renderTeachersTable(filtered);
    }

    // FUNGSI SUSUN A-Z
    let isAscending = true;
    function sortTeachersAlphabetical() {
        const sorted = [...allTeachersData].sort((a, b) => {
            const nameA = a.full_name.toUpperCase();
            const nameB = b.full_name.toUpperCase();
            return isAscending ? nameA.localeCompare(nameB) : nameB.localeCompare(nameA);
        });

        isAscending = !isAscending; // Tukar arah susunan untuk klik seterusnya
        renderTeachersTable(sorted);

        // Tukar ikon butang (opsional)
        const btn = event.currentTarget;
        btn.innerHTML = isAscending ? '<span>🔤</span> Susun A-Z' : '<span>🔤</span> Susun Z-A';
    }

    // ========== NOTIFICATION FUNCTIONS ==========
    var notificationsData = [];
    var notificationInterval = null;

    // Note: DOMContentLoaded handler moved to after function definitions (around line 3160)

    function loadNotifications() {
        fetch('../api.php?action=get_notifications')
            .then(function (response) { return response.json(); })
            .then(function (result) {
                if (result.success && result.notifications) {
                    notificationsData = result.notifications;
                    displayNotifications();

                    // Update sidebar badge
                    var unreadCount = notificationsData.filter(function (n) { return n.is_read !== 'Yes'; }).length;
                    var badge = document.getElementById('sidebarNotificationBadge');
                    if (badge) {
                        if (unreadCount > 0) {
                            badge.textContent = unreadCount;
                            badge.style.display = 'inline-block';
                        } else {
                            badge.style.display = 'none';
                        }
                    }
                } else {
                    console.warn('Notifications API returned unsuccessful:', result.message);
                }
            })
            .catch(function (err) {
                console.error('Error loading notifications:', err);
            });
    }

    function displayNotifications() {
        var tabContainer = document.getElementById('notificationTabList');
        if (notificationsData && notificationsData.length > 0) {
            var html = '';
            notificationsData.forEach(function (n) {
                var isRead = n.is_read === 'Yes' ? '' : 'border-left: 4px solid var(--primary-color); background: #f0f7ff;';
                var icon = getNotificationIcon(n.type);
                var readBadge = n.is_read === 'Yes' ? '' : '<span class="badge bg-primary" style="font-size: 10px; margin-left: 8px;">Baru</span>';

                html += '<div class="notification-card-item" style="padding: 20px; border-bottom: 1px solid #eee; margin-bottom: 10px; border-radius: 12px; transition: all 0.2s ease; cursor: pointer; ' + isRead + '" onclick="handleNotificationClick(' + n.id + ', \'' + n.type + '\')">';
                html += '<div style="display: flex; gap: 15px; align-items: start;">';
                html += '<div style="font-size: 2rem; background: white; width: 50px; height: 50px; display: flex; align-items: center; justify-content: center; border-radius: 12px; box-shadow: 0 4px 10px rgba(0,0,0,0.05);">' + icon + '</div>';
                html += '<div style="flex: 1;">';
                html += '<div style="display: flex; justify-content: space-between; align-items: start;">';
                html += '<div><strong>' + n.title + '</strong>' + readBadge + '</div>';
                html += '<button class="btn btn-sm btn-icon" onclick="event.stopPropagation(); deleteNotification(' + n.id + ')" title="Padam" style="background: #fee2e2; color: #ef4444; border: none; padding: 5px 8px; border-radius: 6px;">🗑️</button>';
                html += '</div>';
                html += '<p style="margin: 8px 0 0 0; color: #555; line-height: 1.5;">' + n.message + '</p>';
                html += '<div style="margin-top: 10px; display: flex; align-items: center; gap: 15px; color: #999; font-size: 0.8rem;">';
                html += '<span>📅 ' + formatDateTime(n.created_at) + '</span>';
                if (n.is_read !== 'Yes') {
                    html += '<span style="color: var(--primary-color); font-weight: 600;">● Belum Dibaca</span>';
                }
                html += '</div>';
                html += '</div></div></div>';
            });
            if (tabContainer) tabContainer.innerHTML = html;
        } else {
            if (tabContainer) tabContainer.innerHTML = '<div style="text-align: center; padding: 60px 20px;"><div style="font-size: 4rem; opacity: 0.2;">🔔</div><h4 style="margin-top: 20px; color: #999;">Tiada notifikasi baru</h4><p class="text-muted">Semua notifikasi penting akan dipaparkan di sini.</p></div>';
        }
    }

    function getNotificationIcon(type) {
        switch (type) {
            case 'success': return '✅';
            case 'error': return '❌';
            case 'warning': return '⚠️';
            case 'announcement': return '📢';
            case 'forum': return '💬';
            case 'student': return '👨‍🎓';
            case 'enrollment': return '📝';
            default: return '🔔';
        }
    }

    function formatDateTime(dateString) {
        if (!dateString) return '';
        var date = new Date(dateString);
        var now = new Date();
        var diff = now - date;

        if (diff < 3600000) {
            var mins = Math.floor(diff / 60000);
            return mins + ' minit lalu';
        }
        if (diff < 86400000) {
            var hours = Math.floor(diff / 3600000);
            return hours + ' jam lalu';
        }
        var days = ['Ahad', 'Isnin', 'Selasa', 'Rabu', 'Khamis', 'Jumaat', 'Sabtu'];
        var months = ['Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ogos', 'Sep', 'Okt', 'Nov', 'Dis'];
        return days[date.getDay()] + ', ' + date.getDate() + ' ' + months[date.getMonth()] + ' ' + date.getFullYear() + ' ' +
            String(date.getHours()).padStart(2, '0') + ':' + String(date.getMinutes()).padStart(2, '0');
    }

    // Check DB Fix on load
    function checkDbFix() {
        if (!localStorage.getItem('db_fixed_v1')) {
            fetch('../fix_db.php')
                .then(r => r.json())
                .then(res => {
                    console.log('DB Fix:', res);
                    if (res.success) localStorage.setItem('db_fixed_v1', 'true');
                })
                .catch(e => console.error(e));
        }
    }
    document.addEventListener('DOMContentLoaded', checkDbFix);

    // === NOTIFICATION FUNCTIONS ===
    // Make it GLOBAL so HTML onclick can find it


    function selectAdminEmoji(el) {
        document.querySelectorAll('#adminEmojiPicker .emoji-option').forEach(opt => opt.classList.remove('selected'));
        el.classList.add('selected');
        document.getElementById('adminSelectedEmoji').value = el.dataset.emoji;
    }

    // Close dropdown when clicking outside

    function handleNotificationClick(id, type) {
        markNotificationRead(id, type);
    }

    function markNotificationRead(id, type) {
        var formData = new FormData();
        formData.append('action', 'mark_notification_read');
        formData.append('id', id);

        fetch('../api.php', { method: 'POST', body: formData })
            .then(function (response) { return response.json(); })
            .then(function (result) {
                loadNotifications();
            });
    }

    function markAllNotificationsRead() {
        var formData = new FormData();
        formData.append('action', 'mark_notification_read');
        formData.append('id', 0);

        fetch('../api.php', { method: 'POST', body: formData })
            .then(function (response) { return response.json(); })
            .then(function (result) {
                loadNotifications();
                showNotification('Semua notifikasi dibaca', 'success');
            });
    }

    function deleteNotification(id) {
        // Get portal theme color
        const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

        Swal.fire({
            title: 'Padam Notifikasi?',
            text: "Notifikasi ini akan dipadamkan secara kekal.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: themeColor,
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Ya, Padam',
            cancelButtonText: 'Batal',
            borderRadius: '15px',
            reverseButtons: true,
            focusCancel: true
        }).then((result) => {
            if (result.isConfirmed) {
                var formData = new FormData();
                formData.append('action', 'delete_notification');
                formData.append('id', id);

                fetch('../api.php', { method: 'POST', body: formData })
                    .then(function (response) { return response.json(); })
                    .then(function (result) {
                        if (result.success) {
                            Swal.fire({
                                title: '✅ Berjaya!',
                                text: 'Notifikasi telah dipadam.',
                                icon: 'success',
                                confirmButtonColor: themeColor,
                                borderRadius: '15px'
                            });
                            loadNotifications();
                        } else {
                            Swal.fire({
                                title: 'Ralat!',
                                text: result.message,
                                icon: 'error',
                                confirmButtonColor: themeColor,
                                borderRadius: '15px'
                            });
                        }
                    })
                    .catch(function (err) {
                        Swal.fire({
                            title: 'Ralat Sambungan!',
                            text: 'Sila cuba lagi.',
                            icon: 'error',
                            confirmButtonColor: themeColor,
                            borderRadius: '15px'
                        });
                    });
            }
        });
    }

    // Initialize notifications after all functions are defined
    document.addEventListener('DOMContentLoaded', function () {
        // Load notifications on start
        loadNotifications();
        // Check for new notifications every 30 seconds
        notificationInterval = setInterval(loadNotifications, 30000);
    });

    // ========== ANNOUNCEMENT FUNCTIONS ==========
    function showAddAnnouncementModal() {
        openModal('announcementModal');
        document.getElementById('announcementForm').reset();
        document.getElementById('announcementId').value = '';
    }

    function loadAnnouncements() {
        const container = document.getElementById('announcementsList'); // FIXED: Match HTML ID
        if (!container) return;

        container.innerHTML = '<p class="text-center text-muted">Memuatkan...</p>';

        fetch('../api.php?action=get_announcements')
            .then(function (response) { return response.json(); })
            .then(function (result) {
                if (result.success && result.announcements && result.announcements.length > 0) {
                    var html = '';
                    result.announcements.forEach(function (a) {
                        var priorityClass = a.priority === 'Urgent' ? 'danger' : (a.priority === 'Penting' ? 'warning' : 'primary');
                        var priorityIcon = a.priority === 'Urgent' ? '🚨' : (a.priority === 'Penting' ? '⚠️' : 'ℹ️');
                        var targetBadge = a.target_audience ? '<span class="badge badge-secondary" style="margin-left:5px;">👥 ' + a.target_audience + '</span>' : '';

                        // Encode for JS
                        var titleEnc = encodeURIComponent(a.title);
                        var contentEnc = encodeURIComponent(a.content);
                        var categoryEnc = encodeURIComponent(a.category || 'Umum');

                        html += '<div class="card" style="border-left: 4px solid var(--primary-color); margin-bottom: 20px;">';
                        html += '<div class="card-body">';
                        html += '<div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 10px;">';
                        html += '<div>';
                        html += '<h5 style="margin: 0; color: var(--primary-color); font-weight: 700;">' + a.title + '</h5>';
                        html += '<div style="margin-top: 5px; font-size: 0.85rem; color: #666;">';
                        html += '<span>📅 ' + formatDateTime(a.created_at) + '</span> • ';
                        html += '<span>📂 ' + (a.category || 'Umum') + '</span>';
                        html += targetBadge;
                        html += '</div>';
                        html += '</div>';
                        html += '<div style="display: flex; gap: 5px; align-items: center;">';
                        html += '<span class="badge badge-' + priorityClass + '">' + priorityIcon + ' ' + a.priority + '</span>';
                        html += '<button class="btn btn-primary btn-sm btn-icon" onclick="openEditAnnouncementModal(' + a.id + ', \'' + titleEnc + '\', \'' + contentEnc + '\', \'' + categoryEnc + '\', \'' + a.priority + '\', \'' + a.target_audience + '\', \'' + (a.attachment_link || '') + '\', \'' + (a.expiry_date || '') + '\')" title="Edit">✏️</button>';
                        html += '<button class="btn btn-danger btn-sm btn-icon" onclick="deleteAnnouncement(' + a.id + ')" title="Padam">🗑️</button>';
                        html += '</div></div>';
                        html += '<p style="margin: 15px 0 10px 0; color: #444; line-height: 1.6;">' + a.content + '</p>';
                        if (a.attachment_link) {
                            html += '<a href="' + a.attachment_link + '" target="_blank" class="btn btn-outline-primary btn-sm">🔗 Lihat Lampiran</a>';
                        }
                        html += '</div></div>';
                    });
                    container.innerHTML = html;
                } else {
                    container.innerHTML = '<div style="text-align: center; padding: 40px;"><div style="font-size: 3rem; opacity: 0.3;">📢</div><p class="text-muted mt-3">Tiada pengumuman dijumpai</p></div>';
                }
            })
            .catch(function (err) {
                console.error('Error loading announcements:', err);
                container.innerHTML = '<p class="text-center text-danger">Ralat memuatkan pengumuman.</p>';
            });
    }

    function openEditAnnouncementModal(id, title, content, category, priority, target, attachment, expiry) {
        document.getElementById('announcementId').value = id;
        document.getElementById('announcementTitle').value = decodeURIComponent(title);
        document.getElementById('announcementContent').value = decodeURIComponent(content);
        document.getElementById('announcementCategory').value = decodeURIComponent(category);
        document.getElementById('announcementPriority').value = priority;
        document.getElementById('announcementTarget').value = target;
        document.getElementById('announcementAttachment').value = attachment || '';
        document.getElementById('announcementExpiry').value = expiry || '';

        openModal('announcementModal');
    }

    function saveAnnouncement(event) {
        event.preventDefault();
        var formData = new FormData(document.getElementById('announcementForm'));
        var id = document.getElementById('announcementId').value;

        formData.append('action', id ? 'update_announcement' : 'add_announcement');

        var btn = event.target.querySelector('button[type="submit"]');
        var originalText = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '⏳ Menyimpan...';

        fetch('../api.php', { method: 'POST', body: formData })
            .then(function (response) { return response.json(); })
            .then(function (result) {
                if (result.success) {
                    showNotification(result.message || 'Pengumuman berjaya disimpan', 'success');
                    closeModal('announcementModal');
                    loadAnnouncements();
                } else {
                    showNotification(result.message, 'error');
                }
            })
            .catch(function (err) {
                showNotification('Ralat sambungan', 'error');
            })
            .finally(function () {
                btn.disabled = false;
                btn.innerHTML = originalText;
            });
    }

    // Function to delete announcement
    function deleteAnnouncement(id) {
        const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

        Swal.fire({
            title: 'Padam Pengumuman?',
            text: "Pengumuman ini akan dipadamkan secara kekal.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: themeColor,
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Ya, Padam',
            cancelButtonText: 'Batal',
            borderRadius: '15px',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                var formData = new FormData();
                formData.append('action', 'delete_announcement_by_admin');
                formData.append('id', id);

                fetch('../api.php', { method: 'POST', body: formData })
                    .then(function (response) { return response.json(); })
                    .then(function (res) {
                        if (res.success) {
                            showNotification('Pengumuman berjaya dipadam', 'success');
                            loadAnnouncements();
                        } else {
                            showNotification(res.message, 'error');
                        }
                    })
                    .catch(function (err) {
                        showNotification('Ralat sambungan', 'error');
                    });
            }
        });
    }

    // ========== MAINTENANCE LOG EDIT FUNCTIONS ==========
    function editMaintenanceLog(id, activity, status, details) {
        document.getElementById('editLogId').value = id;
        document.getElementById('editActivity').value = activity;
        document.getElementById('editStatus').value = status;
        document.getElementById('editDetails').value = details || '';
        openModal('editMaintenanceModal');
    }

    function submitEditMaintenanceLog(e) {
        e.preventDefault();

        const btn = e.target.querySelector('button[type="submit"]');
        const originalBtnText = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '⏳ Menyimpan...';

        var formData = new FormData(e.target);
        formData.append('action', 'update_maintenance_log');

        fetch('../api.php', { method: 'POST', body: formData })
            .then(r => r.json())
            .then(res => {
                if (res.success) {
                    const Toast = Swal.mixin({
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 1500,
                        timerProgressBar: true
                    });

                    Toast.fire({
                        icon: 'success',
                        title: 'Log berjaya dikemaskini!'
                    }).then(() => {
                        closeModal('editMaintenanceModal');
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: 'Gagal!',
                        text: res.message,
                        icon: 'error',
                        confirmButtonColor: 'var(--primary-color)',
                        borderRadius: '15px'
                    });
                    btn.disabled = false;
                    btn.innerHTML = originalBtnText;
                }
            })
            .catch(err => {
                console.error(err);
                Swal.fire({
                    title: 'Ralat!',
                    text: 'Masalah sambungan server.',
                    icon: 'error',
                    confirmButtonColor: 'var(--primary-color)',
                    borderRadius: '15px'
                });
                btn.disabled = false;
                btn.innerHTML = originalBtnText;
            });
    }
    // --- SUBJECT MANAGEMENT ---
    function loadSubjectsList() {
        fetch('../api.php?action=get_subjects')
            .then(response => response.json())
            .then(result => {
                const tbody = document.getElementById('subjectsList');
                if (!tbody) return;
                if (result.success && result.subjects && result.subjects.length > 0) {
                    let html = '';
                    result.subjects.forEach(subject => {
                        html += `
                                <tr>
                                    <td>${subject.subject_name}</td>
                                    <td>${subject.subject_code || '-'}</td>
                                    <td>${subject.category}</td>
                                    <td>${subject.education_level || 'Semua'}</td>
                                    <td>
                                        <button class="btn btn-sm btn-danger btn-icon" onclick="deleteSubject(${subject.id})" title="Padam">🗑️</button>
                                    </td>
                                </tr>
                            `;
                    });
                    tbody.innerHTML = html;
                } else {
                    tbody.innerHTML = '<tr><td colspan="5" class="text-center" style="padding: 20px;">Tiada subjek dijumpai.</td></tr>';
                }
            });
    }

    function showAddSubjectModal() {
        document.getElementById('addSubjectForm').reset();
        openModal('addSubjectModal');
    }

    function saveSubject(event) {
        event.preventDefault();
        const form = event.target;
        const submitBtn = form.querySelector('button[type="submit"]');
        const originalBtnText = submitBtn.innerHTML;

        submitBtn.disabled = true;
        submitBtn.innerHTML = '⏳ Menyimpan...';

        const formData = new FormData(form);
        formData.append('action', 'add_subject');

        fetch('../api.php', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    showNotification('✅ Subjek berjaya ditambah!', 'success');
                    closeModal('addSubjectModal');
                    loadSubjects(); // Update checklist in Add Teacher modal
                    loadSubjectsList(); // Update subjects table
                } else {
                    Swal.fire({
                        title: 'Ralat!',
                        text: result.message || 'Gagal menambah subjek.',
                        icon: 'error',
                        confirmButtonColor: 'var(--primary-color)'
                    });
                }
            })
            .catch(err => {
                console.error('Save Subject Error:', err);
                showNotification('❌ Ralat sambungan', 'error');
            })
            .finally(() => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnText;
            });
    }

    function deleteSubject(id) {
        Swal.fire({
            title: 'Nyah-aktifkan Subjek?',
            text: "Subjek ini tidak akan dipaparkan untuk pendaftaran baharu.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ffcdd2',
            cancelButtonColor: '#6c757d',
            confirmButtonText: '<span style="color: #c62828">Ya, Nyah-aktifkan</span>',
            cancelButtonText: 'Batal',
            borderRadius: '15px',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                const formData = new FormData();
                formData.append('action', 'delete_subject');
                formData.append('id', id);

                fetch('../api.php', { method: 'POST', body: formData })
                    .then(response => response.json())
                    .then(res => {
                        if (res.success) {
                            showNotification('Subjek berjaya dinyah-aktifkan.', 'success');
                            loadSubjects();
                            loadSubjectsList();
                        } else {
                            Swal.fire('Ralat!', res.message, 'error');
                        }
                    });
            }
        });
    }

    function showAddTeacherModal() {
        const form = document.getElementById('addTeacherForm');
        if (form) form.reset();
        loadSubjects();
        openModal('addTeacherModal');
    }
    function resetTeacherPassword(username) {
        const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

        Swal.fire({
            title: 'Reset Kata Laluan?',
            text: `Adakah anda pasti mahu reset kata laluan untuk guru "${username}" kepada "tutor123"?`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: themeColor,
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Ya, Reset',
            cancelButtonText: 'Batal',
            borderRadius: '15px',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                const formData = new FormData();
                formData.append('action', 'reset_teacher_password');
                formData.append('username', username);

                fetch('../api.php', {
                    method: 'POST',
                    body: formData
                })
                    .then(response => response.json())
                    .then(result => {
                        if (result.success) {
                            showNotification(result.message, 'success');
                        } else {
                            Swal.fire('Ralat!', result.message, 'error');
                        }
                    });
            }
        });
    }

    // ========== DELETE ALL NOTIFICATIONS ==========
    function deleteAllNotifications() {
        const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

        Swal.fire({
            title: 'Padam Semua Notifikasi?',
            text: "Semua notifikasi akan dipadamkan secara kekal.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Ya, Padam Semua',
            cancelButtonText: 'Batal',
            borderRadius: '15px',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                var formData = new FormData();
                formData.append('action', 'delete_all_notifications');

                fetch('../api.php', { method: 'POST', body: formData })
                    .then(response => response.json())
                    .then(result => {
                        if (result.success) {
                            showNotification('Semua notifikasi berjaya dipadam', 'success');
                            loadNotifications();
                        } else {
                            showNotification(result.message || 'Gagal memadam notifikasi', 'error');
                        }
                    })
                    .catch(err => {
                        showNotification('Ralat sambungan', 'error');
                    });
            }
        });
    }
</script>

<!-- Bootstrap 5 JS Bundle (includes Popper) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>