<?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();
$userId = $_SESSION['user_id'];

// Initialize instructor course analytics values
$instructorId = $_SESSION['user_id'];

$overallStats = [
    'total_courses' => 0,
    'published_courses' => 0,
    'draft_courses' => 0,
    'recent_enrollments_30d' => 0,
    'total_students' => 0,
];

$coursePerformance = []; // used by the detailed table
$enrollmentTrends = []; // 12 months trends
$topCourses = []; // top courses list
$engagementMetrics = [
    'avg_progress' => 0,
    'completion_rate' => 0,
    'avg_completion_days' => null,
    'active_last_week' => 0
];
$recentReviews = [];

try {
    // 1) Course stats (instructor scope)
    $stmt = $db->prepare("\n        SELECT\n            COUNT(*) AS total_courses,\n            COUNT(CASE WHEN status = 'published' THEN 1 END) AS published_courses,\n            COUNT(CASE WHEN status = 'draft' THEN 1 END) AS draft_courses\n        FROM courses\n        WHERE instructor_id = ?\n    ");
    $stmt->execute([$instructorId]);
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($stats) {
        $overallStats['total_courses'] = (int)($stats['total_courses'] ?? 0);
        $overallStats['published_courses'] = (int)($stats['published_courses'] ?? 0);
        $overallStats['draft_courses'] = (int)($stats['draft_courses'] ?? 0);
    }

    // 2) Total students (distinct) across instructor courses
    $stmt = $db->prepare("\n        SELECT COUNT(DISTINCT ce.student_id) AS total_students\n        FROM course_enrollments ce\n        INNER JOIN courses c ON c.id = ce.course_id\n        WHERE c.instructor_id = ?\n    ");
    $stmt->execute([$instructorId]);
    $overallStats['total_students'] = (int)($stmt->fetchColumn() ?? 0);

    // 3) Recent enrollments (last 30 days)
    $stmt = $db->prepare("\n        SELECT COUNT(*)\n        FROM course_enrollments ce\n        INNER JOIN courses c ON c.id = ce.course_id\n        WHERE c.instructor_id = ?\n          AND ce.enrollment_date >= DATE_SUB(NOW(), INTERVAL 30 DAY)\n    ");
    $stmt->execute([$instructorId]);
    $overallStats['recent_enrollments_30d'] = (int)($stmt->fetchColumn() ?? 0);

    // 4) Engagement metrics derived from enrollments
    $stmt = $db->prepare("\n        SELECT\n            COALESCE(AVG(ce.progress_percentage), 0) AS avg_progress,\n            COALESCE(\n                (SUM(CASE WHEN ce.status = 'completed' THEN 1 ELSE 0 END) * 100.0) / NULLIF(COUNT(*), 0)\n            , 0) AS completion_rate\n        FROM course_enrollments ce\n        INNER JOIN courses c ON c.id = ce.course_id\n        WHERE c.instructor_id = ?\n    ");
    $stmt->execute([$instructorId]);
    $m = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($m) {
        $engagementMetrics['avg_progress'] = (float)($m['avg_progress'] ?? 0);
        $engagementMetrics['completion_rate'] = (float)($m['completion_rate'] ?? 0);
    }

    // Avg completion days (best-effort). Uses completion_date if it exists.
    try {
        $stmt = $db->prepare("\n            SELECT\n                COALESCE(AVG(DATEDIFF(ce.completion_date, ce.enrollment_date)), NULL) AS avg_completion_days\n            FROM course_enrollments ce\n            INNER JOIN courses c ON c.id = ce.course_id\n            WHERE c.instructor_id = ?\n              AND ce.status = 'completed'\n              AND ce.completion_date IS NOT NULL\n        ");
        $stmt->execute([$instructorId]);
        $avgDays = $stmt->fetchColumn();
        $engagementMetrics['avg_completion_days'] = ($avgDays === null) ? null : (float)$avgDays;
    } catch (Exception $ignored) {
        $engagementMetrics['avg_completion_days'] = null;
    }

    // Active this week: distinct students enrolled in last 7 days (best-effort)
    $stmt = $db->prepare("\n        SELECT COUNT(DISTINCT ce.student_id)\n        FROM course_enrollments ce\n        INNER JOIN courses c ON c.id = ce.course_id\n        WHERE c.instructor_id = ?\n          AND ce.enrollment_date >= DATE_SUB(NOW(), INTERVAL 7 DAY)\n    ");
    $stmt->execute([$instructorId]);
    $engagementMetrics['active_last_week'] = (int)($stmt->fetchColumn() ?? 0);

    // 5) Top courses (published only) by enrollments
    $stmt = $db->prepare("\n        SELECT\n            c.id,\n            c.title AS title,\n            COUNT(ce.id) AS enrollments,\n            COUNT(CASE WHEN ce.status = 'completed' THEN 1 END) AS completions,\n            COALESCE(AVG(ce.progress_percentage), 0) AS avg_progress,\n            COALESCE(AVG(cr.rating), 0) AS avg_rating\n        FROM courses c\n        LEFT JOIN course_enrollments ce ON ce.course_id = c.id\n        LEFT JOIN course_reviews cr ON cr.course_id = c.id AND cr.status = 'approved'\n        WHERE c.instructor_id = ?\n          AND c.status = 'published'\n        GROUP BY c.id, c.title\n        HAVING enrollments > 0\n        ORDER BY enrollments DESC\n        LIMIT 5\n    ");
    $stmt->execute([$instructorId]);
    $topCourses = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 6) Enrollment trends (last 12 months)
    $stmt = $db->prepare("\n        SELECT\n            DATE_FORMAT(ce.enrollment_date, '%Y-%m') AS month,\n            COUNT(*) AS enrollments\n        FROM course_enrollments ce\n        INNER JOIN courses c ON c.id = ce.course_id\n        WHERE c.instructor_id = ?\n          AND ce.enrollment_date >= DATE_SUB(NOW(), INTERVAL 12 MONTH)\n        GROUP BY DATE_FORMAT(ce.enrollment_date, '%Y-%m')\n        ORDER BY month ASC\n    ");
    $stmt->execute([$instructorId]);
    $trends = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $trendMap = [];
    foreach ($trends as $t) {
        $trendMap[$t['month']] = (int)($t['enrollments'] ?? 0);
    }

    $enrollmentTrends = [];
    for ($i = 11; $i >= 0; $i--) {
        $monthKey = date('Y-m', strtotime("-$i months"));
        $monthLabel = date('M', strtotime("-$i months"));
        $enrollmentTrends[] = [
            'month' => $monthLabel,
            'enrollments' => $trendMap[$monthKey] ?? 0
        ];
    }

    // 7) Recent course reviews (approved) with real ratings
    $stmt = $db->prepare("\n        SELECT\n            cr.id,\n            cr.rating,\n            cr.review_title,\n            cr.review_text,\n            cr.created_at,\n            c.title AS course_title,\n            COALESCE(CONCAT(up.first_name, ' ', up.last_name), u.username) AS student_name,\n            cr.status\n        FROM course_reviews cr\n        INNER JOIN courses c ON c.id = cr.course_id\n        INNER JOIN users u ON u.id = cr.student_id\n        LEFT JOIN user_profiles up ON up.user_id = u.id\n        WHERE c.instructor_id = ?\n          AND cr.status = 'approved'\n        ORDER BY cr.created_at DESC\n        LIMIT 5\n    ");
    $stmt->execute([$instructorId]);
    $recentReviews = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 8) Detailed table rows (recent courses)
    $stmt = $db->prepare("\n        SELECT\n            c.id,\n            c.title,\n            c.status,\n            c.created_at,\n            COUNT(ce.id) AS enrollments,\n            COUNT(CASE WHEN ce.status = 'completed' THEN 1 END) AS completions,\n            COALESCE(AVG(ce.progress_percentage), 0) AS avg_progress,\n            COALESCE(AVG(cr.rating), 0) AS avg_rating\n        FROM courses c\n        LEFT JOIN course_enrollments ce ON ce.course_id = c.id\n        LEFT JOIN course_reviews cr ON cr.course_id = c.id AND cr.status = 'approved'\n        WHERE c.instructor_id = ?\n          AND c.status IN ('published','draft')\n        GROUP BY c.id, c.title, c.status, c.created_at\n        ORDER BY c.created_at DESC\n        LIMIT 10\n    ");
    $stmt->execute([$instructorId]);
    $coursePerformance = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    error_log("Instructor analytics database error: " . $e->getMessage());
}

$page_title = 'Analytics Dashboard - ' . $lms_config['lms']['site_name'];
$active_link = 'analytics';
?>

<!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>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#1E3A8A',
                        'background-light': '#F8FAFC',
                        'text-dark': '#1F2937',
                        'accent-subtle': '#E5E7EB'
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        html, body { height: 100%; }
        ::-webkit-scrollbar { width: 8px; height: 8px; }
        ::-webkit-scrollbar-thumb { background-color: #D1D5DB; border-radius: 4px; }
        ::-webkit-scrollbar-track { background-color: transparent; }

        .admin-sidebar { transition: transform 0.3s ease-in-out; min-width: 250px; }
        @media (max-width: 1024px) {
            .admin-sidebar {
                position: fixed;
                top: 0;
                left: 0;
                transform: translateX(-100%);
                z-index: 50;
                height: 100%;
            }
            .admin-container.sidebar-open .admin-sidebar { transform: translateX(0); }
            .admin-container.sidebar-open .sidebar-overlay { display: block; }
        }

        .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-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 .fas.fa-star { color: #ddd; }
        .rating .fas.fa-star.filled { color: #ffc107; }

        /* Use existing large CSS from previous version for layout/visuals */
        .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 { 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 { 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; }

        .top-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; }

        .trends-section { padding: 4rem 0; background: #f8fafc; }
        .trends-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 2rem; max-width: 1200px; margin: 0 auto; padding: 0 2rem; }
        .trend-card, .engagement-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-subtitle { font-size: 0.875rem; color: #64748b; margin-top: 0.25rem; }
        .engagement-metrics { display: flex; flex-direction: column; gap: 1.5rem; }
        .metric-item { display: flex; justify-content: space-between; align-items: center; padding: 1rem; background: #f8fafc; border-radius: 8px; }
        .metric-info { flex: 1; }
        .metric-label { font-size: 0.875rem; color: #64748b; margin-bottom: 0.25rem; }
        .metric-value { font-size: 1.25rem; font-weight: 700; color: #1e293b; }
        .metric-progress { flex: 1; max-width: 120px; margin-left: 1rem; }
        .metric-progress .progress-bar { height: 6px; background: #e2e8f0; border-radius: 3px; overflow: hidden; }
        .metric-progress .progress-fill { height: 100%; background: linear-gradient(90deg, #10b981, #059669); border-radius: 3px; transition: width 0.3s ease; }
        .metric-visual { color: #667eea; font-size: 1.25rem; }

        .reviews-section { padding: 4rem 0; background: white; }
        .reviews-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 1fr)); gap: 2rem; max-width: 1200px; margin: 0 auto; padding: 0 2rem; }
        .review-card { background: white; border-radius: 12px; padding: 1.5rem; 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; }
        .review-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); }
        .review-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 1rem; }
        .reviewer-avatar { width: 40px; height: 40px; border-radius: 50%; background: linear-gradient(135deg, #667eea, #764ba2); color: white; display: flex; align-items: center; justify-content: center; font-size: 1rem; flex-shrink: 0; margin-right: 1rem; }
        .reviewer-info h4 { font-size: 1rem; font-weight: 600; color: #1e293b; margin-bottom: 0.25rem; }
        .course-name { font-size: 0.875rem; color: #64748b; }
        .review-rating { display: flex; align-items: center; gap: 0.5rem; }
        .review-rating .fas.fa-star { color: #e2e8f0; font-size: 0.875rem; }
        .review-rating .fas.fa-star.filled { color: #f59e0b; }
        .rating-number { font-size: 0.875rem; color: #64748b; font-weight: 600; }
        .review-content { margin-bottom: 1rem; }
        .review-title { font-size: 1rem; font-weight: 600; color: #1e293b; margin-bottom: 0.5rem; }
        .review-text { color: #64748b; line-height: 1.6; font-size: 0.9rem; }
        .review-footer { display: flex; justify-content: space-between; align-items: center; font-size: 0.8rem; color: #64748b; }
        .review-date { display: flex; align-items: center; gap: 0.5rem; }
        .review-status { display: flex; align-items: center; gap: 0.25rem; padding: 0.25rem 0.5rem; border-radius: 12px; font-size: 0.75rem; font-weight: 600; }
        .review-status.pending { background: #fef3c7; color: #d97706; }

        .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; }
        .metric-cell .metric-value { font-size: 1.25rem; font-weight: 700; color: #1e293b; }
        .metric-cell .metric-label { font-size: 0.8rem; color: #64748b; }

        .status-cell .status-badge { padding: 0.25rem 0.75rem; border-radius: 20px; font-size: 0.75rem; font-weight: 600; text-transform: uppercase; }
        .status-cell .status-badge.published { background: #d1fae5; color: #065f46; }
        .status-cell .status-badge.draft { background: #fef3c7; color: #d97706; }
        .category-cell .category-tag { background: #e0f2fe; color: #0369a1; padding: 0.25rem 0.75rem; border-radius: 15px; font-size: 0.8rem; font-weight: 500; }
        .author-cell .author-name { font-weight: 500; color: #374151; }
        .engagement-cell .engagement-score { display: flex; flex-direction: column; gap: 0.25rem; }

        .mini-progress { height: 4px; background: #e5e7eb; border-radius: 2px; overflow: hidden; width: 60px; }
        .mini-progress-fill { height: 100%; background: linear-gradient(90deg, #10b981, #059669); border-radius: 2px; }

        .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); }
        .btn-outline-primary { background: white; color: #667eea; border: 2px solid #667eea; }
        .btn-outline-primary:hover { background: #667eea; color: white; }

        @media (max-width: 1024px) {
            .charts-grid { grid-template-columns: 1fr; }
            .trends-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; }
            .reviews-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen">
<div id="toast-container"></div>
<div id="sidebar-overlay" class="sidebar-overlay lg:hidden"></div>

<div class="flex">
    <?php include 'includes/sidebar.php'; ?>

    <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">
                <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 class="flex-1 overflow-y-auto pt-16">
        <?php include 'includes/mobile_menu.php'; ?>

        <!-- Analytics Hero Section -->
        <section class="analytics-hero">
            <div class="container">
                <div class="hero-content">
                    <div class="hero-text">
                        <h1 class="hero-title">Analytics Dashboard</h1>
                        <p class="hero-subtitle">Track your course performance, student engagement, and revenue 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>Key Performance Indicators</h2>
                    <p>Monitor your teaching impact and business metrics</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>
                                +<?php echo (int)($overallStats['recent_enrollments_30d'] ?? 0); ?>
                            </div>
                        </div>
                        <div class="metric-content">
                            <div class="metric-value"><?php echo number_format((int)($overallStats['total_courses'] ?? 0)); ?></div>
                            <div class="metric-label">Total Courses</div>
                            <div class="metric-description">Courses you have created</div>
                        </div>
                    </div>

                    <div class="metric-card success">
                        <div class="metric-header">
                            <div class="metric-icon">
                                <i class="fas fa-check-circle"></i>
                            </div>
                            <div class="metric-badge">
                                <i class="fas fa-chart-line"></i>
                                <?php
                                $published = (int)($overallStats['published_courses'] ?? 0);
                                $total = max(1, (int)($overallStats['total_courses'] ?? 1));
                                echo (int)round(($published / $total) * 100);
                                ?>%
                            </div>
                        </div>
                        <div class="metric-content">
                            <div class="metric-value"><?php echo number_format($published); ?></div>
                            <div class="metric-label">Published Courses</div>
                            <div class="metric-description">Live courses</div>
                        </div>
                    </div>

                    <div class="metric-card warning">
                        <div class="metric-header">
                            <div class="metric-icon">
                                <i class="fas fa-layer-group"></i>
                            </div>
                            <div class="metric-badge">
                                <i class="fas fa-layer-group"></i>
                                Draft
                            </div>
                        </div>
                        <div class="metric-content">
                            <div class="metric-value"><?php echo number_format((int)($overallStats['draft_courses'] ?? 0)); ?></div>
                            <div class="metric-label">Draft Courses</div>
                            <div class="metric-description">Courses not published yet</div>
                        </div>
                    </div>

                    <div class="metric-card info">
                        <div class="metric-header">
                            <div class="metric-icon">
                                <i class="fas fa-users"></i>
                            </div>
                            <div class="metric-badge">
                                <i class="fas fa-user-friends"></i>
                                <?php echo (int)($engagementMetrics['active_last_week'] ?? 0); ?>
                            </div>
                        </div>
                        <div class="metric-content">
                            <div class="metric-value"><?php echo number_format((int)($overallStats['total_students'] ?? 0)); ?></div>
                            <div class="metric-label">Total Students</div>
                            <div class="metric-description">Students enrolled in your courses</div>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- Charts and Insights Section -->
        <section class="charts-section">
            <div class="container">
                <div class="charts-grid">
                    <div class="chart-card">
                        <div class="card-header">
                            <div class="card-title">
                                <i class="fas fa-chart-bar"></i>
                                <h3>Course Performance Overview</h3>
                            </div>
                            <div class="card-controls">
                                <select class="metric-selector" id="performanceMetric">
                                    <option value="enrollments">Enrollments</option>
                                    <option value="completions">Completions</option>
                                    <option value="completion_rate">Completion %</option>
                                </select>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="chart-container">
                                <canvas id="performanceChart" height="300"></canvas>
                            </div>
                        </div>
                    </div>

                    <div class="insights-card">
                        <div class="card-header">
                            <div class="card-title">
                                <i class="fas fa-trophy"></i>
                                <h3>Top Performing Courses</h3>
                            </div>
                        </div>
                        <div class="card-body">
                            <?php if (!empty($topCourses)): ?>
                                <div class="top-courses-list">
                                    <?php foreach ($topCourses as $index => $course):
                                        $enrollments = (int)($course['enrollments'] ?? 0);
                                        $completions = (int)($course['completions'] ?? 0);
                                        $completionRate = $enrollments > 0 ? round(($completions / $enrollments) * 100, 1) : 0;
                                        $avgRating = $course['avg_rating'] !== null ? (float)$course['avg_rating'] : 0;
                                    ?>
                                        <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 $enrollments; ?> students</span>
                                                    </div>
                                                    <div class="metric">
                                                        <i class="fas fa-check-circle"></i>
                                                        <span><?php echo $completionRate; ?>% completion</span>
                                                    </div>
                                                    <?php if ($avgRating > 0): ?>
                                                        <div class="metric">
                                                            <i class="fas fa-star"></i>
                                                            <span><?php echo number_format($avgRating, 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-chart-line"></i></div>
                                    <h4>No Course Data</h4>
                                    <p>No course performance data available yet. Start teaching to see insights here.</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- Trends and Engagement Section -->
        <section class="trends-section">
            <div class="container">
                <div class="section-header">
                    <h2>Trends & Engagement</h2>
                    <p>Monitor enrollment patterns and student activity over time</p>
                </div>

                <div class="trends-grid">
                    <div class="trend-card">
                        <div class="card-header">
                            <div class="card-title">
                                <i class="fas fa-calendar-alt"></i>
                                <div>
                                    <h3>Enrollment Trends</h3>
                                    <p class="card-subtitle">Monthly enrollment data over the last 12 months</p>
                                </div>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="chart-container">
                                <canvas id="enrollmentChart" height="250"></canvas>
                            </div>
                        </div>
                    </div>

                    <div class="engagement-card">
                        <div class="card-header">
                            <div class="card-title">
                                <i class="fas fa-users-cog"></i>
                                <div>
                                    <h3>Student Engagement</h3>
                                    <p class="card-subtitle">Key engagement metrics and completion rates</p>
                                </div>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="engagement-metrics">
                                <div class="metric-item">
                                    <div class="metric-info">
                                        <div class="metric-label">Completion Rate</div>
                                        <div class="metric-value"><?php echo round((float)($engagementMetrics['completion_rate'] ?? 0), 1); ?>%</div>
                                    </div>
                                    <div class="metric-progress">
                                        <div class="progress-bar">
                                            <div class="progress-fill" style="width: <?php echo min(100, (float)($engagementMetrics['completion_rate'] ?? 0)); ?>%"></div>
                                        </div>
                                    </div>
                                </div>

                                <div class="metric-item">
                                    <div class="metric-info">
                                        <div class="metric-label">Average Progress</div>
                                        <div class="metric-value"><?php echo round((float)($engagementMetrics['avg_progress'] ?? 0)); ?>%</div>
                                    </div>
                                    <div class="metric-progress">
                                        <div class="progress-bar">
                                            <div class="progress-fill" style="width: <?php echo min(100, (float)($engagementMetrics['avg_progress'] ?? 0)); ?>%"></div>
                                        </div>
                                    </div>
                                </div>

                                <div class="metric-item">
                                    <div class="metric-info">
                                        <div class="metric-label">Avg. Completion Time</div>
                                        <div class="metric-value"><?php echo $engagementMetrics['avg_completion_days'] !== null ? round((float)$engagementMetrics['avg_completion_days']) . ' days' : 'N/A'; ?></div>
                                    </div>
                                    <div class="metric-visual"><i class="fas fa-clock"></i></div>
                                </div>

                                <div class="metric-item">
                                    <div class="metric-info">
                                        <div class="metric-label">Active This Week</div>
                                        <div class="metric-value"><?php echo (int)($engagementMetrics['active_last_week'] ?? 0); ?> students</div>
                                    </div>
                                    <div class="metric-visual"><i class="fas fa-user-check"></i></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- Reviews Section -->
        <?php if (!empty($recentReviews)): ?>
            <section class="reviews-section">
                <div class="container">
                    <div class="section-header">
                        <h2>Recent Student Reviews</h2>
                        <p>What your students are saying about your courses</p>
                        <a href="reviews.php" class="btn btn-outline-primary">
                            <i class="fas fa-eye"></i>
                            View All Reviews
                        </a>
                    </div>

                    <div class="reviews-grid">
                        <?php foreach ($recentReviews as $review): ?>
                            <div class="review-card">
                                <div class="review-header">
                                    <div class="reviewer-avatar"><i class="fas fa-user"></i></div>
                                    <div class="reviewer-info">
                                        <h4><?php echo htmlspecialchars($review['student_name'] ?? ''); ?></h4>
                                        <p class="course-name"><?php echo htmlspecialchars($review['course_title'] ?? ''); ?></p>
                                    </div>
                                    <div class="review-rating">
                                        <?php $rating = (int)($review['rating'] ?? 0); ?>
                                        <?php for ($i = 1; $i <= 5; $i++): ?>
                                            <i class="fas fa-star <?php echo $i <= $rating ? 'filled' : ''; ?>"></i>
                                        <?php endfor; ?>
                                        <span class="rating-number"><?php echo $rating; ?>/5</span>
                                    </div>
                                </div>

                                <div class="review-content">
                                    <?php if (!empty($review['review_title'])): ?>
                                        <h5 class="review-title"><?php echo htmlspecialchars($review['review_title']); ?></h5>
                                    <?php endif; ?>
                                    <?php if (!empty($review['review_text'])): ?>
                                        <p class="review-text"><?php echo htmlspecialchars(mb_substr($review['review_text'], 0, 200)) . (mb_strlen($review['review_text']) > 200 ? '...' : ''); ?></p>
                                    <?php endif; ?>
                                </div>

                                <div class="review-footer">
                                    <div class="review-date">
                                        <i class="fas fa-calendar"></i>
                                        <?php echo !empty($review['created_at']) ? date('M j, Y', strtotime($review['created_at'])) : ''; ?>
                                    </div>
                                    <?php if (($review['status'] ?? '') === 'pending'): ?>
                                        <span class="review-status pending"><i class="fas fa-clock"></i>Pending Review</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </section>
        <?php endif; ?>

        <!-- Detailed Analytics Table Section -->
        <section class="analytics-table-section">
            <div class="container">
                <div class="section-header">
                    <h2>Detailed Course Analytics</h2>
                    <p>Comprehensive performance data for your courses</p>
                    <button class="btn btn-primary" onclick="exportAnalytics()">
                        <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>Status</th>
                                    <th>Enrollments</th>
                                    <th>Completions</th>
                                    <th>Avg. Progress</th>
                                    <th>Avg. Rating</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($coursePerformance as $course):
                                    $enrollments = (int)($course['enrollments'] ?? 0);
                                    $completions = (int)($course['completions'] ?? 0);
                                    $avgProgress = (float)($course['avg_progress'] ?? 0);
                                    $avgRating = (float)($course['avg_rating'] ?? 0);
                                    $completionRate = $enrollments > 0 ? round(($completions / $enrollments) * 100, 1) : 0;
                                ?>
                                    <tr>
                                        <td>
                                            <div class="course-cell">
                                                <div class="course-title"><?php echo htmlspecialchars($course['title'] ?? ''); ?></div>
                                                <div class="course-meta">ID: <?php echo (int)($course['id'] ?? 0); ?></div>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="status-cell">
                                                <span class="status-badge <?php echo htmlspecialchars($course['status'] ?? 'draft'); ?>">
                                                    <?php echo htmlspecialchars(ucfirst($course['status'] ?? 'draft')); ?>
                                                </span>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="metric-cell">
                                                <div class="metric-value"><?php echo $enrollments; ?></div>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="metric-cell">
                                                <div class="metric-value"><?php echo $completions; ?></div>
                                                <div class="metric-label"><?php echo $completionRate; ?>% completion</div>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="metric-cell">
                                                <div class="metric-value"><?php echo round($avgProgress); ?>%</div>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="metric-cell">
                                                <div class="metric-value"><?php echo $avgRating > 0 ? number_format($avgRating, 1) : 'N/A'; ?></div>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                                <?php if (empty($coursePerformance)): ?>
                                    <tr>
                                        <td colspan="6" style="text-align:center; padding: 2rem; color:#64748b;">No course data available.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </section>
    </main>
</div>

<script>
    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');
        });

        mobileMenu.querySelectorAll('a').forEach(link => {
            link.addEventListener('click', () => {
                mobileMenu.classList.add('-translate-x-full');
            });
        });
    }
</script>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Data from database (no mock/random)
const courseData = <?php echo json_encode(array_map(function($c){
    $enrollments = (int)($c['enrollments'] ?? 0);
    $completions = (int)($c['completions'] ?? 0);
    $completionRate = $enrollments > 0 ? ($completions / $enrollments) * 100 : 0;
    return [
        'title' => $c['title'] ?? '',
        'enrollments' => $enrollments,
        'completions' => $completions,
        'completion_rate' => $completionRate,
        'avg_progress' => (float)($c['avg_progress'] ?? 0),
        'avg_rating' => (float)($c['avg_rating'] ?? 0)
    ];
}, $topCourses)); ?>;

const postingTrends = <?php echo json_encode($enrollmentTrends); ?>;

function safeArr(arr, fallback){ return (Array.isArray(arr) && arr.length ? arr : fallback); }

function initializeCharts(){
    const labels = safeArr(courseData.map(c=>c.title), ['No Courses']);
    const enrollments = safeArr(courseData.map(c=>c.enrollments), [0]);
    const completions = safeArr(courseData.map(c=>c.completions), [0]);
    const completionRate = safeArr(courseData.map(c=>c.completion_rate), [0]);

    const ctx = document.getElementById('performanceChart').getContext('2d');
    const performanceChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels,
            datasets: [{
                label: 'Enrollments',
                data: enrollments,
                backgroundColor: 'rgba(54, 162, 235, 0.5)',
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { display: false } },
            scales: { y: { beginAtZero: true } }
        }
    });

    document.getElementById('performanceMetric').addEventListener('change', function(){
        const metric = this.value;
        let data = enrollments;
        let label = 'Enrollments';
        let color = 'rgba(54, 162, 235, 0.5)';
        let border = 'rgba(54, 162, 235, 1)';

        if(metric === 'completions'){
            data = completions; label = 'Completions';
            color = 'rgba(16, 185, 129, 0.5)';
            border = 'rgba(16, 185, 129, 1)';
        } else if(metric === 'completion_rate'){
            data = completionRate; label = 'Completion %';
            color = 'rgba(245, 158, 11, 0.4)';
            border = 'rgba(245, 158, 11, 1)';
        }

        performanceChart.data.datasets[0].data = data;
        performanceChart.data.datasets[0].label = label;
        performanceChart.data.datasets[0].backgroundColor = color;
        performanceChart.data.datasets[0].borderColor = border;
        performanceChart.update();
    });

    const trendCtx = document.getElementById('enrollmentChart').getContext('2d');
    const trendLabels = safeArr(postingTrends.map(t=>t.month), ['No Data']);
    const trendEnrollments = safeArr(postingTrends.map(t=>t.enrollments), [0]);

    new Chart(trendCtx, {
        type: 'line',
        data: {
            labels: trendLabels,
            datasets: [{
                label: 'Monthly Enrollments',
                data: trendEnrollments,
                borderColor: 'rgba(118, 75, 162, 1)',
                backgroundColor: 'rgba(118, 75, 162, 0.15)',
                tension: 0.4,
                fill: true,
                pointRadius: 3
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { display: false } },
            scales: { y: { beginAtZero: true } }
        }
    });
}

document.addEventListener('DOMContentLoaded', initializeCharts);

function exportAnalytics(){
    const data = <?php echo json_encode($coursePerformance); ?>;
    let csv = 'Course Title,Status,Enrollments,Completions,Avg Progress,Avg Rating\n';
    data.forEach(c => {
        const title = (c.title ?? '').toString().replace(/"/g,'""');
        const status = c.status ?? '';
        const enrollments = c.enrollments ?? 0;
        const completions = c.completions ?? 0;
        const avgProgress = c.avg_progress ?? 0;
        const avgRating = c.avg_rating ?? '';
        csv += `"${title}","${status}","${enrollments}","${completions}","${avgProgress}","${avgRating}"\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>

