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

$db = getDB();
$courseId = 14;
$userId = 4;

// Get course details
$stmt = $db->prepare("
    SELECT c.*, cat.name as category_name,
           COUNT(DISTINCT cl.id) as total_lessons
    FROM courses c
    LEFT JOIN course_categories cat ON c.category_id = cat.id
    LEFT JOIN course_lessons cl ON c.id = cl.course_id
    WHERE c.id = ? AND c.status = 'published'
    GROUP BY c.id
");
$stmt->execute([$courseId]);
$course = $stmt->fetch(PDO::FETCH_ASSOC);
echo "Course: ";
print_r($course);

// Check enrollment
$stmt = $db->prepare("
    SELECT * FROM course_enrollments
    WHERE course_id = ? AND student_id = ?
");
$stmt->execute([$courseId, $userId]);
$enrollment = $stmt->fetch(PDO::FETCH_ASSOC);
echo "\nEnrollment: ";
print_r($enrollment);

if (!$enrollment) {
    echo "No enrollment!";
    exit;
}

// Get course lessons
$stmt = $db->prepare("
    SELECT cl.*,
           COALESCE(clp.status, 'not_started') as progress_status,
           clp.completed_at,
           clp.time_spent,
           ct.id as topic_id,
           ct.title as topic_name,
           ct.sort_order as topic_sort_order,
           cm.id as module_id,
           cm.title as module_name,
           cm.sort_order as module_sort_order
    FROM course_modules cm
    LEFT JOIN course_topics ct ON cm.id = ct.module_id
    LEFT JOIN course_lessons cl ON (ct.id = cl.topic_id OR (cl.topic_id IS NULL AND cl.module_id = cm.id))
    LEFT JOIN course_lesson_progress clp ON cl.id = clp.lesson_id AND clp.enrollment_id = ?
    WHERE cm.course_id = ?
    ORDER BY cm.sort_order ASC, ct.sort_order ASC, cl.sort_order ASC
");
$stmt->execute([$enrollment['id'], $courseId]);
$lessons = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo "\nLessons count: " . count($lessons) . "\n";
echo "First lesson: ";
print_r($lessons[0] ?? 'none');

// Build curriculum
$curriculum = [];
$processedLessonIds = [];

foreach ($lessons as $lesson) {
    $lessonId = $lesson['id'];
    
    if ($lessonId && in_array($lessonId, $processedLessonIds)) {
        continue;
    }
    if ($lessonId) {
        $processedLessonIds[] = $lessonId;
    }
    
    $moduleId = $lesson['module_id'] ?? 'general';
    $topicId = $lesson['topic_id'] ?? 'general';

    if (!isset($curriculum[$moduleId])) {
        $curriculum[$moduleId] = [
            'id' => $lesson['module_id'],
            'title' => $lesson['module_name'] ?? 'General',
            'sort_order' => $lesson['module_sort_order'] ?? 9999,
            'topics' => []
        ];
    }

    if (!isset($curriculum[$moduleId]['topics'][$topicId])) {
        $curriculum[$moduleId]['topics'][$topicId] = [
            'id' => $lesson['topic_id'],
            'title' => $lesson['topic_name'] ?? 'General',
            'sort_order' => $lesson['topic_sort_order'] ?? 9999,
            'lessons' => []
        ];
    }

    $curriculum[$moduleId]['topics'][$topicId]['lessons'][] = $lesson;
}

echo "\n\nCurriculum modules: " . count($curriculum) . "\n";
echo "Curriculum: ";
print_r($curriculum);