<?php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: http://localhost:5173");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
    http_response_code(200);
    exit;
}

// INCLUDE DB CONNECTION
require_once "db.php";

// Read JSON Body
$body = json_decode(file_get_contents("php://input"), true);

if (!$body) {
    echo json_encode(["success" => false, "message" => "Invalid JSON"]);
    exit;
}

$task_name    = trim($body["task_name"] ?? "");
$project_name = trim($body["project_name"] ?? "");
$module       = trim($body["module"] ?? "");
$task_date    = $body["task_date"] ?? null;
$deadline     = $body["deadline"] ?? null;

if ($task_name === "") {
    echo json_encode(["success" => false, "message" => "Task name is required"]);
    exit;
}

try {
    $sql = "INSERT INTO tasks (task_name, project_name, module, task_date, deadline)
            VALUES (:task_name, :project_name, :module, :task_date, :deadline)";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ":task_name"    => $task_name,
        ":project_name" => $project_name ?: null,
        ":module"       => $module ?: null,
        ":task_date"    => $task_date,
        ":deadline"     => $deadline
    ]);

    echo json_encode([
        "success" => true,
        "message" => "Task created successfully",
        "id"      => $pdo->lastInsertId()
    ]);

} catch (PDOException $e) {
    echo json_encode(["success" => false, "message" => "Database error"]);
}
