<?php
header("Content-Type: application/json");
require_once __DIR__ . "/../auth/check-permission.php";
require_once __DIR__ . "/../services/db.php";
require_once __DIR__ . "/../activity/log.php";

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

if (empty($data["id"]) || empty($data["project_id"])) {
    http_response_code(400);
    echo json_encode(["error" => "Missing required task or project ID"]);
    exit;
}

// 1. Enforce project role permissions
requireProjectRole($conn, $data["project_id"], ["owner", "member"]);

// 2. Update task fields AND bump updated_at = GETDATE() to trigger real-time SSE broadcasts
$sql = "UPDATE tasks
        SET title = ?, 
            description = ?, 
            assignee_id = ?, 
            status = ?, 
            due_date = ?, 
            section_id = ?, 
            sort_order = ?,
            updated_at = GETDATE()
        WHERE id = ?";

$params = [
    $data["title"] ?? '',
    $data["description"] ?? '',
    $data["assignee_id"] ?? null,
    $data["status"] ?? 'todo',
    $data["due_date"] ?? null,
    $data["section_id"] ?? null,
    $data["sort_order"] ?? 0,
    $data["id"]
];

$stmt = sqlsrv_query($conn, $sql, $params);

if ($stmt === false) {
    http_response_code(500);
    echo json_encode(["error" => "Failed to update task", "details" => sqlsrv_errors()]);
    exit;
}

// 3. Log activity
logActivity(
    $conn,
    $data["id"],
    $data["project_id"],
    $authUser["id"] ?? $authUser["user_id"] ?? 1,
    "updated task",
    json_encode($data)
);

echo json_encode(["success" => true, "updated_at" => date('Y-m-d H:i:s')]);