<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../config/rbac.php';
$lms_config = require '../config/lms.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() ?: ['total_courses' => 0, 'published_courses' => 0, 'draft_courses' => 0];

// 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() ?: ['total_students' => 0, 'total_enrollments' => 0, 'completed_enrollments' => 0];

// 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 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 - ' . $lms_config['lms']['site_name'];
$active_link = '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($page_title); ?></title>
    <!-- Load Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Set up Tailwind configuration for Inter font and a professional color palette -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#1E3A8A', // Deep Indigo/Navy
                        'background-light': '#F8FAFC', // Slate 50
                        'text-dark': '#1F2937', // Gray 800
                        'accent-subtle': '#E5E7EB', // Gray 200
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </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>
        /* Ensuring full page height and scrolling */
        html, body {
            height: 100%;
        }
        /* Custom scrollbar for a cleaner look */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-thumb {
            background-color: #D1D5DB; /* Gray 300 */
            border-radius: 4px;
        }
        ::-webkit-scrollbar-track {
            background-color: transparent;
        }

        /* 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: #10b981; }
        .toast-error { background-color: #ef4444; }

        /* Rating Stars */
        .rating .fas.fa-star {
            color: #ddd; /* Unfilled */
        }
        .rating .fas.fa-star.filled {
            color: #ffc107; /* Filled (Yellow/Gold) */
        }
    </style>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen">

<!-- 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="flex">
    <?php include 'includes/sidebar.php'; ?>

    <!-- 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="Instructor Panel Logo" class="h-10 w-10">
                <div>
                    <h1 class="text-xl font-bold text-primary-blue"><?php echo htmlspecialchars($lms_config['lms']['site_name']); ?></h1>
                    <p class="text-sm text-gray-600"><?php echo htmlspecialchars($page_title); ?></p>
                </div>
            </div>

            <div class="flex items-center space-x-4">
                <span class="text-sm font-medium hidden sm:inline"><?php echo htmlspecialchars($user['username']); ?></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'] ?? 'I'), 0, 1); ?>" alt="User Avatar">
                <!-- Mobile Menu Button (Hamburger) -->
                <button class="lg:hidden p-2 rounded-lg text-text-dark hover:bg-accent-subtle ml-4" id="mobileMenuButton">
                    <span class="text-xl">☰</span>
                </button>
            </div>
        </div>
    </header>

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

        <?php include 'includes/mobile_menu.php'; ?>

        <!-- 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-accent-subtle 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-accent-subtle 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-accent-subtle 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-accent-subtle 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 border border-accent-subtle">
                <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 border border-accent-subtle">
                    <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 border border-accent-subtle">
                    <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 border border-accent-subtle">
                <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/course_builder.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 border border-accent-subtle">
                <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="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>
        </main>
    </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');
        };
    }

    // Mobile Menu Functionality
    const mobileMenuButton = document.getElementById('mobileMenuButton');
    const closeMobileMenu = document.getElementById('closeMobileMenu');
    const mobileMenu = document.getElementById('mobileMenu');

    if (mobileMenuButton && closeMobileMenu && mobileMenu) {
        mobileMenuButton.addEventListener('click', () => {
            mobileMenu.classList.remove('-translate-x-full');
        });

        closeMobileMenu.addEventListener('click', () => {
            mobileMenu.classList.add('-translate-x-full');
        });

        // Close menu when a link is clicked
        mobileMenu.querySelectorAll('a').forEach(link => {
            link.addEventListener('click', () => {
                mobileMenu.classList.add('-translate-x-full');
            });
        });
    }
</script>
</body>
</html>