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

$courseId = 15;
$db = getDB();

echo "=== Course 15 Diagnostics ===\n";

// Check if course exists
$stmt = $db->prepare('SELECT id, title, status FROM courses WHERE id = ?');
$stmt->execute([$courseId]);
$course = $stmt->fetch();
echo "Course: " . ($course ? "Found '{$course['title']}' (status: {$course['status']})\n" : 'NOT FOUND') . "\n";

// Modules
$stmt = $db->prepare('SELECT COUNT(*) FROM course_modules WHERE course_id = ?');
$stmt->execute([$courseId]);
$modules = $stmt->fetchColumn();
echo "Modules count: $modules\n";

// Topics
$stmt = $db->prepare('SELECT COUNT(*) FROM course_topics WHERE module_id IN (SELECT id FROM course_modules WHERE course_id = ?)');
$stmt->execute([$courseId]);
$topics = $stmt->fetchColumn();
echo "Topics count: $topics\n";

// Lessons
$stmt = $db->prepare('SELECT COUNT(*) FROM course_lessons WHERE course_id = ?');
$stmt->execute([$courseId]);
$lessons = $stmt->fetchColumn();
echo "Lessons count: $lessons\n";

// Enrollment
$stmt = $db->prepare('SELECT id FROM course_enrollments WHERE course_id = ?');
$stmt->execute([$courseId]);
$enrollment = $stmt->fetch();
echo "Enrollment: " . ($enrollment ? 'EXISTS' : 'NOT FOUND') . "\n";

// Full hierarchy query test
$stmt = $db->prepare("
    SELECT cm.id as module_id, ct.id as topic_id, cl.id as lesson_id
    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))
    WHERE cm.course_id = ?
");
$stmt->execute([$courseId]);
$hierarchy = $stmt->fetchAll();
echo "Hierarchy rows: " . count($hierarchy) . "\n";

foreach ($hierarchy as $row) {
    echo "- Module: " . ($row['module_id'] ?? 'null') . ", Topic: " . ($row['topic_id'] ?? 'null') . ", Lesson: " . ($row['lesson_id'] ?? 'null') . "\n";
}

echo "\n=== END ===\n";
?>

