<?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';

// Check if user is instructor or admin
anyRoleMiddleware(['instructor', 'admin']);

$user = getUserContext();
$db = getDB();

// Get instructor's courses statistics
$userId = $_SESSION['user_id'];
$stmt = $db->prepare("
    SELECT
        COUNT(*) as total_courses,
        COUNT(CASE WHEN status = 'published' THEN 1 END) as published_courses,
        COUNT(CASE WHEN status = 'draft' THEN 1 END) as draft_courses
    FROM courses
    WHERE instructor_id = ?
");
$stmt->execute([$userId]);
$courseStats = $stmt->fetch();

// Get enrollment statistics
$stmt = $db->prepare("
    SELECT
        COUNT(DISTINCT ce.student_id) as total_students,
        COUNT(ce.id) as total_enrollments,
        COUNT(CASE WHEN ce.status = 'completed' THEN 1 END) as completed_enrollments
    FROM course_enrollments ce
    JOIN courses c ON ce.course_id = c.id
    WHERE c.instructor_id = ?
");
$stmt->execute([$userId]);
$enrollmentStats = $stmt->fetch();

// Get recent courses
$stmt = $db->prepare("
    SELECT c.*, COUNT(ce.id) as enrollment_count,
           COUNT(CASE WHEN ce.status = 'completed' THEN 1 END) as completion_count,
           AVG(ce.progress_percentage) as avg_progress
    FROM courses c
    LEFT JOIN course_enrollments ce ON c.id = ce.course_id
    WHERE c.instructor_id = ?
    GROUP BY c.id
    ORDER BY c.created_at DESC
    LIMIT 5
");
$stmt->execute([$userId]);
$recentCourses = $stmt->fetchAll();

// Get recent student 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
    WHERE c.instructor_id = ?
    ORDER BY ce.enrollment_date DESC
    LIMIT 10
");
$stmt->execute([$userId]);
$recentEnrollments = $stmt->fetchAll();

// Get upcoming exams that need grading
$stmt = $db->prepare("
    SELECT e.*, c.title as course_title, COUNT(ea.id) as attempts_count
    FROM exams e
    JOIN courses c ON e.course_id = c.id
    LEFT JOIN exam_attempts ea ON e.id = ea.exam_id AND ea.status = 'completed'
    WHERE c.instructor_id = ? AND e.status = 'published'
    GROUP BY e.id
    ORDER BY e.created_at DESC
    LIMIT 5
");
$stmt->execute([$userId]);
$upcomingExams = $stmt->fetchAll();

// Get course performance analytics
$stmt = $db->prepare("
    SELECT c.title, c.id,
           COUNT(ce.id) as total_enrollments,
           COUNT(CASE WHEN ce.status = 'completed' THEN 1 END) as completions,
           AVG(ce.progress_percentage) as avg_progress,
           AVG(cr.rating) as avg_rating,
           COUNT(cr.id) as review_count
    FROM courses c
    LEFT JOIN course_enrollments ce ON c.id = ce.course_id
    LEFT JOIN course_reviews cr ON c.id = cr.course_id AND cr.status = 'approved'
    WHERE c.instructor_id = ?
    GROUP BY c.id
    ORDER BY total_enrollments DESC
    LIMIT 5
");
$stmt->execute([$userId]);
$courseAnalytics = $stmt->fetchAll();

// Get pending reviews/feedback
$stmt = $db->prepare("
    SELECT cr.*, c.title as course_title, u.username as student_name,
           up.first_name, up.last_name
    FROM course_reviews cr
    JOIN courses c ON cr.course_id = c.id
    JOIN users u ON cr.student_id = u.id
    LEFT JOIN user_profiles up ON u.id = up.user_id
    WHERE c.instructor_id = ? AND cr.status = 'pending'
    ORDER BY cr.created_at DESC
    LIMIT 5
");
$stmt->execute([$userId]);
$pendingReviews = $stmt->fetchAll();

$page_title = 'Instructor Dashboard - Mutalex Academy';
?>
<!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($page_title); ?></title>
    <!-- Load Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* Custom Tailwind Configuration and Base Styles */
        :root {
            --primary: #007bff; /* Blue */
            --secondary: #6c757d; /* Gray */
            --success: #28a745; /* Green */
            --danger: #dc3545; /* Red */
            --info: #17a2b8; /* Cyan */
        }
        .text-primary { color: var(--primary); }
        .bg-primary { background-color: var(--primary); }
        .bg-success { background-color: var(--success); }
        .bg-secondary { background-color: var(--secondary); }

        /* Ensure smooth scrolling and font */
        body { font-family: 'Inter', sans-serif; background-color: #f8f9fa; }

        /* Custom Styles for Dashboard Layout */
        .admin-sidebar {
            transition: transform 0.3s ease-in-out;
            min-width: 250px;
            /* Using min-h-screen utility class */
        }
        @media (max-width: 1024px) {
            .admin-sidebar {
                position: fixed;
                top: 0;
                left: 0; /* Always positioned at 0, use transform to hide */
                transform: translateX(-100%); /* Hidden by default on mobile */
                z-index: 50;
                height: 100%;
            }
            .admin-container.sidebar-open .admin-sidebar {
                transform: translateX(0); /* Show on mobile */
            }
            .admin-container.sidebar-open .sidebar-overlay {
                display: block;
            }
        }

        /* Sidebar Overlay for Mobile */
        .sidebar-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 40;
            display: none;
            transition: opacity 0.3s ease;
        }

        /* Toast Notification Styles */
        #toast-container {
            position: fixed;
            top: 1.5rem;
            right: 1.5rem;
            z-index: 100;
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
            max-width: 350px;
        }

        .toast {
            padding: 1rem 1.5rem;
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            color: white;
            opacity: 0;
            transform: translateX(100%);
            transition: opacity 0.3s ease-out, transform 0.3s ease-out;
        }

        .toast.show {
            opacity: 1;
            transform: translateX(0);
        }

        .toast-success { background-color: var(--success); }
        .toast-error { background-color: var(--danger); }

        /* Rating Stars */
        .rating .fas.fa-star {
            color: #ddd; /* Unfilled */
        }
        .rating .fas.fa-star.filled {
            color: #ffc107; /* Filled (Yellow/Gold) */
        }
    </style>
</head>
<body class="antialiased">

<!-- Toast Notification Container -->
<div id="toast-container"></div>

<!-- Sidebar Overlay (for closing sidebar on mobile tap outside) -->
<div id="sidebar-overlay" class="sidebar-overlay lg:hidden"></div>

<div class="admin-container flex min-h-screen">
    <!-- Sidebar -->
    <div id="admin-sidebar" class="admin-sidebar bg-gray-800 text-white shadow-xl lg:sticky lg:top-0 h-screen overflow-y-auto">
        <div class="p-6 border-b border-gray-700">
            <h2 class="text-2xl font-extrabold text-blue-400">Mutalex Academy</h2>
            <p class="text-sm font-light text-gray-400 mt-1">Instructor Panel</p>
        </div>

        <nav class="p-4">
            <ul class="space-y-2">
                <li><a href="dashboard.php" class="flex items-center p-3 rounded-lg bg-gray-700 text-blue-300 font-semibold hover:bg-gray-700 transition duration-150"><i class="fas fa-chart-line w-5 h-5 mr-3"></i>Dashboard</a></li>
                <li><a href="courses/index.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-graduation-cap w-5 h-5 mr-3"></i>My Courses</a></li>
                <li><a href="courses/new.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-plus-circle w-5 h-5 mr-3"></i>Create Course</a></li>
                <li><a href="/lms/instructor/questions/index.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-question-circle w-5 h-5 mr-3"></i>Question Bank</a></li>
                <li><a href="/lms/instructor/exams/index.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-clipboard-check w-5 h-5 mr-3"></i>Exams & Quizzes</a></li>
                <li><a href="students.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-users w-5 h-5 mr-3"></i>My Students</a></li>
                <li><a href="resources.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-book-open w-5 h-5 mr-3"></i>Resources</a></li>
                <li><a href="/lms/instructor/grading/index.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-trophy w-5 h-5 mr-3"></i>Grades</a></li>
                <li class="pt-4 border-t border-gray-700 mt-4">
                    <a href="../logout.php" class="flex items-center p-3 rounded-lg text-red-400 hover:bg-gray-700 transition duration-150">
                        <i class="fas fa-sign-out-alt w-5 h-5 mr-3"></i>Logout
                    </a>
                </li>
            </ul>
        </nav>
    </div>

    <!-- Main Content -->
    <div class="admin-content flex-1 p-4 sm:p-6 lg:p-8">
        <!-- Header (Mobile Menu Button and User Info) -->
        <div class="admin-header flex justify-between items-center pb-6 border-b border-gray-200 mb-6">
            <div class="flex items-center">
                <!-- Hamburger Menu for Mobile -->
                <button id="sidebar-toggle" class="lg:hidden p-2 mr-4 text-gray-600 hover:text-gray-900 rounded-lg focus:outline-none">
                    <i class="fas fa-bars text-xl"></i>
                </button>
                <h1 class="text-3xl font-bold text-gray-800">Welcome, <?php echo htmlspecialchars($user['username']); ?>!</h1>
            </div>

            <div class="admin-user-info flex items-center space-x-4">
                <span class="text-sm font-medium text-gray-600 hidden sm:block">Role: <span class="text-blue-600 font-semibold"><?php echo htmlspecialchars($user['role_display']); ?></span></span>
                <a href="../logout.php" class="px-4 py-2 bg-red-500 text-white rounded-lg shadow hover:bg-red-600 transition duration-150 text-sm">
                    <i class="fas fa-sign-out-alt mr-1"></i> Logout
                </a>
            </div>
        </div>

        <!-- Dashboard Statistics -->
        <div class="dashboard-stats grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <!-- Stat Card: My Courses -->
            <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-100 transform hover:shadow-xl transition duration-300">
                <div class="flex items-center justify-between">
                    <h3 class="text-lg font-semibold text-gray-600">My Courses</h3>
                    <i class="fas fa-book-open text-2xl text-blue-500"></i>
                </div>
                <div class="text-4xl font-extrabold text-gray-900 mt-2"><?php echo $courseStats['total_courses']; ?></div>
                <p class="text-sm text-gray-500 mt-1"><?php echo $courseStats['published_courses']; ?> Published, <?php echo $courseStats['draft_courses']; ?> Drafts</p>
            </div>

            <!-- Stat Card: Total Students -->
            <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-100 transform hover:shadow-xl transition duration-300">
                <div class="flex items-center justify-between">
                    <h3 class="text-lg font-semibold text-gray-600">Total Students</h3>
                    <i class="fas fa-users text-2xl text-green-500"></i>
                </div>
                <div class="text-4xl font-extrabold text-gray-900 mt-2"><?php echo $enrollmentStats['total_students']; ?></div>
                <p class="text-sm text-gray-500 mt-1"><?php echo $enrollmentStats['total_enrollments']; ?> Total Enrollments</p>
            </div>

            <!-- Stat Card: Course Completions -->
            <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-100 transform hover:shadow-xl transition duration-300">
                <div class="flex items-center justify-between">
                    <h3 class="text-lg font-semibold text-gray-600">Completions</h3>
                    <i class="fas fa-check-circle text-2xl text-purple-500"></i>
                </div>
                <div class="text-4xl font-extrabold text-gray-900 mt-2"><?php echo $enrollmentStats['completed_enrollments']; ?></div>
                <p class="text-sm text-gray-500 mt-1">Students finished courses</p>
            </div>

            <!-- Stat Card: Completion Rate -->
            <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-100 transform hover:shadow-xl transition duration-300">
                <div class="flex items-center justify-between">
                    <h3 class="text-lg font-semibold text-gray-600">Completion Rate</h3>
                    <i class="fas fa-percent text-2xl text-yellow-500"></i>
                </div>
                <div class="text-4xl font-extrabold text-gray-900 mt-2">
                    <?php
                    $completionRate = $enrollmentStats['total_enrollments'] > 0
                        ? round(($enrollmentStats['completed_enrollments'] / $enrollmentStats['total_enrollments']) * 100)
                        : 0;
                    echo $completionRate . '%';
                    ?>
                </div>
                <p class="text-sm text-gray-500 mt-1">Overall average rate</p>
            </div>
        </div>

        <!-- Dashboard Content: Performance, Enrollments, Reviews -->
        <div class="dashboard-content space-y-8">
            <!-- Course Performance Overview -->
            <?php if (!empty($courseAnalytics)): ?>
            <div class="dashboard-section bg-white p-6 rounded-xl shadow-lg">
                <h2 class="text-2xl font-bold text-gray-800 mb-4">Top 5 Course Performance</h2>
                <div class="analytics-grid grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-4">
                    <?php foreach ($courseAnalytics as $analytics): ?>
                    <!-- Placeholder Analytics Card -->
                    <div class="analytics-card border border-blue-200 p-4 rounded-lg bg-blue-50/50">
                        <h4 class="text-sm font-bold text-gray-700 truncate mb-3"><?php echo htmlspecialchars($analytics['title']); ?></h4>
                        <div class="space-y-2">
                            <div class="flex justify-between text-sm">
                                <span class="text-gray-500">Enrollments</span>
                                <span class="font-semibold text-blue-600"><?php echo $analytics['total_enrollments']; ?></span>
                            </div>
                            <div class="flex justify-between text-sm">
                                <span class="text-gray-500">Avg. Progress</span>
                                <span class="font-semibold text-green-600"><?php echo round($analytics['avg_progress'] ?? 0); ?>%</span>
                            </div>
                            <div class="flex justify-between text-sm">
                                <span class="text-gray-500">Avg. Rating</span>
                                <span class="font-semibold text-yellow-600">
                                    <?php echo round($analytics['avg_rating'] ?? 0, 1); ?> <i class="fas fa-star text-yellow-500"></i>
                                </span>
                            </div>
                        </div>
                        <div class="mt-4 text-center">
                            <a href="courses/analytics.php?id=<?php echo $analytics['id']; ?>" class="text-xs font-medium text-blue-600 hover:text-blue-800 transition">View Details &rarr;</a>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                <!-- Recent Enrollments (Two-thirds width on large screens) -->
                <?php if (!empty($recentEnrollments)): ?>
                <div class="lg:col-span-2 dashboard-section bg-white p-6 rounded-xl shadow-lg">
                    <h2 class="text-2xl font-bold text-gray-800 mb-4">Recent Student Enrollments</h2>
                    <div class="overflow-x-auto">
                        <ul class="divide-y divide-gray-100">
                            <?php foreach ($recentEnrollments as $enrollment): ?>
                            <li class="flex items-center justify-between py-3">
                                <div class="flex items-center space-x-4">
                                    <div class="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center text-green-600">
                                        <i class="fas fa-user-check"></i>
                                    </div>
                                    <div>
                                        <p class="font-medium text-gray-900"><?php echo htmlspecialchars($enrollment['first_name'] && $enrollment['last_name'] ? $enrollment['first_name'] . ' ' . $enrollment['last_name'] : $enrollment['student_name']); ?></p>
                                        <p class="text-sm text-gray-500 truncate max-w-xs"><?php echo htmlspecialchars($enrollment['course_title']); ?></p>
                                    </div>
                                </div>
                                <div class="flex flex-col items-end sm:flex-row sm:items-center space-y-1 sm:space-y-0 sm:space-x-3">
                                    <span class="text-xs font-semibold px-2.5 py-0.5 rounded-full bg-<?php echo $enrollment['status'] === 'completed' ? 'green' : 'blue'; ?>-100 text-<?php echo $enrollment['status'] === 'completed' ? 'green' : 'blue'; ?>-800">
                                        <?php echo ucfirst($enrollment['status']); ?>
                                    </span>
                                    <small class="text-xs text-gray-400"><?php echo date('M j, Y', strtotime($enrollment['enrollment_date'])); ?></small>
                                </div>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Pending Reviews (One-third width on large screens) -->
                <?php if (!empty($pendingReviews)): ?>
                <div class="lg:col-span-1 dashboard-section bg-white p-6 rounded-xl shadow-lg">
                    <div class="flex justify-between items-center mb-4">
                        <h2 class="text-2xl font-bold text-gray-800">Pending Reviews</h2>
                        <a href="reviews.php" class="text-sm font-medium text-blue-600 hover:text-blue-800 transition">Manage All &rarr;</a>
                    </div>
                    <ul class="divide-y divide-gray-100">
                        <?php foreach ($pendingReviews as $review): ?>
                        <li class="py-3">
                            <div class="flex justify-between items-start mb-1">
                                <div class="text-sm">
                                    <span class="font-semibold text-gray-900"><?php echo htmlspecialchars($review['first_name'] && $review['last_name'] ? $review['first_name'] . ' ' . $review['last_name'] : $review['student_name']); ?></span>
                                    <span class="text-gray-500"> reviewed</span>
                                    <p class="text-xs text-blue-600 mt-0.5 font-medium truncate"><?php echo htmlspecialchars($review['course_title']); ?></p>
                                </div>
                                <small class="text-xs text-gray-400"><?php echo date('M j, Y', strtotime($review['created_at'])); ?></small>
                            </div>

                            <div class="mb-2">
                                <h5 class="text-sm italic font-light text-gray-800 mt-1"><?php echo htmlspecialchars($review['review_title'] ?? 'No title'); ?></h5>
                                <div class="rating text-sm mt-1">
                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                        <i class="fas fa-star <?php echo $i <= $review['rating'] ? 'filled' : ''; ?>"></i>
                                    <?php endfor; ?>
                                </div>
                            </div>

                            <div class="flex space-x-2">
                                <button class="flex-1 px-3 py-1 text-xs font-semibold bg-green-500 text-white rounded-md hover:bg-green-600 transition" onclick="approveReview(<?php echo $review['id']; ?>)">
                                    <i class="fas fa-check-circle mr-1"></i> Approve
                                </button>
                                <button class="flex-1 px-3 py-1 text-xs font-semibold bg-red-500 text-white rounded-md hover:bg-red-600 transition" onclick="rejectReview(<?php echo $review['id']; ?>)">
                                    <i class="fas fa-times-circle mr-1"></i> Reject
                                </button>
                            </div>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <?php endif; ?>
            </div>

            <!-- My Recent Courses -->
            <div class="dashboard-section bg-white p-6 rounded-xl shadow-lg">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-2xl font-bold text-gray-800">My Recent Courses</h2>
                    <a href="courses/new.php" class="px-4 py-2 bg-blue-600 text-white rounded-lg shadow hover:bg-blue-700 transition duration-150 text-sm font-medium">
                        <i class="fas fa-plus mr-1"></i> Create New Course
                    </a>
                </div>

                <?php if (empty($recentCourses)): ?>
                <div class="text-center py-4">
                    <i class="fas fa-book fa-3x text-gray-400 mb-3"></i>
                    <h5 class="text-lg font-semibold text-gray-900">No courses yet</h5>
                    <p class="text-gray-500">Start by creating your first course!</p>
                    <a href="courses/new.php" class="inline-block mt-3 px-6 py-2 bg-blue-600 text-white rounded-lg shadow hover:bg-blue-700 transition">Create Course</a>
                </div>
                <?php else: ?>
                <div class="courses-grid grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-6">
                    <?php foreach ($recentCourses as $course): ?>
                    <div class="course-card border border-gray-200 p-5 rounded-xl shadow-md flex flex-col justify-between">
                        <div class="course-header mb-3">
                            <h4 class="text-lg font-bold text-gray-800 mb-1"><?php echo htmlspecialchars($course['title']); ?></h4>
                            <div class="course-badges">
                                <span class="text-xs font-semibold px-2 py-0.5 rounded-full bg-<?php echo $course['status'] === 'published' ? 'green' : 'yellow'; ?>-100 text-<?php echo $course['status'] === 'published' ? 'green' : 'yellow'; ?>-800">
                                    <?php echo ucfirst($course['status']); ?>
                                </span>
                            </div>
                        </div>

                        <div class="course-stats grid grid-cols-3 text-center py-4 border-y border-gray-100 my-3">
                            <div class="stat">
                                <span class="block text-2xl font-bold text-blue-600"><?php echo $course['enrollment_count']; ?></span>
                                <span class="block text-xs text-gray-500 uppercase tracking-wider">Students</span>
                            </div>
                            <div class="stat border-x border-gray-200">
                                <span class="block text-2xl font-bold text-purple-600"><?php echo $course['completion_count']; ?></span>
                                <span class="block text-xs text-gray-500 uppercase tracking-wider">Completed</span>
                            </div>
                            <div class="stat">
                                <span class="block text-2xl font-bold text-green-600"><?php echo round($course['avg_progress'] ?? 0); ?>%</span>
                                <span class="block text-xs text-gray-500 uppercase tracking-wider">Avg Progress</span>
                            </div>
                        </div>

                        <div class="course-actions flex flex-wrap gap-2 justify-center mt-3">
                            <a href="courses/edit.php?id=<?php echo $course['id']; ?>" class="px-3 py-1 text-sm font-medium border border-blue-500 text-blue-500 rounded-lg hover:bg-blue-50 transition">Edit</a>
                            <a href="../courses/detail.php?id=<?php echo $course['id']; ?>" target="_blank" class="px-3 py-1 text-sm font-medium border border-gray-500 text-gray-500 rounded-lg hover:bg-gray-50 transition">Preview</a>
                            <a href="courses/analytics.php?id=<?php echo $course['id']; ?>" class="px-3 py-1 text-sm font-medium border border-indigo-500 text-indigo-500 rounded-lg hover:bg-indigo-50 transition">Analytics</a>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <div class="text-center mt-6">
                    <a href="courses/index.php" class="inline-block px-6 py-2 text-blue-600 border border-blue-600 rounded-lg hover:bg-blue-50 transition font-medium">View All Courses</a>
                </div>
                <?php endif; ?>
            </div>

            <!-- Quick Actions -->
            <div class="dashboard-section bg-white p-6 rounded-xl shadow-lg">
                <h2 class="text-2xl font-bold text-gray-800 mb-4">Quick Actions</h2>
                <div class="quick-actions flex flex-wrap gap-4">
                    <a href="courses/new.php" class="flex items-center justify-center p-4 bg-blue-600 text-white rounded-xl shadow-md hover:bg-blue-700 transition flex-1 min-w-[150px]">
                        <i class="fas fa-plus mr-2"></i>Create Course
                    </a>
                    <a href="courses/index.php" class="flex items-center justify-center p-4 bg-gray-200 text-gray-800 rounded-xl shadow-md hover:bg-gray-300 transition flex-1 min-w-[150px]">
                        <i class="fas fa-graduation-cap mr-2"></i>Manage Courses
                    </a>
                    <a href="/lms/instructor/exams/index.php" class="flex items-center justify-center p-4 bg-gray-200 text-gray-800 rounded-xl shadow-md hover:bg-gray-300 transition flex-1 min-w-[150px]">
                        <i class="fas fa-clipboard-check mr-2"></i>Manage Exams
                    </a>
                    <a href="/lms/instructor/questions/index.php" class="flex items-center justify-center p-4 bg-gray-200 text-gray-800 rounded-xl shadow-md hover:bg-gray-300 transition flex-1 min-w-[150px]">
                        <i class="fas fa-question-circle mr-2"></i>Question Bank
                    </a>
                    <a href="analytics.php" class="flex items-center justify-center p-4 bg-gray-200 text-gray-800 rounded-xl shadow-md hover:bg-gray-300 transition flex-1 min-w-[150px]">
                        <i class="fas fa-chart-bar mr-2"></i>View Analytics
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Custom Confirmation Modal (Hidden by default) -->
<div id="confirmation-modal" class="fixed inset-0 bg-gray-900 bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white p-6 rounded-lg shadow-2xl max-w-sm w-full transform transition-all">
        <h3 class="text-xl font-bold text-gray-800 mb-4" id="modal-title">Confirm Action</h3>
        <p class="text-gray-600 mb-6" id="modal-message">Are you sure you want to perform this action?</p>
        <div class="flex justify-end space-x-3">
            <button id="modal-cancel" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 transition">Cancel</button>
            <button id="modal-confirm" class="px-4 py-2 text-white rounded-md transition"></button>
        </div>
    </div>
</div>


<script>
    // --- UI/Utility Functions ---

    // Function to show a dismissible toast notification
    function showToast(message, type = 'success') {
        const container = document.getElementById('toast-container');
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`; // Note: 'show' added below
        toast.innerHTML = `<i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} mr-2"></i>${message}`;
        container.appendChild(toast);

        // Force repaint to start transition
        setTimeout(() => toast.classList.add('show'), 10);

        // Auto-dismiss after 4 seconds
        setTimeout(() => {
            toast.classList.remove('show');
            // Remove from DOM after transition finishes
            setTimeout(() => toast.remove(), 300);
        }, 4000);
    }

    // Function to handle the custom confirmation modal (replacing window.confirm)
    function showConfirmationModal(action, reviewId) {
        const modal = document.getElementById('confirmation-modal');
        const title = document.getElementById('modal-title');
        const message = document.getElementById('modal-message');
        const confirmButton = document.getElementById('modal-confirm');
        const cancelButton = document.getElementById('modal-cancel');

        const isApprove = action === 'approve';
        const actionText = isApprove ? 'Approve' : 'Reject';

        // Placeholder function to simulate the PHP action
        const performAction = () => {
            // In a real application, this would be an AJAX call:
            // fetch('api/review_action.php', { method: 'POST', body: JSON.stringify({ action: action, review_id: reviewId }) })
            // .then(response => response.json()).then(data => { ... })
            fetch('../api/reviews.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: action,
                    review_id: reviewId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast(`Review ${actionText.toLowerCase()}d successfully.`, 'success');
                    modal.classList.add('hidden');
                    modal.classList.remove('flex');
                    // Reload or remove the review item from the UI
                    location.reload();
                } else {
                    showToast('Error: ' + data.error, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('An error occurred. Please try again.', 'error');
            });
        };

        // Set modal content
        title.textContent = `Confirm ${actionText}`;
        message.textContent = `Are you sure you want to ${actionText.toLowerCase()} this review? This action cannot be undone. (Review ID: ${reviewId})`;
        confirmButton.textContent = actionText;
        confirmButton.className = `px-4 py-2 text-white rounded-md transition ${isApprove ? 'bg-green-500 hover:bg-green-600' : 'bg-red-500 hover:bg-red-600'}`;

        // Show modal
        modal.classList.remove('hidden');
        modal.classList.add('flex');

        // Set listeners
        confirmButton.onclick = performAction;
        cancelButton.onclick = () => {
            modal.classList.add('hidden');
            modal.classList.remove('flex');
        };

        // Allow clicking the overlay to close
        document.getElementById('sidebar-overlay').onclick = () => {
            modal.classList.add('hidden');
            modal.classList.remove('flex');
        };
    }

    // --- Sidebar Toggle Logic ---
    document.getElementById('sidebar-toggle').addEventListener('click', () => {
        document.querySelector('.admin-container').classList.toggle('sidebar-open');
    });

    // Close sidebar when clicking the overlay on mobile
    document.getElementById('sidebar-overlay').addEventListener('click', () => {
        document.querySelector('.admin-container').classList.remove('sidebar-open');
    });

    // Ensure sidebar is always visible on large screens
    window.addEventListener('resize', () => {
        if (window.innerWidth >= 1024) {
            document.querySelector('.admin-container').classList.remove('sidebar-open');
        }
    });
</script>
</body>
</html>