<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");

require "db.php";

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

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

if (!is_array($data)) {
    echo json_encode(["status" => "error", "message" => "Invalid JSON"]);
    exit;
}

$id           = $data["id"] ?? null;
$task_name    = $data["task_name"] ?? "";
$project_name = $data["project_name"] ?? "";
$module       = $data["module"] ?? "";
$task_date    = $data["task_date"] ?? "";
$deadline     = $data["deadline"] ?? "";

if (!$id) {
    echo json_encode(["status" => "error", "message" => "Task ID missing"]);
    exit;
}

$stmt = $pdo->prepare("
    UPDATE tasks SET 
        task_name=?, 
        project_name=?, 
        module=?, 
        task_date=?, 
        deadline=?
    WHERE id=?
");

$stmt->execute([
    $task_name,
    $project_name,
    $module,
    $task_date,
    $deadline,
    $id
]);

echo json_encode([
    "status" => "success",
    "message" => "Task updated successfully"
]);
