<?php
/**
 * SmartThink LMS - Student Dashboard
 * 
 * Main dashboard for logged-in students
 */

require_once __DIR__ . '/../config/database.php';

// Check if user is logged in
requireLogin();

// Get current user
$user = getCurrentUser();
if (!$user) {
    redirect('login.php');
}

// Route admin-level users to the CMS dashboard instead of the student dashboard
if (hasRole('admin')) {
    redirect(APP_URL . '/cms/dashboard.php');
}

// Get database instance
$db = Database::getInstance();

// Get user statistics
$stats = getStudentStats($user['id']);

// Get recent enrollments
$recentEnrollments = getRecentEnrollments($user['id']);

// Get achievements
$achievements = getStudentAchievements($user['id']);

// Get upcoming live sessions across enrolled courses
$upcomingLiveSessions = getUpcomingLiveSessions($user['id']);

// Get upcoming installment payments for this student
function getUpcomingInstallments($userId, $limit = 10) {
    global $db;

    return $db->getAll(
        "SELECT ei.*, c.title AS course_title
         FROM enrollment_installments ei
         JOIN course_enrollments ce ON ei.enrollment_id = ce.id
         JOIN courses c ON ce.course_id = c.id
         WHERE ce.student_id = ? AND ei.status = 'pending'
         ORDER BY ei.due_date ASC
         LIMIT ?",
        [$userId, $limit]
    );
}

$upcomingInstallments = getUpcomingInstallments($user['id']);

// Get recommended courses
$recommendedCourses = getRecommendedCourses($user['id']);

function getStudentStats($userId) {
    global $db;
    
    $stats = [];
    
    // Enrollment statistics
    $enrollments = $db->get("
        SELECT COUNT(*) as total,
               SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed,
               AVG(progress_percentage) as avg_progress,
               SUM(total_time_spent) as total_time
        FROM course_enrollments 
        WHERE student_id = ?
    ", [$userId]);
    
    $stats['enrollments'] = $enrollments;
    
    // Certificate statistics
    $certificates = $db->get("
        SELECT COUNT(*) as total,
               MAX(issue_date) as latest
        FROM certificates 
        WHERE student_id = ? AND is_revoked = 0
    ", [$userId]);
    
    $stats['certificates'] = $certificates;
    
    // Achievement statistics
    $achievements = $db->get("
        SELECT COUNT(*) as total,
               SUM(CASE WHEN achievement_type = 'badge' THEN 1 ELSE 0 END) as badges,
               SUM(CASE WHEN achievement_type = 'points' THEN achievement_value ELSE 0 END) as points
        FROM gamification 
        WHERE user_id = ?
    ", [$userId]);
    
    $stats['achievements'] = $achievements;
    
    // Learning streak
    $streak = $db->get("
        SELECT COUNT(DISTINCT DATE(created_at)) as days
        FROM activity_logs 
        WHERE user_id = ? 
        AND action LIKE '%lesson%'
        AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    ", [$userId]);
    
    $stats['streak'] = $streak['days'] ?? 0;
    
    return $stats;
}

function getRecentEnrollments($userId, $limit = 5) {
    global $db;
    
    return $db->getAll("
        SELECT ce.*, c.title, c.slug, c.thumbnail, c.instructor_id,
               u.first_name, u.last_name,
               a.id AS agreement_id,
               (SELECT COUNT(*) FROM course_modules WHERE course_id = c.id) as module_count,
               (SELECT COUNT(*) FROM lesson_progress lp 
                JOIN course_lessons cl ON lp.lesson_id = cl.id 
                WHERE lp.enrollment_id = ce.id AND lp.status = 'completed') as completed_lessons
        FROM course_enrollments ce
        JOIN courses c ON ce.course_id = c.id
        JOIN users u ON c.instructor_id = u.id
        LEFT JOIN course_enrollment_agreements a ON a.enrollment_id = ce.id AND a.status = 'signed'
        WHERE ce.student_id = ? AND ce.status = 'active'
        ORDER BY ce.enrollment_date DESC
        LIMIT ?
    ", [$userId, $limit]);
}

function getStudentAchievements($userId, $limit = 10) {
    global $db;
    
    return $db->getAll("
        SELECT * FROM gamification 
        WHERE user_id = ? AND is_displayed = 1
        ORDER BY earned_at DESC
        LIMIT ?
    ", [$userId, $limit]);
}

function getRecommendedCourses($userId, $limit = 6) {
    global $db;
    
    // Get user's enrolled categories
    $categories = $db->getAll("
        SELECT DISTINCT c.category_id
        FROM course_enrollments ce
        JOIN courses c ON ce.course_id = c.id
        WHERE ce.student_id = ? AND ce.status = 'active'
    ", [$userId]);
    
    $categoryIds = array_column($categories, 'category_id');
    
    if (empty($categoryIds)) {
        // If no enrollments, get popular courses
        return $db->getAll("
            SELECT c.*, cat.name as category_name,
                   u.first_name, u.last_name
            FROM courses c
            LEFT JOIN categories cat ON c.category_id = cat.id
            LEFT JOIN users u ON c.instructor_id = u.id
            WHERE c.status = 'published'
            ORDER BY c.enrollment_count DESC, c.rating DESC
            LIMIT ?
        ", [$limit]);
    }
    
    // Get courses from same categories
    $placeholders = str_repeat('?,', count($categoryIds) - 1) . '?';
    array_unshift($categoryIds, $userId);
    $categoryIds[] = $limit;
    
    return $db->getAll("
        SELECT c.*, cat.name as category_name,
               u.first_name, u.last_name
        FROM courses c
        LEFT JOIN categories cat ON c.category_id = cat.id
        LEFT JOIN users u ON c.instructor_id = u.id
        WHERE c.status = 'published'
        AND c.category_id IN ($placeholders)
        AND c.id NOT IN (
            SELECT course_id FROM course_enrollments WHERE student_id = ?
        )
        ORDER BY c.rating DESC, c.enrollment_count DESC
        LIMIT ?
    ", $categoryIds);
}

function getUpcomingLiveSessions($userId, $limit = 5) {
    global $db;

    return $db->getAll("
        SELECT cl.*, c.title AS course_title
        FROM course_lessons cl
        JOIN courses c ON cl.course_id = c.id
        JOIN course_enrollments ce ON ce.course_id = c.id
        WHERE ce.student_id = ?
          AND ce.status = 'active'
          AND cl.content_type = 'live_session'
          AND cl.zoom_start_time IS NOT NULL
          AND cl.is_published = 1
          AND cl.zoom_start_time >= NOW()
        ORDER BY cl.zoom_start_time ASC
        LIMIT ?
    ", [$userId, $limit]);
}

 $currentPage = basename($_SERVER['PHP_SELF']);
 $currentUser = $user;
 $pageTitle = 'My Dashboard';
 include __DIR__ . '/includes/header.php';
?>

<div class="hero-section bg-gradient-primary text-white py-5 mb-5" style="background: linear-gradient(135deg, var(--tcs-primary) 0%, var(--tcs-primary-dark) 100%);">
    <div class="container-xxl">
        <div class="row align-items-center">
            <div class="col-lg-8">
                <h1 class="display-4 fw-bold mb-3">Welcome back, <?php echo htmlspecialchars($user['first_name']); ?>!</h1>
                <p class="lead mb-4">Continue your learning journey with personalized courses and track your progress.</p>
                <div class="d-flex flex-wrap gap-3">
                    <a href="courses.php" class="btn btn-light btn-lg px-4">
                        <i class="ri ri-search-line me-2"></i>Browse Courses
                    </a>
                    <a href="profile.php" class="btn btn-outline-light btn-lg px-4">
                        <i class="ri ri-user-line me-2"></i>My Profile
                    </a>
                </div>
            </div>
            <div class="col-lg-4 text-center d-none d-lg-block">
                <div class="hero-illustration">
                    <img src="<?php echo APP_URL; ?>/assets/images/learning-illustration.svg" alt="Learning" class="img-fluid" style="max-height: 300px; opacity: 0.8;">
                </div>
            </div>
        </div>
    </div>
</div>

<div class="container-xxl mb-5">
    <div class="row g-4">
        <div class="col-xl-3 col-md-6">
            <div class="stats-card">
                <div class="stats-icon">
                    <i class="ri ri-book-open-line"></i>
                </div>
                <div class="stats-content">
                    <h3 class="stats-number"><?php echo number_format((int)($stats['enrollments']['total'] ?? 0)); ?></h3>
                    <p class="stats-label">Active Courses</p>
                    <div class="stats-trend">
                        <small class="text-success">
                            <i class="ri ri-arrow-up-line me-1"></i>
                            <?php echo number_format((int)($stats['enrollments']['completed'] ?? 0)); ?> completed
                        </small>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6">
            <div class="stats-card">
                <div class="stats-icon">
                    <i class="ri ri-award-line"></i>
                </div>
                <div class="stats-content">
                    <h3 class="stats-number"><?php echo number_format((int)($stats['certificates']['total'] ?? 0)); ?></h3>
                    <p class="stats-label">Certificates</p>
                    <div class="stats-trend">
                        <small class="text-muted">
                            <?php echo $stats['certificates']['latest'] ? 'Latest: ' . date('M j, Y', strtotime($stats['certificates']['latest'])) : 'No certificates yet'; ?>
                        </small>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6">
            <div class="stats-card">
                <div class="stats-icon">
                    <i class="ri ri-time-line"></i>
                </div>
                <div class="stats-content">
                    <h3 class="stats-number"><?php echo htmlspecialchars(formatLearningTime((int)($stats['enrollments']['total_time'] ?? 0))); ?></h3>
                    <p class="stats-label">Learning Time</p>
                    <div class="stats-trend">
                        <small class="text-primary">
                            <i class="ri ri-fire-line me-1"></i>
                            <?php echo (int)$stats['streak']; ?> day streak
                        </small>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6">
            <div class="stats-card">
                <div class="stats-icon">
                    <i class="ri ri-star-smile-line"></i>
                </div>
                <div class="stats-content">
                    <h3 class="stats-number"><?php echo number_format((int)($stats['achievements']['points'] ?? 0)); ?></h3>
                    <p class="stats-label">Achievement Points</p>
                    <div class="stats-trend">
                        <small class="text-warning">
                            <i class="ri ri-medal-line me-1"></i>
                            <?php echo number_format((int)($stats['achievements']['badges'] ?? 0)); ?> badges
                        </small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="container-xxl mb-5">
    <div class="row">
        <div class="col-12">
            <div class="card shadow-sm">
                <div class="card-header bg-white border-bottom-0">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h4 class="mb-1">Your Learning Progress</h4>
                            <p class="text-muted mb-0">Track your advancement across all enrolled courses</p>
                        </div>
                        <div class="text-end">
                            <div class="h2 mb-0 text-primary"><?php echo round((float)($stats['enrollments']['avg_progress'] ?? 0), 1); ?>%</div>
                            <small class="text-muted">Average Progress</small>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="progress mb-4" style="height: 8px;">
                        <div class="progress-bar bg-primary" style="width: <?php echo min(100, (float)($stats['enrollments']['avg_progress'] ?? 0)); ?>%"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="container-xxl">
    <div class="row g-4">
        <!-- Continue Learning -->
        <div class="col-xl-8">
                            <div class="card shadow-sm h-100">
                                <div class="card-header bg-white">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h5 class="mb-0">Continue Learning</h5>
                                        <a href="courses.php" class="btn btn-outline-primary btn-sm">View All Courses</a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <?php if ($recentEnrollments): ?>
                                        <div class="course-list">
                                            <?php foreach ($recentEnrollments as $enrollment): ?>
                                                <div class="course-item-modern mb-3 p-3 border rounded">
                                                    <div class="row align-items-center">
                                                        <div class="col-md-2">
                                                            <div class="course-thumbnail-modern">
                                                                <img src="<?php echo $enrollment['thumbnail'] ? '../uploads/courses/' . $enrollment['thumbnail'] : '../assets/images/course-placeholder.jpg'; ?>"
                                                                     alt="<?php echo htmlspecialchars($enrollment['title']); ?>"
                                                                     class="rounded">
                                                            </div>
                                                        </div>
                                                        <div class="col-md-6">
                                                            <h6 class="mb-1">
                                                                <a href="courses.php?course_id=<?php echo $enrollment['course_id']; ?>" class="text-decoration-none text-dark">
                                                                    <?php echo htmlspecialchars($enrollment['title']); ?>
                                                                </a>
                                                            </h6>
                                                            <p class="text-muted small mb-2">by <?php echo htmlspecialchars($enrollment['first_name'] . ' ' . $enrollment['last_name']); ?></p>
                                                            <div class="progress" style="height: 4px;">
                                                                <div class="progress-bar bg-primary" style="width: <?php echo $enrollment['progress_percentage']; ?>%"></div>
                                                            </div>
                                                            <small class="text-muted mt-1 d-block">
                                                                <?php echo $enrollment['completed_lessons']; ?>/<?php echo $enrollment['module_count']; ?> lessons completed
                                                            </small>
                                                        </div>
                                                        <div class="col-md-4 text-end">
                                                            <a href="courses.php?course_id=<?php echo $enrollment['course_id']; ?>" class="btn btn-primary btn-sm">
                                                                <i class="ri ri-play-line me-1"></i>Continue
                                                            </a>
                                                            <?php if (!empty($enrollment['agreement_id'])): ?>
                                                                <a href="view_agreement.php?enrollment_id=<?php echo (int)$enrollment['id']; ?>" class="btn btn-outline-secondary btn-sm ms-1">
                                                                    View Agreement
                                                                </a>
                                                            <?php endif; ?>
                                                        </div>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php else: ?>
                                        <div class="empty-state text-center py-5">
                                            <div class="empty-icon mb-3">
                                                <i class="ri ri-graduation-cap-line icon-xxl text-muted"></i>
                                            </div>
                                            <h5 class="text-muted">No courses yet</h5>
                                            <p class="text-muted">Start your learning journey by enrolling in a course</p>
                                            <a href="courses.php" class="btn btn-primary">Browse Courses</a>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

        <!-- Sidebar -->
        <div class="col-xl-4">
                            <!-- Upcoming Payments -->
                            <div class="card shadow-sm mb-4">
                                <div class="card-header bg-white">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h6 class="mb-0">Upcoming Payments</h6>
                                        <a href="courses.php?mine=1" class="btn btn-outline-primary btn-sm">My Courses</a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <?php if ($upcomingInstallments): ?>
                                        <ul class="list-unstyled mb-0 small">
                                            <?php foreach ($upcomingInstallments as $inst): ?>
                                                <?php
                                                    $dueTs = !empty($inst['due_date']) ? strtotime($inst['due_date']) : null;
                                                    $daysLeft = null;
                                                    if ($dueTs) {
                                                        $daysLeft = (int) floor(($dueTs - time()) / 86400);
                                                    }
                                                ?>
                                                <li class="mb-3">
                                                    <div class="fw-semibold mb-0"><?php echo htmlspecialchars($inst['course_title'] ?? 'Course'); ?></div>
                                                    <div class="text-muted">
                                                        Installment <?php echo (int)($inst['installment_no'] ?? 1); ?>:
                                                        <?php echo htmlspecialchars(number_format((float)($inst['amount'] ?? 0.0), 2)); ?>
                                                        <?php echo htmlspecialchars($inst['currency'] ?? 'USD'); ?>
                                                    </div>
                                                    <?php if ($dueTs): ?>
                                                        <div class="text-muted">
                                                            Due: <?php echo htmlspecialchars(date('Y-m-d H:i', $dueTs)); ?>
                                                            <?php if ($daysLeft !== null && $daysLeft >= 0): ?>
                                                                (in <?php echo $daysLeft; ?> day<?php echo $daysLeft === 1 ? '' : 's'; ?>)
                                                            <?php endif; ?>
                                                        </div>
                                                    <?php endif; ?>
                                                </li>
                                            <?php endforeach; ?>
                                        </ul>
                                    <?php else: ?>
                                        <div class="empty-state text-center py-3">
                                            <h6 class="text-muted mb-1">No upcoming payments</h6>
                                            <p class="text-muted small mb-0">Installment schedules will appear here after you enroll with a payment plan.</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Upcoming Live Sessions -->
                            <div class="card shadow-sm mb-4">
                                <div class="card-header bg-white">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h6 class="mb-0">Upcoming Live Sessions</h6>
                                        <a href="courses.php?mine=1" class="btn btn-outline-primary btn-sm">My Courses</a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <?php if ($upcomingLiveSessions): ?>
                                        <ul class="list-unstyled mb-0 small">
                                            <?php foreach ($upcomingLiveSessions as $session): ?>
                                                <?php
                                                    $start = $session['zoom_start_time'] ?? null;
                                                    $joinUrl = $session['zoom_join_url'] ?? ($session['content_url'] ?? null);
                                                    $startTs = $start ? strtotime($start) : null;
                                                    $now = time();
                                                    $isToday = $startTs ? (date('Y-m-d', $startTs) === date('Y-m-d')) : false;
                                                    $isLiveNow = $startTs ? (abs($now - $startTs) <= 1800) : false; // within 30 minutes of start
                                                ?>
                                                <li class="mb-3">
                                                    <div class="d-flex align-items-center mb-1">
                                                        <?php if ($isLiveNow): ?>
                                                            <span class="badge bg-danger me-2">LIVE NOW</span>
                                                        <?php elseif ($isToday): ?>
                                                            <span class="badge bg-success me-2">Today</span>
                                                        <?php endif; ?>
                                                        <div class="fw-semibold mb-0"><?php echo htmlspecialchars($session['title'] ?? 'Live Session'); ?></div>
                                                    </div>
                                                    <div class="text-muted">
                                                        Course: <?php echo htmlspecialchars($session['course_title'] ?? ''); ?>
                                                    </div>
                                                    <?php if ($startTs): ?>
                                                        <div class="text-muted">
                                                            <?php
                                                                $timeLabel = $isToday ? 'Today, ' . date('H:i', $startTs) : date('Y-m-d H:i', $startTs);
                                                                echo htmlspecialchars($timeLabel);
                                                            ?>
                                                            (<?php echo date_default_timezone_get(); ?>)
                                                        </div>
                                                    <?php endif; ?>
                                                    <?php if ($joinUrl): ?>
                                                        <a href="<?php echo htmlspecialchars($joinUrl); ?>" target="_blank" class="btn btn-sm btn-primary mt-1">Join Session</a>
                                                    <?php endif; ?>
                                                </li>
                                            <?php endforeach; ?>
                                        </ul>
                                    <?php else: ?>
                                        <div class="empty-state text-center py-3">
                                            <h6 class="text-muted mb-1">No upcoming live sessions</h6>
                                            <p class="text-muted small mb-0">New sessions will appear here when your instructors schedule them.</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Recent Achievements -->
                            <div class="card shadow-sm mb-4">
                                <div class="card-header bg-white">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h6 class="mb-0">Recent Achievements</h6>
                                        <a href="achievements.php" class="btn btn-outline-primary btn-sm">View All</a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <?php if ($achievements): ?>
                                        <div class="achievement-list">
                                            <?php foreach (array_slice($achievements, 0, 3) as $achievement): ?>
                                                <div class="achievement-item-modern d-flex align-items-center mb-3">
                                                    <div class="achievement-icon-modern me-3">
                                                        <i class="<?php echo getAchievementIcon($achievement['achievement_type']); ?> text-primary"></i>
                                                    </div>
                                                    <div class="achievement-info">
                                                        <div class="achievement-name fw-semibold"><?php echo htmlspecialchars($achievement['achievement_name']); ?></div>
                                                        <div class="achievement-date small text-muted"><?php echo formatDateAgo($achievement['earned_at']); ?></div>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php else: ?>
                                        <div class="empty-state text-center py-3">
                                            <i class="ri ri-trophy-line icon-lg text-muted mb-2"></i>
                                            <h6 class="text-muted">No achievements yet</h6>
                                            <p class="text-muted small">Complete lessons to earn achievements</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Quick Actions -->
                            <div class="card shadow-sm">
                                <div class="card-header bg-white">
                                    <h6 class="mb-0">Quick Actions</h6>
                                </div>
                                <div class="card-body">
                                    <div class="d-grid gap-2">
                                        <a href="courses.php" class="btn btn-outline-primary d-flex align-items-center">
                                            <i class="ri ri-search-line me-2"></i>Browse Courses
                                        </a>
                                        <a href="certificates.php" class="btn btn-outline-success d-flex align-items-center">
                                            <i class="ri ri-award-line me-2"></i>My Certificates
                                        </a>
                                        <a href="profile.php" class="btn btn-outline-info d-flex align-items-center">
                                            <i class="ri ri-user-line me-2"></i>My Profile
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
    </div>
</div>

<?php if ($recommendedCourses): ?>
<div class="container-xxl mt-5">
    <div class="row">
        <div class="col-12">
            <div class="card shadow-sm">
                <div class="card-header bg-white">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">Recommended for You</h5>
                        <a href="courses.php" class="btn btn-outline-primary btn-sm">Browse All</a>
                    </div>
                </div>
                <div class="card-body">
                    <div class="row g-4">
                        <?php foreach (array_slice($recommendedCourses, 0, 6) as $course): ?>
                            <div class="col-lg-4 col-md-6">
                                <div class="course-card-modern">
                                    <div class="course-image-modern">
                                        <?php
                                            $thumb = $course['thumbnail'] ?? '';
                                            $baseUrl = defined('APP_URL') ? rtrim(APP_URL, '/') : '';
                                            $thumbCandidate = $thumb ? ltrim($thumb, '/') : '';

                                            if ($thumb && stripos($thumb, 'http') === 0) {
                                                $thumbSrc = $thumb;
                                            } elseif ($thumbCandidate && file_exists(__DIR__ . '/../' . $thumbCandidate)) {
                                                $thumbSrc = $baseUrl . '/' . $thumbCandidate;
                                            } elseif ($thumbCandidate && file_exists(__DIR__ . '/../uploads/courses/' . basename($thumbCandidate))) {
                                                $thumbSrc = $baseUrl . '/uploads/courses/' . basename($thumbCandidate);
                                            } else {
                                                $thumbSrc = $baseUrl . '/assets/images/course-placeholder.jpg';
                                            }
                                        ?>
                                        <img src="<?php echo htmlspecialchars($thumbSrc); ?>"
                                             alt="<?php echo htmlspecialchars($course['title']); ?>"
                                             class="course-img">
                                        <div class="course-overlay">
                                            <span class="badge bg-primary"><?php echo htmlspecialchars($course['level'] ?? 'Beginner'); ?></span>
                                        </div>
                                    </div>
                                    <div class="course-content-modern">
                                        <h6 class="course-title-modern">
                                            <a href="courses.php?course_id=<?php echo $course['id']; ?>" class="text-decoration-none">
                                                <?php echo htmlspecialchars($course['title']); ?>
                                            </a>
                                        </h6>
                                        <p class="course-instructor-modern text-muted">
                                            <?php echo htmlspecialchars($course['first_name'] . ' ' . $course['last_name']); ?>
                                        </p>
                                        <div class="course-meta-modern d-flex justify-content-between align-items-center">
                                            <div class="course-rating">
                                                <i class="ri ri-star-fill text-warning"></i>
                                                <span class="ms-1"><?php echo number_format((float)($course['rating'] ?? 0), 1); ?></span>
                                            </div>
                                            <div class="course-price text-primary fw-semibold">
                                                <?php echo formatPrice($course['price'], $course['currency']); ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<style>
/* TCS-inspired dashboard styles */
.hero-section {
    position: relative;
    overflow: hidden;
}

.hero-section::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 1000 100" fill="rgba(255,255,255,0.1)"><polygon points="0,0 1000,0 1000,60 0,100"/></svg>') no-repeat center bottom;
    background-size: cover;
}

.stats-card {
    background: var(--tcs-white);
    border-radius: 12px;
    padding: 1.5rem;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    border: 1px solid var(--tcs-gray-200);
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 1rem;
}

.stats-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.stats-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    background: linear-gradient(135deg, var(--tcs-primary) 0%, var(--tcs-accent) 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--tcs-white);
    font-size: 1.5rem;
    flex-shrink: 0;
}

.stats-content {
    flex: 1;
}

.stats-number {
    font-size: 2rem;
    font-weight: 700;
    color: var(--tcs-gray-800);
    margin-bottom: 0.25rem;
}

.stats-label {
    color: var(--tcs-gray-600);
    font-size: 0.9rem;
    margin-bottom: 0.5rem;
    font-weight: 500;
}

.stats-trend {
    font-size: 0.8rem;
}

.course-item-modern {
    transition: all 0.2s ease;
}

.course-item-modern:hover {
    background-color: var(--tcs-gray-50);
    transform: translateX(4px);
}

.course-thumbnail-modern img {
    width: 80px;
    height: 60px;
    object-fit: cover;
}

.achievement-item-modern {
    padding: 0.75rem;
    border-radius: 8px;
    transition: all 0.2s ease;
}

.achievement-item-modern:hover {
    background-color: var(--tcs-gray-50);
}

.achievement-icon-modern {
    width: 40px;
    height: 40px;
    border-radius: 8px;
    background: var(--tcs-gray-100);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.2rem;
    color: var(--tcs-primary);
}

.course-card-modern {
    background: var(--tcs-white);
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    border: 1px solid var(--tcs-gray-200);
}

.course-card-modern:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.course-image-modern {
    position: relative;
    height: 160px;
    overflow: hidden;
}

.course-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s ease;
}

.course-card-modern:hover .course-img {
    transform: scale(1.05);
}

.course-overlay {
    position: absolute;
    top: 12px;
    right: 12px;
}

.course-content-modern {
    padding: 1rem;
}

.course-title-modern {
    font-size: 1rem;
    font-weight: 600;
    margin-bottom: 0.5rem;
    line-height: 1.4;
}

.course-title-modern a {
    color: var(--tcs-gray-800);
}

.course-title-modern a:hover {
    color: var(--tcs-primary);
}

.course-instructor-modern {
    font-size: 0.85rem;
    margin-bottom: 0.75rem;
}

.course-meta-modern {
    margin-top: 0.75rem;
    padding-top: 0.75rem;
    border-top: 1px solid var(--tcs-gray-200);
}

.empty-state {
    padding: 3rem 1rem;
}

@media (max-width: 768px) {
    .hero-section {
        text-align: center;
        padding: 3rem 0;
    }

    .stats-card {
        padding: 1rem;
    }

    .stats-icon {
        width: 50px;
        height: 50px;
        font-size: 1.2rem;
    }

    .stats-number {
        font-size: 1.5rem;
    }
}
  </style>

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

// Helper functions
function formatLearningTime($minutes) {
    if ($minutes < 60) {
        return $minutes . ' min';
    } elseif ($minutes < 1440) {
        return round($minutes / 60, 1) . ' hrs';
    } else {
        return round($minutes / 1440, 1) . ' days';
    }
}

function getAchievementIcon($type) {
    $icons = [
        'badge' => 'ri ri-medal-line',
        'points' => 'ri ri-star-smile-line',
        'level' => 'ri ri-arrow-up-line',
        'streak' => 'ri ri-fire-line',
        'milestone' => 'ri ri-flag-line',
    ];

    return $icons[$type] ?? 'ri ri-trophy-line';
}

function formatDateAgo($date) {
    $time = strtotime($date);
    $now = time();
    $diff = $now - $time;
    
    if ($diff < 60) {
        return 'just now';
    } elseif ($diff < 3600) {
        return floor($diff / 60) . ' minutes ago';
    } elseif ($diff < 86400) {
        return floor($diff / 3600) . ' hours ago';
    } elseif ($diff < 604800) {
        return floor($diff / 86400) . ' days ago';
    } else {
        return date('M j, Y', $time);
    }
}

function formatPrice($price, $currency = 'USD') {
    $symbols = [
        'USD' => '$',
        'EUR' => '&euro;',
        'NGN' => '&#8358;'
    ];

    $symbol = $symbols[$currency] ?? $currency;

    return $symbol . number_format($price, 2);
}
?>
