<?php
session_start();
include "connection.php";
include "validation.php";

header("Content-Type: application/json");

$response = [
    "status" => false,
    "message" => ""
];

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

    // Extract input values
    $subject_id = $data["subject_id"] ?? null;
    $lesson_id = $data["lesson_id"] ?? null;
    $lesson = $data["lesson"] ?? null;

    // Validation
    if (empty($subject_id)) {
        $response["message"] = "Please select subject!";
    } elseif (empty($lesson)) {
        $response["message"] = "Please enter lesson name!";
    } elseif (empty($lesson_id)) {
        $response["message"] = "Lesson ID is missing!";
    } else {
        // Check if lesson exists
        $check_rs = Database::search("SELECT * FROM `lesson` WHERE `id` = '" . $lesson_id . "'");
        if ($check_rs->num_rows > 0) {

            try {
                // Update lesson
                Database::iud("UPDATE `lesson`  SET `subject_id` = '" . $subject_id . "', `title` = '" . $lesson . "'  WHERE `id` = '" . $lesson_id . "'");
 
                $response["status"] = true;
                $response["message"] = "Lesson updated successfully!";
            } catch (Exception $e) {
                $response["status"] = false;
                $response["message"] = $e->getMessage();
            }

        } else {
            $response["status"] = false;
            $response["message"] = "Lesson not found!";
        }
    }

} catch (Exception $e) {
    $response["status"] = false;
    $response["message"] = "Error: " . $e->getMessage();
}

echo json_encode($response);
exit;
?>
