<?php
/**
 * SmartThink3 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');
}

// 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 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,
               (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
        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);
}

$pageTitle = "Student Dashboard";
include __DIR__ . '/includes/header.php';
?>

<!-- Hero Section -->
<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 gap-3">
                    <a href="courses.php" class="btn btn-light btn-lg px-4">
                        <i class="fas fa-search me-2"></i>Browse Courses
                    </a>
                    <a href="profile.php" class="btn btn-outline-light btn-lg px-4">
                        <i class="fas fa-user 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>

<!-- Stats Overview -->
<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="fas fa-book-open"></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="fas fa-arrow-up 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="fas fa-award"></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="fas fa-clock"></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="fas fa-fire 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="fas fa-star"></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="fas fa-medal me-1"></i>
                            <?php echo number_format((int)($stats['achievements']['badges'] ?? 0)); ?> badges
                        </small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Progress Overview -->
<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>

<!-- Main Content Grid -->
<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="course.php?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="course.php?id=<?php echo $enrollment['course_id']; ?>" class="btn btn-primary btn-sm">
                                                <i class="fas fa-play me-1"></i>Continue
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="empty-state text-center py-5">
                            <div class="empty-icon mb-3">
                                <i class="fas fa-graduation-cap fa-3x 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">
            <!-- 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="fas fa-<?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="fas fa-trophy fa-2x 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="fas fa-search me-2"></i>Browse Courses
                        </a>
                        <a href="certificates.php" class="btn btn-outline-success d-flex align-items-center">
                            <i class="fas fa-certificate me-2"></i>My Certificates
                        </a>
                        <a href="profile.php" class="btn btn-outline-info d-flex align-items-center">
                            <i class="fas fa-user me-2"></i>My Profile
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Recommended Courses -->
<?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="course.php?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="fas fa-star 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
// 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' => 'medal',
        'points' => 'star',
        'level' => 'arrow-up',
        'streak' => 'fire',
        'milestone' => 'flag'
    ];
    
    return $icons[$type] ?? 'trophy';
}

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' => '€',
        'NGN' => '₦'
    ];
    
    $symbol = $symbols[$currency] ?? $currency;
    
    if ($currency === 'NGN') {
        return $symbol . number_format($price, 2);
    } else {
        return $symbol . number_format($price, 2);
    }
}

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