<?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();

// Initialize default values for course analytics
$overallStats = [
    'total_courses' => 0,
    'total_enrollments' => 0,
    'active_students' => 0,
    'total_categories' => 0,
    'avg_rating' => 0
];

$coursePerformance = [];
$enrollmentTrends = [];
$popularCourses = [];
$categoryStats = [];
$recentEnrollments = [];

try {
    // Get overall course statistics
    $stmt = $db->prepare("
        SELECT
            COUNT(DISTINCT c.id) as total_courses,
            COUNT(DISTINCT ce.id) as total_enrollments,
            COUNT(DISTINCT CASE WHEN ce.status IN ('enrolled', 'in_progress', 'completed') THEN ce.student_id END) as active_students,
            COUNT(DISTINCT cat.id) as total_categories,
            AVG(cr.rating) as avg_rating
        FROM courses c
        LEFT JOIN course_categories cat ON c.category_id = cat.id
        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.status = 'published'
    ");
    $stmt->execute();
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($stats) {
        $overallStats = $stats;
    }

    // Get course performance data
    $stmt = $db->prepare("
        SELECT c.id, c.title, c.level, c.created_at,
                cat.name as category_name,
                COUNT(DISTINCT ce.id) as enrollments,
                AVG(cr.rating) as avg_rating,
                COUNT(DISTINCT cr.id) as review_count
        FROM courses c
        LEFT JOIN course_categories cat ON c.category_id = cat.id
        LEFT JOIN course_enrollments ce ON c.id = ce.course_id AND ce.status IN ('enrolled', 'in_progress', 'completed')
        LEFT JOIN course_reviews cr ON c.id = cr.course_id AND cr.status = 'approved'
        WHERE c.status = 'published'
        GROUP BY c.id
        ORDER BY enrollments DESC
        LIMIT 10
    ");
    $stmt->execute();
    $coursePerformance = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Get enrollment trends (last 12 months)
    $stmt = $db->prepare("
        SELECT
            DATE_FORMAT(ce.created_at, '%Y-%m') as month,
            COUNT(ce.id) as enrollments
        FROM course_enrollments ce
        JOIN courses c ON ce.course_id = c.id
        WHERE ce.created_at >= DATE_SUB(NOW(), INTERVAL 12 MONTH)
        AND c.status = 'published'
        GROUP BY DATE_FORMAT(ce.created_at, '%Y-%m')
        ORDER BY month
    ");
    $stmt->execute();
    $trends = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $enrollmentTrends = array_map(function($trend) {
        return [
            'month' => $trend['month'],
            'enrollments' => $trend['enrollments']
        ];
    }, $trends);

    // Get popular courses
    $stmt = $db->prepare("
        SELECT c.title, c.id, c.thumbnail,
                COUNT(DISTINCT ce.id) as enrollments,
                AVG(cr.rating) as avg_rating,
                COUNT(DISTINCT cr.id) as review_count
        FROM courses c
        LEFT JOIN course_enrollments ce ON c.id = ce.course_id AND ce.status IN ('enrolled', 'in_progress', 'completed')
        LEFT JOIN course_reviews cr ON c.id = cr.course_id AND cr.status = 'approved'
        WHERE c.status = 'published'
        GROUP BY c.id
        HAVING enrollments > 0
        ORDER BY enrollments DESC
        LIMIT 5
    ");
    $stmt->execute();
    $popularCourses = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Get category statistics
    $stmt = $db->prepare("
        SELECT cat.name, cat.color, cat.icon,
                COUNT(DISTINCT c.id) as course_count,
                COUNT(DISTINCT ce.id) as enrollment_count
        FROM course_categories cat
        LEFT JOIN courses c ON cat.id = c.category_id AND c.status = 'published'
        LEFT JOIN course_enrollments ce ON c.id = ce.course_id AND ce.status IN ('enrolled', 'in_progress', 'completed')
        GROUP BY cat.id
        HAVING course_count > 0
        ORDER BY enrollment_count DESC
        LIMIT 6
    ");
    $stmt->execute();
    $categoryStats = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Get recent enrollments
    $stmt = $db->prepare("
        SELECT ce.created_at, 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.status = 'published'
        ORDER BY ce.created_at DESC
        LIMIT 8
    ");
    $stmt->execute();
    $enrollments = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $recentEnrollments = array_map(function($enrollment) {
        return [
            'created_at' => $enrollment['created_at'],
            'course_title' => $enrollment['course_title'],
            'student_name' => $enrollment['first_name'] && $enrollment['last_name'] ?
                            $enrollment['first_name'] . ' ' . $enrollment['last_name'] :
                            $enrollment['student_name']
        ];
    }, $enrollments);

} catch (Exception $e) {
    error_log("Course analytics database error: " . $e->getMessage());
}

$page_title = 'Course Analytics - ' . $lms_config['lms']['site_name'];
$active_link = 'courses';
?>
<!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">
    <!-- Chart.js for visualizations -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <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) */
        }

        /* Professional Course Analytics Dashboard Styles */

        /* Hero Section */
        .analytics-hero {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 4rem 0 3rem;
            position: relative;
            overflow: hidden;
        }

        .analytics-hero::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="75" cy="75" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="50" cy="10" r="0.5" fill="rgba(255,255,255,0.1)"/><circle cx="90" cy="40" r="0.5" fill="rgba(255,255,255,0.1)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
            opacity: 0.1;
        }

        .hero-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 2rem;
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 3rem;
            align-items: center;
        }

        .hero-text h1 {
            font-size: 3rem;
            font-weight: 800;
            margin-bottom: 1rem;
            line-height: 1.1;
        }

        .hero-subtitle {
            font-size: 1.25rem;
            opacity: 0.9;
            margin-bottom: 2rem;
            line-height: 1.6;
        }

        .hero-meta {
            display: flex;
            gap: 2rem;
            font-size: 0.9rem;
        }

        .hero-meta .meta-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            opacity: 0.8;
        }

        .hero-visual {
            display: flex;
            justify-content: center;
        }

        .hero-chart-placeholder {
            width: 200px;
            height: 150px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 12px;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 1rem;
        }

        .hero-chart-placeholder i {
            font-size: 2rem;
            margin-bottom: 1rem;
            opacity: 0.8;
        }

        .chart-bars {
            display: flex;
            align-items: end;
            gap: 0.5rem;
            height: 60px;
        }

        .chart-bars .bar {
            width: 20px;
            background: rgba(255, 255, 255, 0.8);
            border-radius: 2px 2px 0 0;
        }

        /* Metrics Section */
        .metrics-section {
            padding: 4rem 0;
            background: #f8fafc;
        }

        .section-header {
            text-align: center;
            margin-bottom: 3rem;
        }

        .section-header h2 {
            font-size: 2.25rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }

        .section-header p {
            font-size: 1.1rem;
            color: #64748b;
            max-width: 600px;
            margin: 0 auto;
        }

        .metrics-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 2rem;
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 2rem;
        }

        .metric-card {
            background: white;
            border-radius: 16px;
            padding: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            border: 1px solid #e2e8f0;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .metric-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #667eea, #764ba2);
        }

        .metric-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }

        .metric-card.primary::before { background: linear-gradient(90deg, #667eea, #764ba2); }
        .metric-card.success::before { background: linear-gradient(90deg, #10b981, #059669); }
        .metric-card.warning::before { background: linear-gradient(90deg, #f59e0b, #d97706); }
        .metric-card.info::before { background: linear-gradient(90deg, #3b82f6, #2563eb); }

        .metric-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 1.5rem;
        }

        .metric-icon {
            width: 56px;
            height: 56px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            color: white;
        }

        .metric-card.primary .metric-icon { background: linear-gradient(135deg, #667eea, #764ba2); }
        .metric-card.success .metric-icon { background: linear-gradient(135deg, #10b981, #059669); }
        .metric-card.warning .metric-icon { background: linear-gradient(135deg, #f59e0b, #d97706); }
        .metric-card.info .metric-icon { background: linear-gradient(135deg, #3b82f6, #2563eb); }

        .metric-badge {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 0.25rem;
        }

        .metric-content {
            flex: 1;
        }

        .metric-value {
            font-size: 2.5rem;
            font-weight: 800;
            color: #1e293b;
            margin-bottom: 0.5rem;
            line-height: 1;
        }

        .metric-label {
            font-size: 1rem;
            font-weight: 600;
            color: #475569;
            margin-bottom: 0.25rem;
        }

        .metric-description {
            font-size: 0.875rem;
            color: #64748b;
        }

        /* Charts Section */
        .charts-section {
            padding: 4rem 0;
            background: white;
        }

        .charts-grid {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 2rem;
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 2rem;
        }

        .chart-card, .insights-card {
            background: white;
            border-radius: 16px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            border: 1px solid #e2e8f0;
            overflow: hidden;
        }

        .card-header {
            padding: 1.5rem 2rem;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .card-title {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            font-size: 1.25rem;
            font-weight: 600;
            color: #1e293b;
        }

        .card-title i {
            color: #667eea;
            font-size: 1.5rem;
        }

        .card-controls {
            display: flex;
            gap: 0.5rem;
        }

        .metric-selector {
            padding: 0.5rem 1rem;
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            background: white;
            font-size: 0.875rem;
            color: #475569;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .metric-selector:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .card-body {
            padding: 2rem;
        }

        .chart-container {
            position: relative;
            height: 300px;
        }

        .popular-courses-list {
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }

        .course-ranking-item {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 1rem;
            background: #f8fafc;
            border-radius: 8px;
            transition: all 0.3s ease;
        }

        .course-ranking-item:hover {
            background: #f1f5f9;
            transform: translateX(4px);
        }

        .ranking-badge {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 1rem;
            flex-shrink: 0;
        }

        .course-details {
            flex: 1;
        }

        .course-details h4 {
            font-size: 1rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }

        .course-metrics {
            display: flex;
            gap: 1rem;
            font-size: 0.8rem;
        }

        .course-metrics .metric {
            display: flex;
            align-items: center;
            gap: 0.25rem;
            color: #64748b;
        }

        .empty-state {
            text-align: center;
            padding: 3rem 2rem;
        }

        .empty-icon {
            font-size: 3rem;
            color: #cbd5e1;
            margin-bottom: 1rem;
        }

        .empty-state h4 {
            font-size: 1.25rem;
            font-weight: 600;
            color: #475569;
            margin-bottom: 0.5rem;
        }

        .empty-state p {
            color: #64748b;
            max-width: 300px;
            margin: 0 auto;
        }

        /* Category Section */
        .category-section {
            padding: 4rem 0;
            background: #f8fafc;
        }

        .category-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
            gap: 2rem;
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 2rem;
        }

        .category-card {
            background: white;
            border-radius: 16px;
            padding: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            border: 1px solid #e2e8f0;
            transition: all 0.3s ease;
        }

        .category-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
        }

        .category-header {
            display: flex;
            align-items: center;
            gap: 1rem;
            margin-bottom: 1.5rem;
        }

        .category-icon {
            width: 60px;
            height: 60px;
            border-radius: 12px;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            flex-shrink: 0;
        }

        .category-info h3 {
            font-size: 1.25rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }

        .category-stats {
            display: flex;
            gap: 1rem;
            font-size: 0.875rem;
            color: #64748b;
        }

        .category-stats .stat {
            background: #f1f5f9;
            padding: 0.25rem 0.75rem;
            border-radius: 12px;
        }

        .category-progress {
            margin-top: 1rem;
        }

        .category-progress .progress-bar {
            height: 8px;
            background: #e2e8f0;
            border-radius: 4px;
            overflow: hidden;
        }

        .category-progress .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea, #764ba2);
            border-radius: 4px;
            transition: width 0.3s ease;
        }

        /* Activity Section */
        .activity-section {
            padding: 4rem 0;
            background: white;
        }

        .activity-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 1.5rem;
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 2rem;
        }

        .activity-card {
            display: flex;
            align-items: flex-start;
            gap: 1rem;
            padding: 1.5rem;
            background: #f8fafc;
            border-radius: 12px;
            border: 1px solid #e5e7eb;
            transition: all 0.3s ease;
        }

        .activity-card:hover {
            background: white;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            transform: translateX(4px);
        }

        .activity-icon {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1rem;
            flex-shrink: 0;
        }

        .activity-content {
            flex: 1;
        }

        .activity-text {
            font-size: 0.9rem;
            color: #374151;
            line-height: 1.5;
            margin-bottom: 0.5rem;
        }

        .activity-time {
            font-size: 0.8rem;
            color: #6b7280;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        /* Analytics Table Section */
        .analytics-table-section {
            padding: 4rem 0;
            background: #f8fafc;
        }

        .analytics-table-card {
            background: white;
            border-radius: 16px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            border: 1px solid #e2e8f0;
            overflow: hidden;
            max-width: 1200px;
            margin: 0 auto;
        }

        .table-container {
            overflow-x: auto;
        }

        .analytics-table {
            width: 100%;
            border-collapse: collapse;
        }

        .analytics-table thead th {
            background: #f8fafc;
            padding: 1rem 1.5rem;
            text-align: left;
            font-weight: 600;
            color: #475569;
            font-size: 0.875rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            border-bottom: 2px solid #e2e8f0;
        }

        .analytics-table tbody td {
            padding: 1.5rem;
            border-bottom: 1px solid #e5e7eb;
        }

        .analytics-table tbody tr:hover {
            background: #f8fafc;
        }

        .course-cell .course-title {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }

        .course-cell .course-meta {
            font-size: 0.8rem;
            color: #64748b;
        }

        .category-cell .category-tag {
            background: #e0f2fe;
            color: #0369a1;
            padding: 0.25rem 0.75rem;
            border-radius: 15px;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .level-cell .level-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }

        .level-cell .level-badge.beginner {
            background: #d1fae5;
            color: #065f46;
        }

        .level-cell .level-badge.intermediate {
            background: #fef3c7;
            color: #d97706;
        }

        .level-cell .level-badge.advanced {
            background: #fee2e2;
            color: #dc2626;
        }

        .metric-cell .metric-value {
            font-size: 1.25rem;
            font-weight: 700;
            color: #1e293b;
        }

        .metric-cell .metric-label {
            font-size: 0.8rem;
            color: #64748b;
        }

        .rating-cell .rating-display {
            display: flex;
            flex-direction: column;
            gap: 0.25rem;
        }

        .rating-cell .rating-number {
            font-size: 0.875rem;
            font-weight: 600;
            color: #1e293b;
        }

        .rating-cell .rating-stars {
            display: flex;
            gap: 0.125rem;
        }

        .rating-cell .rating-stars .fa-star {
            color: #e2e8f0;
            font-size: 0.75rem;
        }

        .rating-cell .rating-stars .fa-star.filled {
            color: #f59e0b;
        }

        .rating-cell .no-rating {
            font-size: 0.875rem;
            color: #64748b;
        }

        .date-cell {
            font-size: 0.875rem;
            color: #64748b;
        }

        /* Buttons */
        .btn {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            text-decoration: none;
            transition: all 0.3s ease;
            cursor: pointer;
            border: none;
            font-size: 0.9rem;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
        }

        /* Responsive Design */
        @media (max-width: 1024px) {
            .charts-grid {
                grid-template-columns: 1fr;
            }

            .category-grid {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 768px) {
            .hero-content {
                grid-template-columns: 1fr;
                text-align: center;
                gap: 2rem;
            }

            .hero-text h1 {
                font-size: 2.5rem;
            }

            .hero-meta {
                justify-content: center;
                flex-wrap: wrap;
                gap: 1rem;
            }

            .metrics-grid {
                grid-template-columns: 1fr;
            }

            .activity-grid {
                grid-template-columns: 1fr;
            }

            .analytics-table {
                font-size: 0.875rem;
            }

            .analytics-table thead th,
            .analytics-table tbody td {
                padding: 0.75rem;
            }

            .activity-card {
                padding: 1rem;
            }

            .category-card {
                padding: 1.5rem;
            }
        }
    </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'; ?>

        <!-- Course Analytics Hero Section -->
        <section class="analytics-hero">
            <div class="container">
                <div class="hero-content">
                    <div class="hero-text">
                        <h1 class="hero-title">Course Analytics</h1>
                        <p class="hero-subtitle">Explore course performance, enrollment trends, and learning insights</p>
                        <div class="hero-meta">
                            <div class="meta-item">
                                <i class="fas fa-clock"></i>
                                <span>Last updated: <?php echo date('M j, Y \a\t g:i A'); ?></span>
                            </div>
                            <div class="meta-item">
                                <i class="fas fa-calendar"></i>
                                <span>Data from last 12 months</span>
                            </div>
                        </div>
                    </div>
                    <div class="hero-visual">
                        <div class="hero-chart-placeholder">
                            <i class="fas fa-chart-line"></i>
                            <div class="chart-bars">
                                <div class="bar" style="height: 60%"></div>
                                <div class="bar" style="height: 80%"></div>
                                <div class="bar" style="height: 40%"></div>
                                <div class="bar" style="height: 90%"></div>
                                <div class="bar" style="height: 70%"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- Key Metrics Section -->
        <section class="metrics-section">
            <div class="container">
                <div class="section-header">
                    <h2>Course Overview</h2>
                    <p>Key metrics and performance indicators for our course catalog</p>
                </div>

                <div class="metrics-grid">
                    <div class="metric-card primary">
                        <div class="metric-header">
                            <div class="metric-icon">
                                <i class="fas fa-graduation-cap"></i>
                            </div>
                            <div class="metric-badge">
                                <i class="fas fa-arrow-up"></i>
                                Active
                            </div>
                        </div>
                        <div class="metric-content">
                            <div class="metric-value"><?php echo number_format($overallStats['total_courses'] ?? 0); ?></div>
                            <div class="metric-label">Total Courses</div>
                            <div class="metric-description">Published courses available</div>
                        </div>
                    </div>

                    <div class="metric-card success">
                        <div class="metric-header">
                            <div class="metric-icon">
                                <i class="fas fa-users"></i>
                            </div>
                            <div class="metric-badge">
                                <i class="fas fa-user-check"></i>
                                <?php echo number_format($overallStats['active_students'] ?? 0); ?>
                            </div>
                        </div>
                        <div class="metric-content">
                            <div class="metric-value"><?php echo number_format($overallStats['total_enrollments'] ?? 0); ?></div>
                            <div class="metric-label">Total Enrollments</div>
                            <div class="metric-description">Students enrolled in courses</div>
                        </div>
                    </div>

                    <div class="metric-card warning">
                        <div class="metric-header">
                            <div class="metric-icon">
                                <i class="fas fa-tags"></i>
                            </div>
                            <div class="metric-badge">
                                <i class="fas fa-layer-group"></i>
                                Categories
                            </div>
                        </div>
                        <div class="metric-content">
                            <div class="metric-value"><?php echo number_format($overallStats['total_categories'] ?? 0); ?></div>
                            <div class="metric-label">Course Categories</div>
                            <div class="metric-description">Organized course topics</div>
                        </div>
                    </div>

                    <div class="metric-card info">
                        <div class="metric-header">
                            <div class="metric-icon">
                                <i class="fas fa-star"></i>
                            </div>
                            <div class="metric-badge">
                                <i class="fas fa-star-half-alt"></i>
                                <?php echo number_format($overallStats['avg_rating'] ?? 0, 1); ?>
                            </div>
                        </div>
                        <div class="metric-content">
                            <div class="metric-value"><?php echo number_format($overallStats['avg_rating'] ?? 0, 1); ?>/5</div>
                            <div class="metric-label">Average Rating</div>
                            <div class="metric-description">Overall course satisfaction</div>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- Charts and Insights Section -->
        <section class="charts-section">
            <div class="container">
                <div class="charts-grid">

                    <!-- Enrollment Trends Chart -->
                    <div class="chart-card">
                        <div class="card-header">
                            <div class="card-title">
                                <i class="fas fa-chart-line"></i>
                                <h3>Enrollment Trends</h3>
                            </div>
                            <div class="card-controls">
                                <select class="metric-selector" id="trendMetric">
                                    <option value="enrollments">Enrollments</option>
                                    <option value="courses">New Courses</option>
                                </select>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="chart-container">
                                <canvas id="enrollmentChart" height="300"></canvas>
                            </div>
                        </div>
                    </div>

                    <!-- Popular Courses -->
                    <div class="insights-card">
                        <div class="card-header">
                            <div class="card-title">
                                <i class="fas fa-trophy"></i>
                                <h3>Most Popular Courses</h3>
                            </div>
                        </div>
                        <div class="card-body">
                            <?php if (!empty($popularCourses)): ?>
                                <div class="popular-courses-list">
                                    <?php foreach ($popularCourses as $index => $course): ?>
                                        <div class="course-ranking-item">
                                            <div class="ranking-badge">
                                                <span class="rank-number"><?php echo $index + 1; ?></span>
                                            </div>
                                            <div class="course-details">
                                                <h4><?php echo htmlspecialchars($course['title']); ?></h4>
                                                <div class="course-metrics">
                                                    <div class="metric">
                                                        <i class="fas fa-users"></i>
                                                        <span><?php echo number_format($course['enrollments']); ?> students</span>
                                                    </div>
                                                    <?php if ($course['avg_rating']): ?>
                                                        <div class="metric">
                                                            <i class="fas fa-star"></i>
                                                            <span><?php echo number_format($course['avg_rating'], 1); ?> rating</span>
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php else: ?>
                                <div class="empty-state">
                                    <div class="empty-icon">
                                        <i class="fas fa-graduation-cap"></i>
                                    </div>
                                    <h4>No Course Data</h4>
                                    <p>No enrollment data available yet.</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                </div>
            </div>
        </section>

        <!-- Category Performance Section -->
        <section class="category-section">
            <div class="container">
                <div class="section-header">
                    <h2>Category Performance</h2>
                    <p>Course distribution and enrollment by category</p>
                </div>

                <div class="category-grid">
                    <?php if (!empty($categoryStats)): ?>
                        <?php foreach ($categoryStats as $category): ?>
                            <div class="category-card">
                                <div class="category-header">
                                    <div class="category-icon" style="background: linear-gradient(135deg, <?php echo htmlspecialchars($category['color'] ?? '#667eea'); ?>, <?php echo htmlspecialchars($category['color'] ?? '#764ba2'); ?>);">
                                        <i class="<?php echo htmlspecialchars($category['icon'] ?? 'fas fa-graduation-cap'); ?>"></i>
                                    </div>
                                    <div class="category-info">
                                        <h3><?php echo htmlspecialchars($category['name']); ?></h3>
                                        <div class="category-stats">
                                            <span class="stat"><?php echo $category['course_count']; ?> courses</span>
                                            <span class="stat"><?php echo number_format($category['enrollment_count']); ?> enrollments</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="category-progress">
                                    <div class="progress-bar">
                                        <div class="progress-fill" style="width: <?php echo $category['course_count'] > 0 ? min(100, ($category['enrollment_count'] / $category['course_count']) * 10) : 0; ?>%"></div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="empty-state">
                            <div class="empty-icon">
                                <i class="fas fa-tags"></i>
                            </div>
                            <h4>No Category Data</h4>
                            <p>Category performance data will appear here.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </section>

        <!-- Recent Activity Section -->
        <?php if (!empty($recentEnrollments)): ?>
        <section class="activity-section">
            <div class="container">
                <div class="section-header">
                    <h2>Recent Enrollments</h2>
                    <p>Latest student course enrollments</p>
                </div>

                <div class="activity-grid">
                    <?php foreach ($recentEnrollments as $enrollment): ?>
                        <div class="activity-card">
                            <div class="activity-icon">
                                <i class="fas fa-user-plus"></i>
                            </div>
                            <div class="activity-content">
                                <div class="activity-text">
                                    <strong><?php echo htmlspecialchars($enrollment['student_name']); ?></strong>
                                    enrolled in <strong><?php echo htmlspecialchars($enrollment['course_title']); ?></strong>
                                </div>
                                <div class="activity-time">
                                    <i class="fas fa-clock"></i>
                                    <?php echo date('M j, Y \a\t g:i A', strtotime($enrollment['created_at'])); ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </section>
        <?php endif; ?>

        <!-- Detailed Course Table Section -->
        <section class="analytics-table-section">
            <div class="container">
                <div class="section-header">
                    <h2>Course Performance Details</h2>
                    <p>Comprehensive analytics for all published courses</p>
                    <button class="btn btn-primary" onclick="exportCourseAnalytics()">
                        <i class="fas fa-download"></i>
                        Export Data
                    </button>
                </div>

                <div class="analytics-table-card">
                    <div class="table-container">
                        <table class="analytics-table">
                            <thead>
                                <tr>
                                    <th>Course</th>
                                    <th>Category</th>
                                    <th>Level</th>
                                    <th>Enrollments</th>
                                    <th>Rating</th>
                                    <th>Reviews</th>
                                    <th>Created</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($coursePerformance as $course): ?>
                                    <tr>
                                        <td>
                                            <div class="course-cell">
                                                <div class="course-title"><?php echo htmlspecialchars($course['title']); ?></div>
                                                <div class="course-meta">ID: <?php echo $course['id']; ?></div>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="category-cell">
                                                <span class="category-tag"><?php echo htmlspecialchars($course['category_name'] ?? 'Uncategorized'); ?></span>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="level-cell">
                                                <span class="level-badge <?php echo strtolower($course['level']); ?>">
                                                    <?php echo ucfirst($course['level']); ?>
                                                </span>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="metric-cell">
                                                <div class="metric-value"><?php echo number_format($course['enrollments']); ?></div>
                                                <div class="metric-label">students</div>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="rating-cell">
                                                <?php if ($course['avg_rating']): ?>
                                                    <div class="rating-display">
                                                        <span class="rating-number"><?php echo number_format($course['avg_rating'], 1); ?>/5</span>
                                                        <div class="rating-stars">
                                                            <?php for ($i = 1; $i <= 5; $i++): ?>
                                                                <i class="fas fa-star <?php echo $i <= round($course['avg_rating']) ? 'filled' : ''; ?>"></i>
                                                            <?php endfor; ?>
                                                        </div>
                                                    </div>
                                                <?php else: ?>
                                                    <span class="no-rating">No ratings</span>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="metric-cell">
                                                <div class="metric-value"><?php echo number_format($course['review_count']); ?></div>
                                                <div class="metric-label">reviews</div>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="date-cell">
                                                <span><?php echo date('M j, Y', strtotime($course['created_at'])); ?></span>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </section>
    </main>
</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');
            });
        });
    }

    // Course Analytics Data
    const enrollmentTrends = <?php echo json_encode($enrollmentTrends); ?>;
    const coursePerformance = <?php echo json_encode($coursePerformance); ?>;

    document.addEventListener('DOMContentLoaded', function() {
        initializeCharts();
    });

    function initializeCharts() {
        // Enrollment Trends Chart
        const ctx = document.getElementById('enrollmentChart').getContext('2d');
        const enrollmentChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: enrollmentTrends.map(trend => {
                    const date = new Date(trend.month + '-01');
                    return date.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
                }),
                datasets: [{
                    label: 'Enrollments',
                    data: enrollmentTrends.map(trend => trend.enrollments),
                    borderColor: 'rgba(75, 192, 192, 1)',
                    backgroundColor: 'rgba(75, 192, 192, 0.2)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    }
                }
            }
        });

        // Update chart when metric changes
        document.getElementById('trendMetric').addEventListener('change', function() {
            const metric = this.value;
            let data, label;

            switch(metric) {
                case 'enrollments':
                    data = enrollmentTrends.map(trend => trend.enrollments);
                    label = 'Enrollments';
                    break;
                case 'courses':
                    // Mock new courses data
                    data = enrollmentTrends.map(() => Math.floor(Math.random() * 5) + 1);
                    label = 'New Courses';
                    break;
            }

            enrollmentChart.data.datasets[0].data = data;
            enrollmentChart.data.datasets[0].label = label;
            enrollmentChart.update();
        });
    }

    function exportCourseAnalytics() {
        const data = <?php echo json_encode($coursePerformance); ?>;
        let csv = 'Course Title,Category,Level,Enrollments,Average Rating,Review Count,Created Date\n';

        data.forEach(course => {
            csv += `"${course.title}","${course.category_name || 'Uncategorized'}","${course.level}","${course.enrollments}","${course.avg_rating || ''}","${course.review_count}","${course.created_at}"\n`;
        });

        const blob = new Blob([csv], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'course-analytics.csv';
        a.click();
        window.URL.revokeObjectURL(url);
    }
</script>
</body>
</html>