<?php
require "../config/database.php";
require "../includes/auth.php";
require "../includes/csrf.php";
require "../includes/rbac.php";

header("Content-Type: application/json; charset=utf-8");
requireApiAuth();

if (!hasPermission("manage_workers")) {
    http_response_code(403);
    echo json_encode(["success" => false, "error" => "forbidden"]);
    exit;
}

$data = json_decode(file_get_contents("php://input"), true);
if (!is_array($data)) {
    http_response_code(400);
    echo json_encode(["success" => false, "error" => "invalid_payload"]);
    exit;
}

requireCsrf($data["csrf"] ?? null);

$workerId = (int)($data["id"] ?? 0);
$status = trim((string)($data["status"] ?? ""));

$allowedStatuses = ["slobodan", "pregovori", "zaposlen"];
if ($workerId <= 0 || !in_array($status, $allowedStatuses, true)) {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "invalid_worker_or_status"]);
    exit;
}

$stmt = $pdo->prepare("UPDATE workers SET status = ?, updated_at = NOW() WHERE id = ?");
$stmt->execute([$status, $workerId]);

echo json_encode(["success" => true]);
