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

$data = json_decode(file_get_contents("php://input"), true);

$lesson_id = isset($data['lesson_id']) ? (int)$data['lesson_id'] : 0;
$lesson_title = $data['lesson_title'] ?? '';
$slug = $data['slug'] ?? '';
$short_desc = $data['short_desc'] ?? '';
$video_url = $data['video_url'] ?? '';
$content = $data['content'] ?? '';  // Content from Summernote
$lesson_order = isset($data['lesson_order']) ? (int)$data['lesson_order'] : 1;
$status = isset($data['status']) ? (int)$data['status'] : 0;
$meta_title = $data['meta_title'] ?? '';
$meta_description = $data['meta_description'] ?? '';
$chapter_id = isset($data['chapter_id']) ? (int)$data['chapter_id'] : 0;

if ($lesson_id <= 0) {
    echo json_encode(["status" => "error", "message" => "Invalid lesson ID"]);
    exit;
}

try {
    // Prepare the SQL update query
    $stmt = $pdo->prepare("
        UPDATE lessons
        SET lesson_title = ?, slug = ?, short_desc = ?, video_url = ?, content = ?, lesson_order = ?, status = ?, meta_title = ?, meta_description = ?, chapter_id = ?
        WHERE id = ?
    ");

    // Execute the update query with the provided data
    $stmt->execute([
        $lesson_title,
        $slug,
        $short_desc,
        $video_url,
        $content,
        $lesson_order,
        $status,
        $meta_title,
        $meta_description,
        $chapter_id,
        $lesson_id
    ]);

    echo json_encode(["status" => "success", "message" => "Lesson updated successfully"]);
} catch (Exception $e) {
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}
?>
