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

$user = getUserContext();
$page_title = 'Analytics Dashboard';

// Initialize variables with default values
$totalStudents = 0;
$activeCourses = 0;
$totalRevenue = 0;
$avgProgress = 0;
$completionRate = 0;
$recentReviews = [];
$courseAnalytics = [];
$topCourses = [];
$enrollmentTrends = [];
$avgRating = 0;
$totalEnrollments = 0;
$activeThisWeek = 0;

try {
    $db = getDB();
    
    // 1. Get total students count
    $stmt = $db->query("SELECT COUNT(*) FROM users WHERE role = 'student'");
    $totalStudents = (int)$stmt->fetchColumn();
    
    // 2. Get active courses count
    $stmt = $db->query("SELECT COUNT(*) FROM courses WHERE status = 'published'");
    $activeCourses = (int)$stmt->fetchColumn();
    
    // 3. Get total revenue from completed payments
    $stmt = $db->query("SELECT COALESCE(SUM(final_amount), 0) FROM payment_transactions WHERE status = 'completed'");
    $totalRevenue = (float)$stmt->fetchColumn();
    
    // 4. Get average progress from enrollments
    $stmt = $db->query("SELECT COALESCE(AVG(progress_percentage), 0) FROM course_enrollments");
    $avgProgress = (float)$stmt->fetchColumn();
    
    // 5. Get completion rate
    $stmt = $db->query("SELECT 
        CASE 
            WHEN COUNT(*) > 0 THEN (COUNT(CASE WHEN status = 'completed' THEN 1 END) * 100.0 / COUNT(*))
            ELSE 0 
        END 
        FROM course_enrollments");
    $completionRate = (float)$stmt->fetchColumn();
    
    // 6. Get total enrollments
    $stmt = $db->query("SELECT COUNT(*) FROM course_enrollments");
    $totalEnrollments = (int)$stmt->fetchColumn();
    
    // 7. Get average rating from reviews
    $stmt = $db->query("SELECT COALESCE(AVG(rating), 0) FROM course_reviews WHERE status = 'approved'");
    $avgRating = (float)$stmt->fetchColumn();
    
    // 8. Get active students this week
    $stmt = $db->query("SELECT COUNT(DISTINCT student_id) FROM user_activities WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)");
    $activeThisWeek = (int)$stmt->fetchColumn();
    if ($activeThisWeek === 0) {
        // Fallback: get students with recent enrollments
        $stmt = $db->query("SELECT COUNT(DISTINCT student_id) FROM course_enrollments WHERE enrollment_date >= DATE_SUB(NOW(), INTERVAL 7 DAY)");
        $activeThisWeek = (int)$stmt->fetchColumn();
    }
    
    // 9. Get recent reviews with student and course info
    $stmt = $db->query("
        SELECT 
            r.id,
            r.rating,
            r.review_title,
            r.review_text,
            r.created_at,
            c.title as course_name,
            COALESCE(CONCAT(p.first_name, ' ', p.last_name), u.username) as student_name
        FROM course_reviews r
        LEFT JOIN courses c ON r.course_id = c.id
        LEFT JOIN users u ON r.student_id = u.id
        LEFT JOIN user_profiles p ON u.id = p.user_id
        WHERE r.status = 'approved'
        ORDER BY r.created_at DESC
        LIMIT 10
    ");
    $recentReviews = $stmt->fetchAll();
    
    // 10. Get course analytics with enrollments, completions, ratings, revenue
    $stmt = $db->query("
        SELECT 
            c.id,
            c.title as course_name,
            c.price,
            COUNT(e.id) as enrollments,
            COUNT(CASE WHEN e.status = 'completed' THEN 1 END) as completions,
            COALESCE(AVG(e.progress_percentage), 0) as avg_progress,
            COALESCE(AVG(r.rating), 0) as avg_rating,
            COUNT(r.id) as review_count
        FROM courses c
        LEFT JOIN course_enrollments e ON c.id = e.course_id
        LEFT JOIN course_reviews r ON c.id = r.course_id AND r.status = 'approved'
        WHERE c.status = 'published'
        GROUP BY c.id, c.title, c.price
        ORDER BY enrollments DESC
    ");
    $courseAnalytics = $stmt->fetchAll();
    
    // 11. Get revenue per course
    $stmt = $db->query("
        SELECT 
            c.id,
            COALESCE(SUM(pt.final_amount), 0) as revenue
        FROM courses c
        LEFT JOIN payment_transactions pt ON c.id = pt.item_id AND pt.item_type = 'course' AND pt.status = 'completed'
        WHERE c.status = 'published'
        GROUP BY c.id
    ");
    $revenueByCourse = [];
    while ($row = $stmt->fetch()) {
        $revenueByCourse[$row['id']] = (float)$row['revenue'];
    }
    
    // Add revenue to course analytics
    foreach ($courseAnalytics as &$course) {
        $course['revenue'] = $revenueByCourse[$course['id']] ?? 0;
    }
    unset($course);
    
    // 12. Get top courses (by enrollments)
    $topCourses = array_slice($courseAnalytics, 0, 5);
    
    // 13. Get enrollment trends (last 12 months)
    $stmt = $db->query("
        SELECT 
            DATE_FORMAT(enrollment_date, '%Y-%m') as month,
            COUNT(*) as count
        FROM course_enrollments
        WHERE enrollment_date >= DATE_SUB(NOW(), INTERVAL 12 MONTH)
        GROUP BY DATE_FORMAT(enrollment_date, '%Y-%m')
        ORDER BY month ASC
    ");
    $enrollmentTrends = $stmt->fetchAll();
    
    // Fill in missing months with 0
    $trendMap = [];
    foreach ($enrollmentTrends as $t) {
        $trendMap[$t['month']] = (int)$t['count'];
    }
    
    $formattedTrends = [];
    for ($i = 11; $i >= 0; $i--) {
        $month = date('Y-m', strtotime("-$i months"));
        $monthLabel = date('M', strtotime("-$i months"));
        $formattedTrends[] = [
            'month' => $monthLabel,
            'count' => $trendMap[$month] ?? 0
        ];
    }
    $enrollmentTrends = $formattedTrends;
    
} catch (Exception $e) {
    error_log("Analytics Error: " . $e->getMessage());
    // Use default values if database error occurs
}

// Format last updated time
$lastUpdated = date('M d, Y \a\t g:i A');

include 'includes/admin_header.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 $lastUpdated; ?></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%; animation-delay: 0.1s"></div>
                            <div class="bar" style="height: 80%; animation-delay: 0.2s"></div>
                            <div class="bar" style="height: 40%; animation-delay: 0.3s"></div>
                            <div class="bar" style="height: 90%; animation-delay: 0.4s"></div>
                            <div class="bar" style="height: 70%; animation-delay: 0.5s"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- Key Metrics Section -->
    <section class="metrics-section">
        <div class="container">
            <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 $totalEnrollments > 0 ? '+' . $totalEnrollments : '0'; ?>
                        </div>
                    </div>
                    <div class="metric-content">
                        <div class="metric-value"><?php echo number_format($totalStudents); ?></div>
                        <div class="metric-label">Total Students</div>
                        <div class="metric-description">Students enrolled in your courses</div>
                    </div>
                </div>

                <div class="metric-card success">
                    <div class="metric-header">
                        <div class="metric-icon">
                            <i class="fas fa-book-open"></i>
                        </div>
                        <div class="metric-badge">
                            <i class="fas fa-chart-line"></i>
                            <?php echo $completionRate > 0 ? round($completionRate) . '%' : 'N/A'; ?>
                        </div>
                    </div>
                    <div class="metric-content">
                        <div class="metric-value"><?php echo number_format($activeCourses); ?></div>
                        <div class="metric-label">Active Courses</div>
                        <div class="metric-description">Courses you're currently teaching</div>
                    </div>
                </div>

                <div class="metric-card warning">
                    <div class="metric-header">
                        <div class="metric-icon">
                            <i class="fas fa-dollar-sign"></i>
                        </div>
                        <div class="metric-badge">
                            <i class="fas fa-trending-up"></i>
                            Revenue
                        </div>
                    </div>
                    <div class="metric-content">
                        <div class="metric-value">$<?php echo number_format($totalRevenue, 2); ?></div>
                        <div class="metric-label">Total Revenue</div>
                        <div class="metric-description">Earnings from course sales</div>
                    </div>
                </div>

                <div class="metric-card info">
                    <div class="metric-header">
                        <div class="metric-icon">
                            <i class="fas fa-chart-pie"></i>
                        </div>
                        <div class="metric-badge">
                            <i class="fas fa-users"></i>
                            <?php echo $activeThisWeek; ?>
                        </div>
                    </div>
                    <div class="metric-content">
                        <div class="metric-value"><?php echo $avgProgress > 0 ? round($avgProgress) . '%' : '0%'; ?></div>
                        <div class="metric-label">Avg. Progress</div>
                        <div class="metric-description">Student completion progress</div>
                    </div>
                </div>
            </div>
        </div>
    </section>

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

                <!-- Course Performance Chart -->
                <div class="chart-card">
                    <div class="card-header">
                        <div class="card-title">
                            <i class="fas fa-chart-bar"></i>
                            <h3>Course Performance</h3>
                        </div>
                        <div class="card-controls">
                            <select class="metric-selector" id="performanceMetric">
                                <option value="enrollments">Enrollments</option>
                                <option value="revenue">Revenue</option>
                            </select>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="performanceChart"></canvas>
                        </div>
                    </div>
                </div>

                <!-- Top Performing Courses -->
                <div class="insights-card">
                    <div class="card-header">
                        <div class="card-title">
                            <i class="fas fa-trophy"></i>
                            <h3>Top Courses</h3>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="top-courses-list">
                            <?php if (!empty($topCourses)): ?>
                                <?php $rank = 1; foreach ($topCourses as $course): ?>
                                    <?php 
                                    $courseCompletionRate = $course['enrollments'] > 0 ? round(($course['completions'] / $course['enrollments']) * 100) : 0;
                                    $courseRating = $course['avg_rating'] > 0 ? round($course['avg_rating'], 1) : 'N/A';
                                    ?>
                                    <div class="course-ranking-item">
                                        <div class="ranking-badge">
                                            <span class="rank-number"><?php echo $rank; ?></span>
                                        </div>
                                        <div class="course-details">
                                            <h4><?php echo htmlspecialchars($course['course_name']); ?></h4>
                                            <div class="course-metrics">
                                                <div class="metric">
                                                    <i class="fas fa-users"></i>
                                                    <span><?php echo $course['enrollments']; ?> students</span>
                                                </div>
                                                <div class="metric">
                                                    <i class="fas fa-check-circle"></i>
                                                    <span><?php echo $courseCompletionRate; ?>% completion</span>
                                                </div>
                                                <div class="metric">
                                                    <i class="fas fa-star" style="color: #f59e0b;"></i>
                                                    <span><?php echo $courseRating; ?></span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php $rank++; endforeach; ?>
                                <?php else: ?>
                                    <div class="course-ranking-item">
                                        <div class="course-details">
                                            <h4>No course data available</h4>
                                            <div class="course-metrics">
                                                <div class="metric">
                                                    <span>Start enrolling students to see analytics</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endif; ?>
                        </div>
                    </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">

                <!-- Enrollment Trends Chart -->
                <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"></canvas>
                        </div>
                    </div>
                </div>

                <!-- Student Engagement Metrics -->
                <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 $completionRate > 0 ? round($completionRate, 1) . '%' : '0%'; ?></div>
                                </div>
                                <div class="metric-progress">
                                    <div class="progress-bar">
                                        <div class="progress-fill" style="width: <?php echo min($completionRate, 100); ?>%"></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 $avgProgress > 0 ? round($avgProgress) . '%' : '0%'; ?></div>
                                </div>
                                <div class="metric-progress">
                                    <div class="progress-bar">
                                        <div class="progress-fill" style="width: <?php echo min($avgProgress, 100); ?>%"></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 $totalEnrollments > 0 ? 'N/A' : '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 $activeThisWeek; ?> students</div>
                                </div>
                                <div class="metric-visual">
                                    <i class="fas fa-user-check"></i>
                                </div>
                            </div>

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

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

    <!-- Reviews Section -->
    <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>
                <button class="btn btn-outline-primary" onclick="window.location.href='reviews.php'">
                    <i class="fas fa-eye"></i>
                    View All Reviews
                </button>
            </div>

            <div class="reviews-grid">
                <?php if (!empty($recentReviews)): ?>
                    <?php foreach ($recentReviews as $review): ?>
                        <?php
                        $rating = (int)$review['rating'];
                        $fullStars = $rating;
                        $emptyStars = 5 - $rating;
                        $reviewDate = date('M d, Y', strtotime($review['created_at']));
                        ?>
                        <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'] ?? 'Anonymous'); ?></h4>
                                    <p class="course-name"><?php echo htmlspecialchars($review['course_name'] ?? 'Unknown Course'); ?></p>
                                </div>
                                <div class="review-rating">
                                    <?php for ($i = 0; $i < $fullStars; $i++): ?>
                                        <i class="fas fa-star filled"></i>
                                    <?php endfor; ?>
                                    <?php for ($i = 0; $i < $emptyStars; $i++): ?>
                                        <i class="fas fa-star"></i>
                                    <?php endfor; ?>
                                    <span class="rating-number"><?php echo $rating; ?>/5</span>
                                </div>
                            </div>
                            <div class="review-content">
                                <h5 class="review-title"><?php echo htmlspecialchars($review['review_title'] ?? 'Great Course!'); ?></h5>
                                <p class="review-text"><?php echo htmlspecialchars($review['review_text'] ?? ''); ?></p>
                            </div>
                            <div class="review-footer">
                                <div class="review-date">
                                    <i class="fas fa-calendar"></i>
                                    <?php echo $reviewDate; ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="review-card">
                        <div class="review-content">
                            <p class="review-text">No reviews yet. Students will appear here once they submit course reviews.</p>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </section>
        </div>
    </section>

    <!-- 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 all your courses</p>
                <button class="btn btn-primary" onclick="alert('Export functionality coming soon!')">
                    <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>Enrollments</th>
                                <th>Completions</th>
                                <th>Avg. Progress</th>
                                <th>Rating</th>
                                <th>Revenue</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($courseAnalytics)): ?>
                                <?php foreach ($courseAnalytics as $course): ?>
                                    <?php
                                    $courseProgress = $course['avg_progress'] > 0 ? round($course['avg_progress']) : 0;
                                    $courseCompletionRate = $course['enrollments'] > 0 ? round(($course['completions'] / $course['enrollments']) * 100) : 0;
                                    $courseRating = $course['avg_rating'] > 0 ? round($course['avg_rating'], 1) : 0;
                                    $ratingStars = $courseRating > 0 ? floor($courseRating) : 0;
                                    ?>
                                    <tr>
                                        <td>
                                            <div class="course-cell">
                                                <div class="course-title"><?php echo htmlspecialchars($course['course_name']); ?></div>
                                                <div class="course-meta">ID: <?php echo $course['id']; ?></div>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="metric-cell">
                                                <div class="metric-value"><?php echo $course['enrollments']; ?></div>
                                                <div class="metric-label">students</div>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="metric-cell">
                                                <div class="metric-value"><?php echo $course['completions']; ?></div>
                                                <div class="metric-label">completed</div>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="progress-cell">
                                                <div class="progress-info">
                                                    <span class="progress-value"><?php echo $courseProgress; ?>%</span>
                                                    <div class="progress-bar">
                                                        <div class="progress-fill" style="width: <?php echo $courseProgress; ?>%"></div>
                                                    </div>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="rating-cell">
                                                <div class="rating-stars">
                                                    <?php for ($i = 0; $i < 5; $i++): ?>
                                                        <i class="fas fa-star <?php echo $i < $ratingStars ? 'filled' : ''; ?>"></i>
                                                    <?php endfor; ?>
                                                </div>
                                                <div class="rating-info">
                                                    <span class="rating-number"><?php echo $courseRating > 0 ? $courseRating : 'N/A'; ?></span>
                                                    <span class="rating-count">(<?php echo $course['review_count']; ?>)</span>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="revenue-cell">
                                                <div class="revenue-amount">$<?php echo number_format($course['revenue'], 2); ?></div>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="actions-cell">
                                                <button class="btn btn-sm btn-outline-primary" onclick="window.location.href='course_details.php?id=<?php echo $course['id']; ?>'">Details</button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="7" style="text-align: center; padding: 2rem;">
                                        <p>No course data available. Start publishing courses to see analytics.</p>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </section>

<!-- Chart.js for visualizations -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // --- DATA FROM DATABASE ---
    const courseLabels = <?php echo json_encode(array_column($courseAnalytics, 'course_name')); ?>;
    const enrollmentData = <?php echo json_encode(array_column($courseAnalytics, 'enrollments')); ?>;
    const completionData = <?php echo json_encode(array_column($courseAnalytics, 'completions')); ?>;
    const revenueData = <?php echo json_encode(array_map(function($c) { return (float)$c['revenue']; }, $courseAnalytics)); ?>;

    const trendLabels = <?php echo json_encode(array_column($enrollmentTrends, 'month')); ?>;
    const trendEnrollments = <?php echo json_encode(array_column($enrollmentTrends, 'count')); ?>;

    // Fallback to default data if empty
    const safeLabels = courseLabels.length > 0 ? courseLabels : ['No Courses'];
    const safeEnrollments = enrollmentData.length > 0 ? enrollmentData : [0];
    const safeCompletions = completionData.length > 0 ? completionData : [0];
    const safeRevenue = revenueData.length > 0 ? revenueData : [0];
    const safeTrendLabels = trendLabels.length > 0 ? trendLabels : ['No Data'];
    const safeTrendEnrollments = trendEnrollments.length > 0 ? trendEnrollments : [0];

    // 1. Performance Chart (Bar Chart)
    const perfCtx = document.getElementById('performanceChart').getContext('2d');

    const perfChart = new Chart(perfCtx, {
        type: 'bar',
        data: {
            labels: safeLabels,
            datasets: [
                {
                    label: 'Enrollments',
                    data: safeEnrollments,
                    backgroundColor: '#667eea',
                    borderRadius: 4
                },
                {
                    label: 'Completions',
                    data: safeCompletions,
                    backgroundColor: '#10b981',
                    borderRadius: 4
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { position: 'top' },
                tooltip: { mode: 'index', intersect: false }
            },
            scales: {
                y: { beginAtZero: true, grid: { borderDash: [2, 4] } },
                x: { grid: { display: false } }
            }
        }
    });

    // Handle Metric Selector Change
    document.getElementById('performanceMetric').addEventListener('change', function(e) {
        if(e.target.value === 'revenue') {
            perfChart.data.datasets = [{
                label: 'Revenue ($)',
                data: safeRevenue,
                backgroundColor: '#f59e0b',
                borderRadius: 4
            }];
        } else {
            perfChart.data.datasets = [
                {
                    label: 'Enrollments',
                    data: safeEnrollments,
                    backgroundColor: '#667eea',
                    borderRadius: 4
                },
                {
                    label: 'Completions',
                    data: safeCompletions,
                    backgroundColor: '#10b981',
                    borderRadius: 4
                }
            ];
        }
        perfChart.update();
    });

    // 2. Trends Chart (Line Chart)
    const trendsCtx = document.getElementById('enrollmentChart').getContext('2d');

    new Chart(trendsCtx, {
        type: 'line',
        data: {
            labels: safeTrendLabels,
            datasets: [{
                label: 'Monthly Enrollments',
                data: safeTrendEnrollments,
                borderColor: '#764ba2',
                backgroundColor: 'rgba(118, 75, 162, 0.1)',
                tension: 0.4,
                fill: true,
                pointBackgroundColor: '#fff',
                pointBorderColor: '#764ba2',
                pointBorderWidth: 2,
                pointRadius: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { display: false } },
            scales: {
                y: { beginAtZero: true, ticks: { precision: 0 } },
                x: { grid: { display: false } }
            }
        }
    });
});
</script>

<style>
/* Professional Analytics Dashboard Styles */
:root {
    --primary: #667eea;
    --primary-dark: #5a67d8;
    --secondary: #764ba2;
    --success: #10b981;
    --warning: #f59e0b;
    --info: #3b82f6;
    --dark: #1e293b;
    --light: #f8fafc;
    --gray: #64748b;
    --border: #e2e8f0;
}

body {
    background-color: #f1f5f9;
    color: var(--dark);
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
    margin: 0;
    padding: 0;
}

/* Global Container */
.container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 1.5rem;
}

/* Button Helpers */
.btn {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.5rem 1rem;
    border-radius: 6px;
    font-weight: 500;
    cursor: pointer;
    text-decoration: none;
    transition: all 0.2s;
    border: none;
    font-size: 0.9rem;
}

.btn-primary {
    background-color: var(--primary);
    color: white;
}
.btn-primary:hover { background-color: var(--primary-dark); }

.btn-outline-primary {
    background-color: transparent;
    border: 1px solid var(--primary);
    color: var(--primary);
}
.btn-outline-primary:hover {
    background-color: var(--primary);
    color: white;
}

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

.analytics-hero::before {
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0; bottom: 0;
    background: radial-gradient(circle at 20% 50%, rgba(255,255,255,0.1) 0%, transparent 50%);
    opacity: 0.5;
}

.hero-content {
    position: relative;
    z-index: 2;
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 3rem;
    align-items: center;
}

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

.hero-subtitle {
    font-size: 1.1rem;
    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;
    box-shadow: 0 10px 25px rgba(0,0,0,0.1);
}

.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;
    animation: growBar 1.5s ease-out forwards;
}

@keyframes growBar {
    from { height: 0; opacity: 0; }
    to { opacity: 1; }
}

/* Metrics Section */
.metrics-section {
    padding: 0 0 3rem;
    margin-top: -3rem; /* Negative margin to pull up */
    position: relative;
    z-index: 3;
}

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

.section-header h2 {
    font-size: 2rem;
    font-weight: 700;
    color: var(--dark);
    margin: 0 0 0.5rem;
}

.section-header p {
    font-size: 1.1rem;
    color: var(--gray);
    max-width: 600px;
    margin: 0 auto;
}

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

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

.metric-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
}

.metric-card::before {
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 4px;
}

.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: 1rem;
}

.metric-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.25rem;
    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: #f1f5f9;
    color: var(--dark);
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 0.25rem;
}

.metric-value {
    font-size: 2rem;
    font-weight: 800;
    color: var(--dark);
    line-height: 1;
    margin-bottom: 0.25rem;
}

.metric-label {
    font-size: 0.9rem;
    font-weight: 600;
    color: var(--gray);
}

.metric-description {
    font-size: 0.8rem;
    color: #94a3b8;
    margin-top: 0.5rem;
}

/* Charts Section */
.charts-section, .trends-section, .reviews-section, .analytics-table-section {
    padding: 3rem 0;
    background: white;
}
.trends-section { background: #f8fafc; }

.charts-grid, .trends-grid {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 2rem;
}

.chart-card, .insights-card, .trend-card, .engagement-card, .analytics-table-card {
    background: white;
    border-radius: 16px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
    border: 1px solid var(--border);
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.card-header {
    padding: 1.25rem 1.5rem;
    border-bottom: 1px solid var(--border);
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #fff;
}

.card-title {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    font-size: 1.1rem;
    font-weight: 600;
    color: var(--dark);
}

.card-title i {
    color: var(--primary);
    font-size: 1.25rem;
}

.card-title h3 { margin: 0; font-size: 1.1rem; }
.card-subtitle { font-size: 0.85rem; color: var(--gray); margin: 0.2rem 0 0 0; font-weight: normal; }

.card-body { padding: 1.5rem; flex: 1; }

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

.metric-selector {
    padding: 0.25rem 0.5rem;
    border: 1px solid var(--border);
    border-radius: 6px;
    font-size: 0.85rem;
    color: var(--gray);
    outline: none;
    background: white;
}

/* Ranking List */
.top-courses-list { display: flex; flex-direction: column; gap: 0; }
.course-ranking-item {
    display: flex;
    gap: 1rem;
    align-items: center;
    padding: 1rem 0;
    border-bottom: 1px solid #f1f5f9;
}
.course-ranking-item:last-child { border-bottom: none; padding-bottom: 0; }
.course-ranking-item:first-child { padding-top: 0; }

.ranking-badge {
    width: 32px;
    height: 32px;
    background: #f1f5f9;
    color: var(--primary);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    flex-shrink: 0;
}

.course-details { flex: 1; }
.course-details h4 { margin: 0 0 0.25rem 0; font-size: 0.95rem; color: var(--dark); }
.course-metrics { display: flex; gap: 1rem; font-size: 0.8rem; color: var(--gray); flex-wrap: wrap; }
.course-metrics .metric { display: flex; align-items: center; gap: 0.25rem; }

/* Engagement Metrics */
.engagement-metrics { display: flex; flex-direction: column; gap: 1.5rem; }

.metric-item { display: flex; flex-direction: column; gap: 0.5rem; }
.metric-info { display: flex; justify-content: space-between; align-items: flex-end; }
.metric-item .metric-visual { display: flex; justify-content: flex-end; color: var(--primary); opacity: 0.1; font-size: 1.5rem; margin-top: -1.5rem; pointer-events: none;}

.progress-bar {
    height: 8px;
    background: #f1f5f9;
    border-radius: 4px;
    overflow: hidden;
    width: 100%;
}
.progress-fill {
    height: 100%;
    background: var(--primary);
    border-radius: 4px;
}

/* Reviews Grid */
.reviews-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 1.5rem;
}

.review-card {
    background: white;
    border: 1px solid var(--border);
    border-radius: 12px;
    padding: 1.5rem;
    display: flex;
    flex-direction: column;
}

.review-header { display: flex; gap: 1rem; margin-bottom: 1rem; }
.reviewer-avatar {
    width: 40px; height: 40px;
    background: #f1f5f9;
    border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    color: var(--gray);
}
.reviewer-info h4 { margin: 0; font-size: 0.95rem; }
.course-name { margin: 0; font-size: 0.8rem; color: var(--gray); }
.review-rating { margin-left: auto; display: flex; align-items: center; gap: 0.1rem; font-size: 0.8rem; color: #fbbf24; }
.review-rating .filled { color: #f59e0b; }
.review-rating .rating-number { color: var(--gray); margin-left: 0.25rem; }

.review-content { flex: 1; margin-bottom: 1rem; }
.review-title { font-size: 1rem; font-weight: 600; margin: 0 0 0.5rem; }
.review-text { font-size: 0.9rem; color: var(--gray); line-height: 1.5; margin: 0; }

.review-footer { padding-top: 0.75rem; border-top: 1px dashed var(--border); display: flex; justify-content: space-between; font-size: 0.8rem; color: #94a3b8; }
.review-status.pending { color: var(--warning); display: flex; align-items: center; gap: 0.25rem; }

/* Table Styles */
.table-container { overflow-x: auto; -webkit-overflow-scrolling: touch; }
.analytics-table { width: 100%; border-collapse: collapse; min-width: 800px; }
.analytics-table th { text-align: left; padding: 1rem; font-size: 0.85rem; color: var(--gray); text-transform: uppercase; letter-spacing: 0.05em; border-bottom: 1px solid var(--border); background: #f8fafc; font-weight: 600;}
.analytics-table td { padding: 1rem; vertical-align: middle; border-bottom: 1px solid #f1f5f9; }
.analytics-table tr:hover { background: #fcfcfc; }
.analytics-table tr:last-child td { border-bottom: none; }

.course-cell .course-title { font-weight: 600; font-size: 0.95rem; color: var(--dark); margin-bottom: 0.2rem;}
.course-cell .course-meta { font-size: 0.75rem; color: #94a3b8; }

.metric-cell { text-align: center; }
.metric-cell .metric-value { font-weight: 600; color: var(--dark); font-size: 0.95rem;}
.metric-cell .metric-label { font-size: 0.75rem; color: var(--gray); }

.progress-cell { width: 150px; }
.progress-info { display: flex; flex-direction: column; gap: 0.25rem; }
.progress-value { font-size: 0.8rem; font-weight: 600; }

.rating-stars { color: #f59e0b; font-size: 0.8rem; letter-spacing: -1px; }
.rating-info { font-size: 0.75rem; color: var(--gray); }

.revenue-amount { font-weight: 700; color: var(--success); }

.actions-cell .btn-sm { padding: 0.35rem 0.75rem; font-size: 0.8rem; }

/* Media Queries */
@media (max-width: 992px) {
    .hero-content { grid-template-columns: 1fr; text-align: center; gap: 2rem; }
    .hero-meta { justify-content: center; }
    .charts-grid, .trends-grid { grid-template-columns: 1fr; }
}
</style>

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