<?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 and sanitize input
    $subject_id = $data["subject"] ?? null;
    $lesson = $data["lesson"] ?? null;
    $description = $data["description"] ?? null;

    // Validation checks
    if (empty($subject_id)) {
        $response["message"] = "Please select a subject!";
    } elseif (empty($lesson)) {
        $response["message"] = "Please enter lesson name!";
    } else {

        // Check if lesson already exists for this subject
        $check_rs = Database::search("SELECT * FROM `lesson` WHERE `title` = '" . $lesson . "' AND `subject_id` = '" . $subject_id . "'");
        if ($check_rs->num_rows > 0) {
            $response["status"] = false;
            $response["message"] = "This lesson already exists under the selected subject!";
        } else {
            // Set timezone and get current date-time
            $d = new DateTime();
            $tz = new DateTimeZone("Asia/Colombo");
            $d->setTimezone($tz);
            $date = $d->format("Y-m-d H:i:s");

            // Insert lesson
            Database::iud("INSERT INTO `lesson` (`subject_id`, `title`, `created_at`) 
                           VALUES ('" . $subject_id . "', '" . $lesson . "', '" . $date . "')");

            $response["status"] = true;
            $response["message"] = "Lesson added successfully!";
        }
    }

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

echo json_encode($response);
exit;
?>
