<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

require("../includes/config.php");
header("Content-Type: application/json");

try {

    if (empty($_POST['chapter_id'])) {
        throw new Exception("Chapter ID missing");
    }

    if (empty($_POST['lesson_title'])) {
        throw new Exception("Lesson title missing");
    }

    if (empty($_POST['slug'])) {
        throw new Exception("Slug missing");
    }

    $imageName = null;
    if (!empty($_FILES['featured_image']['name'])) {

        if (!is_dir("../uploads/lessons")) {
            throw new Exception("Upload folder not found");
        }

        $imageName = time() . "_" . basename($_FILES['featured_image']['name']);

        if (
            !move_uploaded_file(
                $_FILES['featured_image']['tmp_name'],
                "../uploads/lessons/" . $imageName
            )
        ) {
            throw new Exception("Image upload failed");
        }
    }
    // CHECK DUPLICATE SLUG
    $check = $pdo->prepare("SELECT id FROM lessons WHERE slug = ?");
    $check->execute([$_POST['slug']]);

    if ($check->rowCount() > 0) {
        echo json_encode([
            "status" => "error",
            "message" => "Lesson URL already exists. Please change the title."
        ]);
        exit;
    }

    $stmt = $pdo->prepare("
        INSERT INTO lessons
        (chapter_id, lesson_title, slug, short_desc, video_url, featured_image,
         content, lesson_order, status, meta_title, meta_description)
        VALUES (?,?,?,?,?,?,?,?,?,?,?)
    ");

    $stmt->execute([
        $_POST['chapter_id'],
        $_POST['lesson_title'],
        $_POST['slug'],
        $_POST['short_desc'] ?? null,
        $_POST['video_url'] ?? null,
        $imageName,
        $_POST['content'],
        $_POST['lesson_order'] ?? 1,
        $_POST['status'] ?? 1,
        $_POST['meta_title'] ?? null,
        $_POST['meta_description'] ?? null
    ]);

    echo json_encode([
        "status" => "success",
        "message" => "Lesson added"
    ]);

} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode([
        "status" => "error",
        "message" => $e->getMessage()
    ]);
}
?>