<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../config/rbac.php';
require_once '../includes/functions.php';
require_once '../includes/middleware.php';

requireLogin();
requireRole('admin');

$db = getDB();
$user = getUserContext();
$userId = $_SESSION['user_id'];

// Get comprehensive admin statistics
$stats = [];

// Total Users
$stmt = $db->prepare("SELECT COUNT(*) FROM users");
$stmt->execute();
$stats['total_users'] = $stmt->fetchColumn();

// Total Instructors
$stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE role = 'instructor'");
$stmt->execute();
$stats['total_instructors'] = $stmt->fetchColumn();

// Total Students
$stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE role = 'student'");
$stmt->execute();
$stats['total_students'] = $stmt->fetchColumn();

// Active Users (last 30 days)
$stmt = $db->prepare("SELECT COUNT(DISTINCT user_id) FROM user_activities WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)");
$stmt->execute();
$stats['active_users'] = $stmt->fetchColumn();

// Total Courses
$stmt = $db->prepare("SELECT COUNT(*) FROM courses");
$stmt->execute();
$stats['total_courses'] = $stmt->fetchColumn();

// Published Courses
$stmt = $db->prepare("SELECT COUNT(*) FROM courses WHERE status = 'published'");
$stmt->execute();
$stats['published_courses'] = $stmt->fetchColumn();

// Total Exams
$stmt = $db->prepare("SELECT COUNT(*) FROM exams");
$stmt->execute();
$stats['total_exams'] = $stmt->fetchColumn();

// Total Posts
$stmt = $db->prepare("SELECT COUNT(*) FROM posts");
$stmt->execute();
$stats['total_posts'] = $stmt->fetchColumn();

// Published Posts
$stmt = $db->prepare("SELECT COUNT(*) FROM posts WHERE status = 'published'");
$stmt->execute();
$stats['published_posts'] = $stmt->fetchColumn();

// Draft Posts
$stmt = $db->prepare("SELECT COUNT(*) FROM posts WHERE status = 'draft'");
$stmt->execute();
$stats['draft_posts'] = $stmt->fetchColumn();

// Total Enrollments
$stmt = $db->prepare("SELECT COUNT(*) FROM course_enrollments");
$stmt->execute();
$stats['total_enrollments'] = $stmt->fetchColumn();

// Total Categories
$stmt = $db->prepare("SELECT COUNT(*) FROM categories");
$stmt->execute();
$stats['total_categories'] = $stmt->fetchColumn();

// Course Categories
$stmt = $db->prepare("SELECT COUNT(*) FROM course_categories");
$stmt->execute();
$stats['total_course_categories'] = $stmt->fetchColumn();

// Recent Users
$stmt = $db->prepare("
    SELECT u.*, up.first_name, up.last_name 
    FROM users u 
    LEFT JOIN user_profiles up ON u.id = up.user_id 
    ORDER BY u.created_at DESC 
    LIMIT 5
");
$stmt->execute();
$recentUsers = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Recent Posts
$stmt = $db->prepare("
    SELECT p.*, c.name as category_name 
    FROM posts p 
    LEFT JOIN categories c ON p.category_id = c.id 
    ORDER BY p.created_at DESC 
    LIMIT 5
");
$stmt->execute();
$recentPosts = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Recent Course Enrollments
$stmt = $db->prepare("
    SELECT ce.*, c.title as course_title, u.username as student_name, up.first_name, up.last_name
    FROM course_enrollments ce
    JOIN courses c ON ce.course_id = c.id
    JOIN users u ON ce.student_id = u.id
    LEFT JOIN user_profiles up ON u.id = up.user_id
    ORDER BY ce.enrollment_date DESC
    LIMIT 5
");
$stmt->execute();
$recentEnrollments = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Recent Exam Attempts
$stmt = $db->prepare("
    SELECT ea.*, e.title as exam_title, u.username as student_name
    FROM exam_attempts ea
    JOIN exams e ON ea.exam_id = e.id
    JOIN users u ON ea.student_id = u.id
    ORDER BY ea.started_at DESC
    LIMIT 5
");
$stmt->execute();
$recentExamAttempts = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Pending Question Reviews
$stmt = $db->prepare("
    SELECT q.*, u.username as instructor_name, qc.name as category_name
    FROM questions q
    LEFT JOIN users u ON q.instructor_id = u.id
    LEFT JOIN question_categories qc ON q.category_id = qc.id
    WHERE q.status = 'pending_review'
    ORDER BY q.created_at DESC
    LIMIT 5
");
$stmt->execute();
$pendingQuestions = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get calendar events for widget
$stmt = $db->prepare("
    SELECT * FROM calendar_events 
    WHERE event_date >= CURDATE() 
    ORDER BY event_date ASC 
    LIMIT 5
");
$stmt->execute();
$upcomingEvents = $stmt->fetchAll(PDO::FETCH_ASSOC);

$page_title = 'Admin Dashboard';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($user['username'] ?? 'Admin'); ?>'s Dashboard | Mutalex Academy</title>
    <!-- Load Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Set up Tailwind configuration for professional color palette -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#1E3A8A',
                        'background-light': '#F8FAFC',
                        'text-dark': '#1F2937',
                        'accent-subtle': '#E5E7EB',
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        /* Custom scrollbar */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-thumb {
            background-color: #D1D5DB;
            border-radius: 4px;
        }
        ::-webkit-scrollbar-track {
            background-color: transparent;
        }

        /* Smooth transitions */
        .transition-all {
            transition: all 0.3s ease;
        }

        /* Card hover effects */
        .stat-card {
            transition: all 0.3s ease;
        }
        .stat-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        }

        /* List item styling */
        .list-item {
            transition: all 0.2s ease;
        }
        .list-item:hover {
            background-color: #f8fafc;
        }
    </style>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen">

    <!-- Main Application Container -->
    <div id="app" class="flex">

        <!-- Top Bar (Mobile/Desktop Header) -->
        <header class="bg-white shadow-sm fixed top-0 left-0 right-0 z-10 border-b border-accent-subtle">
            <div class="px-4 sm:px-6 lg:px-8 py-4 flex justify-between items-center">
                <div class="flex items-center space-x-3">
                    <img src="../assets/images/logo_1757657555.jpg" alt="Mutalex Academy Logo" class="h-10 w-10">
                    <div>
                        <h1 class="text-xl font-bold text-primary-blue">Mutalex Academy</h1>
                        <p class="text-sm text-gray-600">Admin Dashboard</p>
                    </div>
                </div>

                <div class="flex items-center space-x-4">
                    <!-- Notifications -->
                    <button class="text-gray-600 hover:text-primary-blue p-2 rounded-full relative transition duration-150">
                        <i class="fas fa-bell"></i>
                        <?php if (count($pendingQuestions) > 0): ?>
                            <span class="absolute -top-1 -right-1 bg-red-500 text-white text-xs font-bold rounded-full h-5 w-5 flex items-center justify-center">
                                <?php echo count($pendingQuestions); ?>
                            </span>
                        <?php endif; ?>
                    </button>

                    <!-- User Profile -->
                    <div class="flex items-center space-x-2">
                        <span class="text-sm font-medium hidden sm:inline"><?php echo htmlspecialchars($user['username'] ?? 'Admin'); ?></span>
                        <img class="h-10 w-10 rounded-full border-2 border-primary-blue object-cover" src="https://placehold.co/100x100/1E3A8A/ffffff?text=<?php echo substr(htmlspecialchars($user['username'] ?? 'A'), 0, 1); ?>" alt="User Avatar">
                    </div>
                </div>
            </div>
        </header>

        <!-- Sidebar Navigation (Desktop View) -->
        <aside class="hidden lg:block w-64 bg-white border-r border-accent-subtle p-6 shadow-sm sticky top-16 h-screen overflow-y-auto">
            <div class="flex flex-col h-full">
                <!-- Navigation Links -->
                <nav class="space-y-2 flex-grow">
                    <a href="dashboard.php" class="flex items-center space-x-3 p-3 rounded-lg bg-primary-blue text-white font-semibold transition duration-150 shadow-md">
                        <i class="fas fa-tachometer-alt w-5"></i>
                        <span>Dashboard</span>
                    </a>
                    <a href="analytics.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <i class="fas fa-chart-bar w-5"></i>
                        <span>Analytics</span>
                    </a>
                    <a href="users.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <i class="fas fa-users w-5"></i>
                        <span>User Management</span>
                    </a>
                    <a href="posts.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <i class="fas fa-file-alt w-5"></i>
                        <span>Posts</span>
                    </a>
                    <a href="categories.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <i class="fas fa-folder w-5"></i>
                        <span>Categories</span>
                    </a>
                    <a href="course_categories.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <i class="fas fa-tags w-5"></i>
                        <span>Course Categories</span>
                    </a>
                    <a href="course_pricing.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <i class="fas fa-dollar-sign w-5"></i>
                        <span>Course Pricing</span>
                    </a>
                    <a href="exam_pricing.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <i class="fas fa-file-invoice-dollar w-5"></i>
                        <span>Exam Pricing</span>
                    </a>
                    <a href="payment_gateways.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <i class="fas fa-credit-card w-5"></i>
                        <span>Payment Settings</span>
                    </a>
                    <a href="announcements.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <i class="fas fa-bullhorn w-5"></i>
                        <span>Announcements</span>
                    </a>
                    <a href="calendar.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <i class="fas fa-calendar w-5"></i>
                        <span>Calendar Events</span>
                    </a>
                    <a href="roles.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <i class="fas fa-shield-alt w-5"></i>
                        <span>Roles Management</span>
                    </a>
                    <a href="site_settings.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <i class="fas fa-cogs w-5"></i>
                        <span>Site Settings</span>
                    </a>
                    <a href="logs.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <i class="fas fa-history w-5"></i>
                        <span>System Audit Logs</span>
                    </a>
                    <a href="../home.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150" target="_blank">
                        <i class="fas fa-eye w-5"></i>
                        <span>View Site</span>
                    </a>
                    <a href="../logout.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <i class="fas fa-sign-out-alt w-5"></i>
                        <span>Logout</span>
                    </a>
                </nav>

                <!-- Footer/User Info (Bottom of Sidebar) -->
                <div class="mt-8 pt-4 border-t border-accent-subtle">
                    <p class="text-xs text-gray-500 mb-2">Authenticated User:</p>
                    <p class="text-xs text-gray-700 truncate font-mono bg-accent-subtle p-1 rounded"><?php echo htmlspecialchars($user['username'] ?? 'User'); ?></p>
                </div>
            </div>
        </aside>

        <!-- Main Content Area -->
        <main class="flex-1 overflow-y-auto pt-16 lg:pl-0">

            <!-- Dashboard Content Grid -->
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 lg:py-12 grid grid-cols-1 lg:grid-cols-3 gap-8">

                <!-- Column 1 & 2: Main Focus -->
                <section class="lg:col-span-2 space-y-8">

                    <!-- Welcome Banner -->
                    <div class="bg-white p-6 sm:p-8 rounded-xl shadow-lg border border-accent-subtle">
                        <h2 class="text-3xl font-bold text-primary-blue mb-2">Welcome back, <?php echo htmlspecialchars($user['username'] ?? 'Admin'); ?>.</h2>
                        <p class="text-gray-600">Here's what's happening with your academy today.</p>
                    </div>

                    <!-- Quick Stats / Key Metrics -->
                    <div class="grid grid-cols-2 sm:grid-cols-4 gap-4">
                        <!-- Stat Card 1 -->
                        <div class="stat-card bg-white p-5 rounded-xl shadow-lg border border-accent-subtle text-center cursor-pointer">
                            <div class="text-3xl font-extrabold text-primary-blue"><?php echo $stats['total_users'] ?? 0; ?></div>
                            <p class="text-sm font-medium text-gray-500 mt-1">Total Users</p>
                        </div>
                        <!-- Stat Card 2 -->
                        <div class="stat-card bg-white p-5 rounded-xl shadow-lg border border-accent-subtle text-center cursor-pointer">
                            <div class="text-3xl font-extrabold text-green-600"><?php echo $stats['total_courses'] ?? 0; ?></div>
                            <p class="text-sm font-medium text-gray-500 mt-1">Total Courses</p>
                        </div>
                        <!-- Stat Card 3 -->
                        <div class="stat-card bg-white p-5 rounded-xl shadow-lg border border-accent-subtle text-center cursor-pointer">
                            <div class="text-3xl font-extrabold text-purple-600"><?php echo $stats['total_exams'] ?? 0; ?></div>
                            <p class="text-sm font-medium text-gray-500 mt-1">Total Exams</p>
                        </div>
                        <!-- Stat Card 4 -->
                        <div class="stat-card bg-white p-5 rounded-xl shadow-lg border border-accent-subtle text-center cursor-pointer">
                            <div class="text-3xl font-extrabold text-indigo-600"><?php echo $stats['active_users'] ?? 0; ?></div>
                            <p class="text-sm font-medium text-gray-500 mt-1">Active Users (30d)</p>
                        </div>
                    </div>

                    <!-- More Stats Row -->
                    <div class="grid grid-cols-2 sm:grid-cols-4 gap-4">
                        <!-- Stat Card 5 -->
                        <div class="stat-card bg-white p-5 rounded-xl shadow-lg border border-accent-subtle text-center cursor-pointer">
                            <div class="text-3xl font-extrabold text-teal-600"><?php echo $stats['total_enrollments'] ?? 0; ?></div>
                            <p class="text-sm font-medium text-gray-500 mt-1">Enrollments</p>
                        </div>
                        <!-- Stat Card 6 -->
                        <div class="stat-card bg-white p-5 rounded-xl shadow-lg border border-accent-subtle text-center cursor-pointer">
                            <div class="text-3xl font-extrabold text-orange-600"><?php echo $stats['total_posts'] ?? 0; ?></div>
                            <p class="text-sm font-medium text-gray-500 mt-1">Total Posts</p>
                        </div>
                        <!-- Stat Card 7 -->
                        <div class="stat-card bg-white p-5 rounded-xl shadow-lg border border-accent-subtle text-center cursor-pointer">
                            <div class="text-3xl font-extrabold text-blue-600"><?php echo $stats['published_posts'] ?? 0; ?></div>
                            <p class="text-sm font-medium text-gray-500 mt-1">Published Posts</p>
                        </div>
                        <!-- Stat Card 8 -->
                        <div class="stat-card bg-white p-5 rounded-xl shadow-lg border border-accent-subtle text-center cursor-pointer">
                            <div class="text-3xl font-extrabold text-yellow-600"><?php echo $stats['draft_posts'] ?? 0; ?></div>
                            <p class="text-sm font-medium text-gray-500 mt-1">Draft Posts</p>
                        </div>
                    </div>

                    <!-- Recent Posts Section -->
                    <div class="bg-white p-6 rounded-xl shadow-lg border border-accent-subtle">
                        <div class="flex justify-between items-center mb-4">
                            <h2 class="text-xl font-semibold text-text-dark">Recent Posts</h2>
                            <a href="posts.php" class="text-sm text-primary-blue hover:text-primary-blue/80 font-medium">View All →</a>
                        </div>
                        <?php if (!empty($recentPosts)): ?>
                            <div class="space-y-3">
                                <?php foreach ($recentPosts as $post): ?>
                                    <div class="list-item flex justify-between items-center p-3 rounded-lg border border-gray-100">
                                        <div class="flex-1">
                                            <h4 class="text-sm font-bold text-text-dark"><?php echo htmlspecialchars($post['title']); ?></h4>
                                            <p class="text-xs text-gray-500">
                                                <span class="category"><?php echo htmlspecialchars($post['category_name'] ?? 'Uncategorized'); ?></span>
                                                <span class="mx-2">•</span>
                                                <span class="status-badge status-<?php echo $post['status']; ?>"><?php echo ucfirst($post['status']); ?></span>
                                                <span class="mx-2">•</span>
                                                <span><?php echo formatDate($post['created_at']); ?></span>
                                            </p>
                                        </div>
                                        <div class="flex gap-2 ml-3">
                                            <a href="edit_post.php?id=<?php echo $post['id']; ?>" class="text-gray-500 hover:text-primary-blue p-1" title="Edit">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <a href="../post.php?slug=<?php echo urlencode($post['slug']); ?>" class="text-gray-500 hover:text-primary-blue p-1" target="_blank" title="View">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <p class="text-gray-500 text-center py-4">No posts yet.</p>
                        <?php endif; ?>
                    </div>

                    <!-- Recent Enrollments Section -->
                    <div class="bg-white p-6 rounded-xl shadow-lg border border-accent-subtle">
                        <div class="flex justify-between items-center mb-4">
                            <h2 class="text-xl font-semibold text-text-dark">Recent Enrollments</h2>
                            <a href="users.php" class="text-sm text-primary-blue hover:text-primary-blue/80 font-medium">View All →</a>
                        </div>
                        <?php if (!empty($recentEnrollments)): ?>
                            <div class="space-y-3">
                                <?php foreach ($recentEnrollments as $enrollment): ?>
                                    <div class="list-item flex justify-between items-center p-3 rounded-lg border border-gray-100">
                                        <div class="flex-1">
                                            <h4 class="text-sm font-bold text-text-dark"><?php echo htmlspecialchars($enrollment['first_name'] . ' ' . $enrollment['last_name'] ?? $enrollment['student_name']); ?></h4>
                                            <p class="text-xs text-gray-500">
                                                <span>Enrolled in: <?php echo htmlspecialchars($enrollment['course_title']); ?></span>
                                                <span class="mx-2">•</span>
                                                <span class="status-badge <?php echo $enrollment['status'] === 'completed' ? 'status-published' : 'status-draft'; ?>"><?php echo ucfirst($enrollment['status']); ?></span>
                                            </p>
                                        </div>
                                        <div class="text-xs text-gray-400">
                                            <?php echo formatDate($enrollment['enrollment_date']); ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <p class="text-gray-500 text-center py-4">No enrollments yet.</p>
                        <?php endif; ?>
                    </div>

                    <!-- Recent Users Section -->
                    <div class="bg-white p-6 rounded-xl shadow-lg border border-accent-subtle">
                        <div class="flex justify-between items-center mb-4">
                            <h2 class="text-xl font-semibold text-text-dark">Recent Users</h2>
                            <a href="users.php" class="text-sm text-primary-blue hover:text-primary-blue/80 font-medium">View All →</a>
                        </div>
                        <?php if (!empty($recentUsers)): ?>
                            <div class="space-y-3">
                                <?php foreach ($recentUsers as $userItem): ?>
                                    <div class="list-item flex justify-between items-center p-3 rounded-lg border border-gray-100">
                                        <div class="flex items-center space-x-3">
                                            <img class="h-10 w-10 rounded-full border-2 border-primary-blue object-cover" src="https://placehold.co/100x100/1E3A8A/ffffff?text=<?php echo substr(htmlspecialchars($userItem['username'] ?? 'U'), 0, 1); ?>" alt="User Avatar">
                                            <div>
                                                <h4 class="text-sm font-bold text-text-dark"><?php echo htmlspecialchars($userItem['first_name'] . ' ' . $userItem['last_name'] ?? $userItem['username']); ?></h4>
                                                <p class="text-xs text-gray-500">@<?php echo htmlspecialchars($userItem['username']); ?></p>
                                            </div>
                                        </div>
                                        <div class="text-right">
                                            <span class="text-xs font-semibold text-white bg-primary-blue px-3 py-1 rounded-full"><?php echo ucfirst($userItem['role']); ?></span>
                                            <p class="text-xs text-gray-400 mt-1"><?php echo formatDate($userItem['created_at']); ?></p>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <p class="text-gray-500 text-center py-4">No users yet.</p>
                        <?php endif; ?>
                    </div>
                </section>

                <!-- Column 3: Secondary Information / Utility -->
                <aside class="lg:col-span-1 space-y-8">

                    <!-- Quick Actions -->
                    <div class="bg-white p-6 rounded-xl shadow-lg border border-accent-subtle">
                        <h2 class="text-xl font-semibold mb-4 text-text-dark">Quick Actions</h2>
                        <div class="grid grid-cols-2 gap-3">
                            <a href="add_post.php" class="flex flex-col items-center justify-center p-4 bg-accent-subtle rounded-lg hover:bg-gray-300 transition duration-150 text-text-dark text-sm font-medium">
                                <i class="fas fa-plus-circle text-lg mb-1"></i>
                                <span>New Post</span>
                            </a>
                            <a href="user_create.php" class="flex flex-col items-center justify-center p-4 bg-accent-subtle rounded-lg hover:bg-gray-300 transition duration-150 text-text-dark text-sm font-medium">
                                <i class="fas fa-user-plus text-lg mb-1"></i>
                                <span>Add User</span>
                            </a>
                            <a href="categories.php" class="flex flex-col items-center justify-center p-4 bg-accent-subtle rounded-lg hover:bg-gray-300 transition duration-150 text-text-dark text-sm font-medium">
                                <i class="fas fa-folder-open text-lg mb-1"></i>
                                <span>Categories</span>
                            </a>
                            <a href="announcements.php" class="flex flex-col items-center justify-center p-4 bg-accent-subtle rounded-lg hover:bg-gray-300 transition duration-150 text-text-dark text-sm font-medium">
                                <i class="fas fa-bullhorn text-lg mb-1"></i>
                                <span>Announce</span>
                            </a>
                            <a href="calendar.php" class="flex flex-col items-center justify-center p-4 bg-accent-subtle rounded-lg hover:bg-gray-300 transition duration-150 text-text-dark text-sm font-medium">
                                <i class="fas fa-calendar-plus text-lg mb-1"></i>
                                <span>Add Event</span>
                            </a>
                            <a href="site_settings.php" class="flex flex-col items-center justify-center p-4 bg-accent-subtle rounded-lg hover:bg-gray-300 transition duration-150 text-text-dark text-sm font-medium">
                                <i class="fas fa-cogs text-lg mb-1"></i>
                                <span>Settings</span>
                            </a>
                        </div>
                    </div>

                    <!-- Pending Question Reviews -->
                    <div class="bg-white p-6 rounded-xl shadow-lg border border-accent-subtle">
                        <div class="flex justify-between items-center mb-4">
                            <h2 class="text-xl font-semibold text-text-dark">Pending Reviews</h2>
                            <?php if (count($pendingQuestions) > 0): ?>
                                <span class="bg-red-500 text-white text-xs font-bold px-2 py-1 rounded-full">
                                    <?php echo count($pendingQuestions); ?>
                                </span>
                            <?php endif; ?>
                        </div>
                        <?php if (!empty($pendingQuestions)): ?>
                            <div class="space-y-3">
                                <?php foreach ($pendingQuestions as $question): ?>
                                    <div class="border-l-4 border-yellow-500 pl-3">
                                        <p class="text-sm font-bold text-text-dark"><?php echo htmlspecialchars(substr($question['content'], 0, 50)); ?><?php echo strlen($question['content']) > 50 ? '...' : ''; ?></p>
                                        <p class="text-xs text-gray-500">
                                            By: <?php echo htmlspecialchars($question['instructor_name'] ?? 'Unknown'); ?>
                                            <span class="mx-1">•</span>
                                            <?php echo ucfirst(str_replace('_', ' ', $question['question_type'])); ?>
                                        </p>
                                        <div class="mt-2 flex gap-2">
                                            <button class="text-xs bg-green-500 hover:bg-green-600 text-white px-2 py-1 rounded" onclick="approveQuestion(<?php echo $question['id']; ?>)">
                                                <i class="fas fa-check"></i> Approve
                                            </button>
                                            <button class="text-xs bg-red-500 hover:bg-red-600 text-white px-2 py-1 rounded" onclick="rejectQuestion(<?php echo $question['id']; ?>)">
                                                <i class="fas fa-times"></i> Reject
                                            </button>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <p class="text-gray-500 text-sm text-center py-4">No pending reviews</p>
                        <?php endif; ?>
                    </div>

                    <!-- Upcoming Events -->
                    <div class="bg-white p-6 rounded-xl shadow-lg border border-accent-subtle">
                        <div class="flex justify-between items-center mb-4">
                            <h2 class="text-xl font-semibold text-text-dark">Upcoming Events</h2>
                            <a href="calendar.php" class="text-sm text-primary-blue hover:text-primary-blue/80 font-medium">View All →</a>
                        </div>
                        <?php if (!empty($upcomingEvents)): ?>
                            <ul class="space-y-3">
                                <?php foreach ($upcomingEvents as $event): ?>
                                    <li class="border-l-4 border-primary-blue pl-3">
                                        <p class="text-sm font-bold text-text-dark"><?php echo htmlspecialchars($event['title']); ?></p>
                                        <p class="text-xs text-gray-500">
                                            <?php echo $event['event_date'] ? date('M j, Y', strtotime($event['event_date'])) : ''; ?>
                                            <?php if ($event['event_time']): ?>
                                                at <?php echo date('g:i A', strtotime($event['event_time'])); ?>
                                            <?php endif; ?>
                                        </p>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        <?php else: ?>
                            <p class="text-gray-500 text-sm text-center py-4">No upcoming events</p>
                        <?php endif; ?>
                    </div>

                    <!-- System Status -->
                    <div class="bg-white p-6 rounded-xl shadow-lg border border-accent-subtle">
                        <h2 class="text-xl font-semibold mb-4 text-text-dark">System Status</h2>
                        <div class="space-y-3">
                            <div class="flex justify-between items-center">
                                <span class="text-sm text-gray-600">Database</span>
                                <span class="flex items-center text-green-600 text-sm font-medium">
                                    <i class="fas fa-circle text-xs mr-2"></i>Connected
                                </span>
                            </div>
                            <div class="flex justify-between items-center">
                                <span class="text-sm text-gray-600">Users</span>
                                <span class="text-sm font-semibold text-primary-blue"><?php echo $stats['total_users'] ?? 0; ?></span>
                            </div>
                            <div class="flex justify-between items-center">
                                <span class="text-sm text-gray-600">Instructors</span>
                                <span class="text-sm font-semibold text-purple-600"><?php echo $stats['total_instructors'] ?? 0; ?></span>
                            </div>
                            <div class="flex justify-between items-center">
                                <span class="text-sm text-gray-600">Students</span>
                                <span class="text-sm font-semibold text-green-600"><?php echo $stats['total_students'] ?? 0; ?></span>
                            </div>
                            <div class="flex justify-between items-center">
                                <span class="text-sm text-gray-600">Categories</span>
                                <span class="text-sm font-semibold text-orange-600"><?php echo $stats['total_categories'] ?? 0; ?></span>
                            </div>
                        </div>
                    </div>
                </aside>
            </div>
        </main>
    </div>

    <script>
        function approveQuestion(questionId) {
            if (confirm('Are you sure you want to approve this question?')) {
                updateQuestionStatus(questionId, 'approved');
            }
        }

        function rejectQuestion(questionId) {
            const reason = prompt('Please provide a reason for rejection:');
            if (reason !== null && reason.trim() !== '') {
                updateQuestionStatus(questionId, 'rejected', reason);
            }
        }

        function updateQuestionStatus(questionId, status, reason = '') {
            const formData = new FormData();
            formData.append('question_id', questionId);
            formData.append('status', status);
            if (reason) {
                formData.append('reason', reason);
            }

            fetch('../instructor/questions/update_status.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Question status updated successfully');
                    location.reload();
                } else {
                    alert('Error updating question status: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error updating question status');
            });
        }
    </script>
</body>
</html>
