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

try {
    $pdo = getDB();

    // Create course_lessons table
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS course_lessons (
            id INT AUTO_INCREMENT PRIMARY KEY,
            course_id INT NOT NULL,
            module_id INT NULL,
            topic_id INT NULL,
            title VARCHAR(255) NOT NULL,
            slug VARCHAR(255) NOT NULL,
            description TEXT,
            content LONGTEXT,
            lesson_type ENUM('video', 'text', 'quiz', 'assignment', 'download') DEFAULT 'text',
            video_url VARCHAR(500),
            attachment_url VARCHAR(500),
            attachment_name VARCHAR(255),
            sort_order INT DEFAULT 1,
            is_preview BOOLEAN DEFAULT FALSE,
            estimated_time INT DEFAULT 0, -- Time in minutes
            learning_objectives JSON,
            prerequisites JSON,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE,
            FOREIGN KEY (module_id) REFERENCES course_modules(id) ON DELETE CASCADE,
            FOREIGN KEY (topic_id) REFERENCES course_topics(id) ON DELETE CASCADE,
            UNIQUE KEY unique_lesson_slug (course_id, slug),
            INDEX idx_course (course_id),
            INDEX idx_module (module_id),
            INDEX idx_topic (topic_id),
            INDEX idx_sort_order (sort_order),
            INDEX idx_lesson_type (lesson_type)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");

    echo "Course lessons migration applied successfully.";
} catch (PDOException $e) {
    echo "Error applying course lessons migration: " . $e->getMessage();
}
?>