<?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);

    $subject = $data["subject"] ?? null;
    $course = $data["course"] ?? null;
    $price = $data["price"] ?? null;

    if (empty($course)) {
        $response["message"] = "Please Select Course";
    } else if (empty($subject)) {
        $response["message"] = "Please Enter Subject Name";
    }else if(empty($price)){
        $response["message"] = "Please Enter Price";
    } else {


        $check_rs = Database::search("SELECT * FROM `subject` WHERE `title` = '" . $subject . "' AND `course_id` = '" . $course . "'");
        if ($check_rs->num_rows > 0) {
            $response["status"] = false;
            $response["message"] = "This Subject Already Exists!";
        } else {

            $d = new DateTime();
            $tz = new DateTimeZone("Asia/Colombo");
            $d->setTimezone($tz);
            $date = $d->format("Y-m-d H:i:s");

            Database::iud("INSERT INTO `subject` ( `course_id`,`title`,`price`,`created_at`) 
            VALUES ( '" . $course . "','" . $subject . "','".$price."','".$date."')");

            $response["status"] = true;
            $response["message"] = "Subject Added Successfully!";
        }
    }
} catch (Exception $e) {
    $response["status"] = false;
    $response["message"] = $e->getMessage();
}

echo json_encode($response);
exit;
