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

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

$user = getUserContext();

// Get course ID from URL
$courseId = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$courseId) {
    header('Location: ../dashboard.php');
    exit;
}

// Verify access to this course
$db = getDB();
$stmt = $db->prepare("SELECT * FROM courses WHERE id = ?");
$stmt->execute([$courseId]);
$course = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$course || ($_SESSION['role'] !== 'admin' && $course['instructor_id'] !== $_SESSION['user_id'])) {
    header('Location: ../dashboard.php');
    exit;
}

$page_title = 'Course Analytics - ' . htmlspecialchars($course['title']);
include '../../includes/header.php';
?>

<div class="admin-container">
    <div class="admin-sidebar">
        <div class="admin-logo">
            <h2>Mutalex Academy</h2>
            <p>Instructor Panel</p>
        </div>

        <nav class="admin-nav">
            <ul>
                <li><a href="../dashboard.php">Dashboard</a></li>
                <li><a href="../courses/" class="active">My Courses</a></li>
                <li><a href="../courses/new.php">Create Course</a></li>
                <li><a href="/lms/instructor/questions/index.php">Question Bank</a></li>
                <li><a href="/lms/instructor/exams/index.php">Exams</a></li>
                <li><a href="../resources.php">Resources</a></li>
                <li><a href="../analytics.php">Analytics</a></li>
                <li><a href="../../logout.php">Logout</a></li>
            </ul>
        </nav>
    </div>

    <div class="admin-content">
        <div class="admin-header">
            <div class="course-header">
                <div class="course-info">
                    <h1><?php echo htmlspecialchars($course['title']); ?></h1>
                    <p class="course-description"><?php echo htmlspecialchars($course['short_description'] ?? ''); ?></p>
                    <div class="course-meta">
                        <span class="badge bg-<?php echo $course['status'] === 'published' ? 'success' : 'secondary'; ?>">
                            <?php echo ucfirst($course['status']); ?>
                        </span>
                        <span class="text-muted">•</span>
                        <span><?php echo htmlspecialchars($course['level']); ?> Level</span>
                        <span class="text-muted">•</span>
                        <span><?php echo $course['duration_hours']; ?> hours</span>
                    </div>
                </div>
                <div class="course-actions">
                    <a href="edit.php?id=<?php echo $courseId; ?>" class="btn btn-secondary">Edit Course</a>
                    <a href="../analytics.php" class="btn btn-primary">Back to Analytics</a>
                </div>
            </div>
        </div>

        <!-- Course Overview Stats -->
        <div class="dashboard-stats" id="course-overview">
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-users"></i>
                </div>
                <div class="stat-info">
                    <h3 id="enrolled-students">-</h3>
                    <p>Enrolled Students</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-check-circle"></i>
                </div>
                <div class="stat-info">
                    <h3 id="completed-students">-</h3>
                    <p>Completed Students</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-chart-line"></i>
                </div>
                <div class="stat-info">
                    <h3 id="completion-rate">0%</h3>
                    <p>Completion Rate</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-star"></i>
                </div>
                <div class="stat-info">
                    <h3 id="avg-rating">0.0</h3>
                    <p>Average Rating</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-clock"></i>
                </div>
                <div class="stat-info">
                    <h3 id="avg-time">0h</h3>
                    <p>Avg. Time per Student</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-book"></i>
                </div>
                <div class="stat-info">
                    <h3 id="total-lessons">-</h3>
                    <p>Total Lessons</p>
                </div>
            </div>
        </div>

        <!-- Charts Section -->
        <div class="analytics-charts">
            <div class="chart-container">
                <h3>Enrollment Trend</h3>
                <canvas id="enrollment-trend-chart"></canvas>
            </div>
            <div class="chart-container">
                <h3>Lesson Completion Rates</h3>
                <canvas id="lesson-completion-chart"></canvas>
            </div>
            <div class="chart-container">
                <h3>Grade Distribution</h3>
                <canvas id="grade-distribution-chart"></canvas>
            </div>
        </div>

        <!-- Student Engagement -->
        <div class="dashboard-section">
            <h2>Student Engagement</h2>
            <div class="engagement-metrics" id="student-engagement">
                <div class="loading">Loading engagement data...</div>
            </div>
        </div>

        <!-- Content Performance -->
        <div class="dashboard-section">
            <h2>Content Performance</h2>
            <div class="content-performance" id="content-performance">
                <div class="loading">Loading content performance...</div>
            </div>
        </div>

        <!-- Assessment Performance -->
        <div class="dashboard-section">
            <h2>Assessment Performance</h2>
            <div class="assessment-performance" id="assessment-performance">
                <div class="loading">Loading assessment data...</div>
            </div>
        </div>

        <!-- Top Students -->
        <div class="dashboard-section">
            <h2>Top Performing Students</h2>
            <div class="top-students" id="top-students">
                <div class="loading">Loading student rankings...</div>
            </div>
        </div>

        <!-- Export Options -->
        <div class="dashboard-section">
            <h2>Export Course Data</h2>
            <div class="export-options">
                <button onclick="exportCourseData('enrollments')" class="btn btn-primary">
                    <i class="fas fa-users"></i> Export Enrollments
                </button>
                <button onclick="exportCourseData('grades')" class="btn btn-secondary">
                    <i class="fas fa-chart-bar"></i> Export Grades
                </button>
                <button onclick="exportCourseData('engagement')" class="btn btn-success">
                    <i class="fas fa-clock"></i> Export Engagement Data
                </button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
let enrollmentTrendChart, lessonCompletionChart, gradeDistributionChart;

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

function loadCourseAnalytics() {
    const courseId = <?php echo $courseId; ?>;

    fetch(`../../api/analytics/index.php?action=course_analytics&course_id=${courseId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updateCourseOverview(data.data.overview);
                updateCharts(data.data.charts);
                updateStudentEngagement(data.data.student_engagement);
                updateContentPerformance(data.data.content_performance);
                updateAssessmentPerformance(data.data.assessment_stats);
                updateTopStudents(data.data.student_engagement.most_active_students);
            } else {
                console.error('Failed to load course analytics:', data.message);
                showError('Failed to load course analytics');
            }
        })
        .catch(error => {
            console.error('Error loading course analytics:', error);
            showError('Error loading course analytics');
        });
}

function updateCourseOverview(overview) {
    document.getElementById('enrolled-students').textContent = overview.enrolled_students;
    document.getElementById('completed-students').textContent = overview.completed_students;
    document.getElementById('completion-rate').textContent = overview.completion_rate + '%';
    document.getElementById('avg-rating').textContent = overview.avg_rating;
    document.getElementById('avg-time').textContent = Math.round(overview.avg_time_per_student / 3600) + 'h';
    document.getElementById('total-lessons').textContent = overview.total_lessons;
}

function initializeCharts() {
    // Enrollment Trend Chart
    const enrollmentTrendCtx = document.getElementById('enrollment-trend-chart').getContext('2d');
    enrollmentTrendChart = new Chart(enrollmentTrendCtx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: 'Enrollments',
                data: [],
                borderColor: '#007bff',
                backgroundColor: 'rgba(0, 123, 255, 0.1)',
                tension: 0.4,
                fill: true
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });

    // Lesson Completion Chart
    const lessonCompletionCtx = document.getElementById('lesson-completion-chart').getContext('2d');
    lessonCompletionChart = new Chart(lessonCompletionCtx, {
        type: 'bar',
        data: {
            labels: [],
            datasets: [{
                label: 'Completion Rate %',
                data: [],
                backgroundColor: '#28a745',
                borderColor: '#28a745',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    max: 100
                }
            }
        }
    });

    // Grade Distribution Chart
    const gradeDistributionCtx = document.getElementById('grade-distribution-chart').getContext('2d');
    gradeDistributionChart = new Chart(gradeDistributionCtx, {
        type: 'doughnut',
        data: {
            labels: [],
            datasets: [{
                data: [],
                backgroundColor: [
                    '#dc3545', // F
                    '#fd7e14', // D
                    '#ffc107', // C
                    '#20c997', // B
                    '#28a745'  // A
                ],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
}

function updateCharts(charts) {
    // Update Enrollment Trend Chart
    if (charts.enrollment_trend && enrollmentTrendChart) {
        enrollmentTrendChart.data.labels = charts.enrollment_trend.map(item => item.date);
        enrollmentTrendChart.data.datasets[0].data = charts.enrollment_trend.map(item => item.enrollments);
        enrollmentTrendChart.update();
    }

    // Update Lesson Completion Chart
    if (charts.lesson_completion && lessonCompletionChart) {
        lessonCompletionChart.data.labels = charts.lesson_completion.map(item => item.title.substring(0, 20) + (item.title.length > 20 ? '...' : ''));
        lessonCompletionChart.data.datasets[0].data = charts.lesson_completion.map(item => item.completed / item.total_attempts * 100);
        lessonCompletionChart.update();
    }

    // Update Grade Distribution Chart
    if (charts.grade_distribution && gradeDistributionChart) {
        gradeDistributionChart.data.labels = charts.grade_distribution.map(item => item.grade_range);
        gradeDistributionChart.data.datasets[0].data = charts.grade_distribution.map(item => item.count);
        gradeDistributionChart.update();
    }
}

function updateStudentEngagement(engagement) {
    const container = document.getElementById('student-engagement');
    container.innerHTML = `
        <div class="engagement-grid">
            <div class="engagement-card">
                <h4>${Math.round(engagement.avg_time_per_student / 3600)}h</h4>
                <p>Average time per student</p>
            </div>
            <div class="engagement-card">
                <h4>${engagement.most_active_students ? engagement.most_active_students.length : 0}</h4>
                <p>Active students tracked</p>
            </div>
        </div>
    `;
}

function updateContentPerformance(performance) {
    const container = document.getElementById('content-performance');
    if (!performance.lesson_performance || performance.lesson_performance.length === 0) {
        container.innerHTML = '<p class="text-muted">No lesson performance data available.</p>';
        return;
    }

    container.innerHTML = `
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Lesson</th>
                    <th>Completion Rate</th>
                    <th>Total Views</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                ${performance.lesson_performance.map(lesson => `
                    <tr>
                        <td>${lesson.title}</td>
                        <td>
                            <div class="progress-bar">
                                <div class="progress-fill" style="width: ${lesson.completion_rate}%"></div>
                            </div>
                            <small>${lesson.completion_rate}%</small>
                        </td>
                        <td>${lesson.total_views}</td>
                        <td>
                            <span class="badge bg-${lesson.completion_rate > 70 ? 'success' : lesson.completion_rate > 40 ? 'warning' : 'danger'}">
                                ${lesson.completion_rate > 70 ? 'Good' : lesson.completion_rate > 40 ? 'Average' : 'Needs Attention'}
                            </span>
                        </td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    `;
}

function updateAssessmentPerformance(assessment) {
    const container = document.getElementById('assessment-performance');
    if (!assessment.exam_performance || assessment.exam_performance.length === 0) {
        container.innerHTML = '<p class="text-muted">No assessment data available.</p>';
        return;
    }

    container.innerHTML = `
        <div class="exam-performance-grid">
            ${assessment.exam_performance.map(exam => `
                <div class="exam-card">
                    <h5>${exam.title}</h5>
                    <div class="exam-metrics">
                        <div class="metric">
                            <span class="metric-value">${exam.total_attempts}</span>
                            <span class="metric-label">Attempts</span>
                        </div>
                        <div class="metric">
                            <span class="metric-value">${exam.avg_score.toFixed(1)}%</span>
                            <span class="metric-label">Avg Score</span>
                        </div>
                        <div class="metric">
                            <span class="metric-value">${exam.pass_rate}%</span>
                            <span class="metric-label">Pass Rate</span>
                        </div>
                    </div>
                </div>
            `).join('')}
        </div>
    `;
}

function updateTopStudents(students) {
    const container = document.getElementById('top-students');
    if (!students || students.length === 0) {
        container.innerHTML = '<p class="text-muted">No student activity data available.</p>';
        return;
    }

    container.innerHTML = `
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Student</th>
                    <th>Time Spent</th>
                    <th>Lessons Completed</th>
                    <th>Rank</th>
                </tr>
            </thead>
            <tbody>
                ${students.slice(0, 10).map((student, index) => `
                    <tr>
                        <td>${student.username}</td>
                        <td>${Math.round(student.total_time / 3600)}h ${Math.round((student.total_time % 3600) / 60)}m</td>
                        <td>${student.lessons_completed}</td>
                        <td>
                            <span class="badge bg-${index < 3 ? 'warning' : 'secondary'}">
                                #${index + 1}
                            </span>
                        </td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    `;
}

function exportCourseData(type) {
    const courseId = <?php echo $courseId; ?>;
    let endpoint = '';

    switch (type) {
        case 'enrollments':
            endpoint = `../../api/analytics/index.php?action=export_data&type=course_data&course_id=${courseId}&format=csv`;
            break;
        case 'grades':
            endpoint = `../../api/analytics/index.php?action=export_data&type=exam_results&course_id=${courseId}&format=csv`;
            break;
        case 'engagement':
            endpoint = `../../api/analytics/index.php?action=export_data&type=user_data&course_id=${courseId}&format=csv`;
            break;
    }

    const link = document.createElement('a');
    link.href = endpoint;
    link.download = `course_${type}_export.csv`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

function showError(message) {
    const errorDiv = document.createElement('div');
    errorDiv.className = 'alert alert-danger';
    errorDiv.textContent = message;
    document.querySelector('.admin-content').prepend(errorDiv);

    setTimeout(() => {
        errorDiv.remove();
    }, 5000);
}
</script>

<style>
:root {
    --primary-color: #6366f1;
    --primary-dark: #4f46e5;
    --secondary-color: #f8fafc;
    --accent-color: #10b981;
    --danger-color: #ef4444;
    --warning-color: #f59e0b;
    --text-primary: #1f2937;
    --text-secondary: #6b7280;
    --text-muted: #9ca3af;
    --border-color: #e5e7eb;
    --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
    --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
    --shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
    --gradient-primary: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    --gradient-accent: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    --gradient-success: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    --border-radius: 12px;
    --border-radius-sm: 8px;
    --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

* {
    box-sizing: border-box;
}

body {
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
    color: var(--text-primary);
    line-height: 1.6;
}

.admin-container {
    min-height: 100vh;
    background: transparent;
}

.admin-sidebar {
    background: linear-gradient(180deg, #1e293b 0%, #0f172a 100%);
    box-shadow: var(--shadow-xl);
    border-right: 1px solid rgba(255, 255, 255, 0.1);
}

.admin-logo h2 {
    background: var(--gradient-primary);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    font-weight: 700;
}

.admin-nav ul li a {
    transition: var(--transition);
    border-radius: var(--border-radius-sm);
    margin: 2px 8px;
}

.admin-nav ul li a:hover,
.admin-nav ul li a.active {
    background: rgba(99, 102, 241, 0.2);
    border-left: 3px solid var(--primary-color);
    transform: translateX(4px);
}

.admin-content {
    background: transparent;
    padding: 2rem;
}

.course-header {
    background: white;
    border-radius: var(--border-radius);
    padding: 2rem;
    margin-bottom: 2rem;
    box-shadow: var(--shadow-lg);
    border: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 2rem;
    position: relative;
    overflow: hidden;
}

.course-header::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: var(--gradient-primary);
}

.course-info h1 {
    font-size: 2.5rem;
    font-weight: 800;
    margin: 0 0 1rem 0;
    background: var(--gradient-primary);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    line-height: 1.2;
}

.course-description {
    color: var(--text-secondary);
    font-size: 1.1rem;
    margin: 0 0 1.5rem 0;
    line-height: 1.6;
}

.course-meta {
    display: flex;
    align-items: center;
    gap: 1rem;
    font-size: 0.95rem;
    color: var(--text-secondary);
    flex-wrap: wrap;
}

.badge {
    padding: 0.5rem 1rem;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.bg-success {
    background: linear-gradient(135deg, #10b981, #059669);
    color: white;
}

.bg-secondary {
    background: linear-gradient(135deg, #6b7280, #4b5563);
    color: white;
}

.course-actions {
    display: flex;
    gap: 1rem;
    flex-shrink: 0;
}

.btn {
    padding: 0.75rem 1.5rem;
    border-radius: var(--border-radius-sm);
    font-weight: 600;
    text-decoration: none;
    transition: var(--transition);
    border: none;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    font-size: 0.95rem;
}

.btn-primary {
    background: var(--gradient-primary);
    color: white;
    box-shadow: var(--shadow-md);
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: var(--shadow-lg);
}

.btn-secondary {
    background: var(--secondary-color);
    color: var(--text-primary);
    border: 1px solid var(--border-color);
}

.btn-secondary:hover {
    background: white;
    transform: translateY(-2px);
    box-shadow: var(--shadow-md);
}

.dashboard-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 1.5rem;
    margin-bottom: 3rem;
}

.stat-card {
    background: white;
    padding: 2rem;
    border-radius: var(--border-radius);
    box-shadow: var(--shadow-lg);
    display: flex;
    align-items: center;
    gap: 1.5rem;
    transition: var(--transition);
    border: 1px solid var(--border-color);
    position: relative;
    overflow: hidden;
}

.stat-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: var(--gradient-primary);
}

.stat-card:hover {
    transform: translateY(-4px);
    box-shadow: var(--shadow-xl);
}

.stat-icon {
    width: 70px;
    height: 70px;
    background: var(--gradient-primary);
    color: white;
    border-radius: var(--border-radius);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.8rem;
    flex-shrink: 0;
    box-shadow: var(--shadow-md);
}

.stat-info h3 {
    font-size: 2.5rem;
    font-weight: 800;
    margin: 0 0 0.5rem 0;
    color: var(--text-primary);
    line-height: 1;
}

.stat-info p {
    margin: 0;
    color: var(--text-secondary);
    font-weight: 600;
    font-size: 1rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.analytics-charts {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
    gap: 2rem;
    margin: 3rem 0;
}

.chart-container {
    background: white;
    border-radius: var(--border-radius);
    padding: 2rem;
    box-shadow: var(--shadow-lg);
    border: 1px solid var(--border-color);
    transition: var(--transition);
    position: relative;
    overflow: hidden;
}

.chart-container::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: var(--gradient-accent);
}

.chart-container:hover {
    transform: translateY(-2px);
    box-shadow: var(--shadow-xl);
}

.chart-container h3 {
    margin: 0 0 1.5rem 0;
    color: var(--text-primary);
    font-size: 1.5rem;
    font-weight: 700;
    text-align: center;
    position: relative;
}

.dashboard-section {
    background: white;
    border-radius: var(--border-radius);
    padding: 2rem;
    margin-bottom: 2rem;
    box-shadow: var(--shadow-lg);
    border: 1px solid var(--border-color);
    position: relative;
    overflow: hidden;
}

.dashboard-section::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: var(--gradient-success);
}

.dashboard-section h2 {
    margin: 0 0 2rem 0;
    color: var(--text-primary);
    font-size: 1.8rem;
    font-weight: 700;
    position: relative;
}

.engagement-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 1.5rem;
}

.engagement-card {
    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
    border-radius: var(--border-radius);
    padding: 2rem;
    box-shadow: var(--shadow-md);
    text-align: center;
    border: 1px solid var(--border-color);
    transition: var(--transition);
}

.engagement-card:hover {
    transform: translateY(-2px);
    box-shadow: var(--shadow-lg);
}

.engagement-card h4 {
    margin: 0 0 0.5rem 0;
    color: var(--primary-color);
    font-size: 2.5rem;
    font-weight: 800;
    line-height: 1;
}

.engagement-card p {
    margin: 0;
    color: var(--text-secondary);
    font-weight: 600;
    font-size: 1rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.content-performance .table {
    background: white;
    border-radius: var(--border-radius);
    overflow: hidden;
    box-shadow: var(--shadow-md);
    border: 1px solid var(--border-color);
}

.table {
    width: 100%;
    margin-bottom: 0;
    border-collapse: collapse;
}

.table th {
    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
    padding: 1.25rem 1rem;
    text-align: left;
    font-weight: 700;
    color: var(--text-primary);
    border-bottom: 2px solid var(--border-color);
    font-size: 0.95rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.table td {
    padding: 1.25rem 1rem;
    border-bottom: 1px solid var(--border-color);
    vertical-align: middle;
    color: var(--text-secondary);
}

.table tr:hover {
    background: rgba(99, 102, 241, 0.02);
}

.progress-bar {
    width: 100%;
    height: 10px;
    background: var(--secondary-color);
    border-radius: 20px;
    overflow: hidden;
    margin-bottom: 0.5rem;
    box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
}

.progress-fill {
    height: 100%;
    background: var(--gradient-primary);
    border-radius: 20px;
    transition: width 0.8s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
}

.progress-fill::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
    animation: shimmer 2s infinite;
}

@keyframes shimmer {
    0% { transform: translateX(-100%); }
    100% { transform: translateX(100%); }
}

.exam-performance-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 1.5rem;
}

.exam-card {
    background: white;
    border-radius: var(--border-radius);
    padding: 2rem;
    box-shadow: var(--shadow-lg);
    border: 1px solid var(--border-color);
    transition: var(--transition);
    position: relative;
    overflow: hidden;
}

.exam-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: var(--gradient-accent);
}

.exam-card:hover {
    transform: translateY(-2px);
    box-shadow: var(--shadow-xl);
}

.exam-card h5 {
    margin: 0 0 1.5rem 0;
    color: var(--text-primary);
    font-size: 1.3rem;
    font-weight: 700;
}

.exam-metrics {
    display: flex;
    justify-content: space-between;
    gap: 1rem;
}

.metric {
    text-align: center;
    flex: 1;
    padding: 1rem;
    background: var(--secondary-color);
    border-radius: var(--border-radius-sm);
    border: 1px solid var(--border-color);
}

.metric-value {
    display: block;
    font-size: 1.5rem;
    font-weight: 800;
    color: var(--primary-color);
    margin-bottom: 0.25rem;
    line-height: 1;
}

.metric-label {
    font-size: 0.85rem;
    color: var(--text-secondary);
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.top-students .table {
    background: white;
    border-radius: var(--border-radius);
    overflow: hidden;
    box-shadow: var(--shadow-md);
    border: 1px solid var(--border-color);
}

.export-options {
    display: flex;
    gap: 1rem;
    flex-wrap: wrap;
    justify-content: center;
}

.export-options .btn {
    padding: 1rem 2rem;
    font-size: 1rem;
    min-width: 200px;
    justify-content: center;
}

.loading {
    text-align: center;
    padding: 4rem 2rem;
    color: var(--text-muted);
    font-size: 1.1rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 1rem;
}

.loading::before {
    content: '';
    width: 40px;
    height: 40px;
    border: 3px solid var(--border-color);
    border-top: 3px solid var(--primary-color);
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.alert {
    padding: 1.5rem;
    margin-bottom: 2rem;
    border: 1px solid transparent;
    border-radius: var(--border-radius);
    display: flex;
    align-items: center;
    gap: 1rem;
}

.alert-danger {
    color: #dc2626;
    background: linear-gradient(135deg, #fef2f2, #fee2e2);
    border-color: #fecaca;
}

.alert i {
    font-size: 1.5rem;
    flex-shrink: 0;
}

.text-muted {
    color: var(--text-muted) !important;
}

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

    .dashboard-stats {
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    }
}

@media (max-width: 768px) {
    .admin-content {
        padding: 1rem;
    }

    .course-header {
        flex-direction: column;
        text-align: center;
        gap: 1.5rem;
    }

    .course-info h1 {
        font-size: 2rem;
    }

    .course-actions {
        justify-content: center;
    }

    .analytics-charts {
        grid-template-columns: 1fr;
    }

    .engagement-grid,
    .exam-performance-grid {
        grid-template-columns: 1fr;
    }

    .exam-metrics {
        flex-direction: column;
        gap: 1rem;
    }

    .export-options {
        flex-direction: column;
        align-items: stretch;
    }

    .export-options .btn {
        width: 100%;
        min-width: auto;
    }

    .dashboard-stats {
        grid-template-columns: 1fr;
    }

    .stat-card {
        padding: 1.5rem;
    }

    .stat-icon {
        width: 60px;
        height: 60px;
        font-size: 1.5rem;
    }

    .stat-info h3 {
        font-size: 2rem;
    }
}

@media (max-width: 480px) {
    .course-info h1 {
        font-size: 1.8rem;
    }

    .dashboard-section,
    .chart-container,
    .exam-card,
    .engagement-card {
        padding: 1.5rem;
    }

    .course-header {
        padding: 1.5rem;
    }

    .stat-card {
        flex-direction: column;
        text-align: center;
        gap: 1rem;
    }

    .exam-metrics {
        grid-template-columns: 1fr;
    }
}
</style>

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