<?php
session_start();
require_once 'lib/ErrorHandler.php';
register_error_handler();

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    throw new WorkflowNotAllowedException('Invalid request method.');
}

require_once 'WorkflowEngine.php';

if (!isset($_POST['instanceId']) || !isset($_POST['transitionId'])) {
    throw new WorkflowNotAllowedException('Błąd: Brak wymaganych parametrów.');
}

$instanceId = (int)$_POST['instanceId'];
$transitionId = $_POST['transitionId'];
$userId = $_SESSION['user_id'] ?? null;
$payload = $_POST['payload'] ?? [];

if (!$userId) {
    throw new WorkflowNotAllowedException('Błąd: Sesja wygasła.', [], 401);
}

$engine = new WorkflowEngine();

if ($transitionId === 'note') {
    $message = $payload['message'] ?? '';
    if (empty($message)) {
        throw new WorkflowNotAllowedException('Treść notatki nie może być pusta.');
    }
    $engine->addNote($instanceId, $message, $userId);
    $response = ['success' => true, 'message' => 'Notatka została dodana.'];
} else {
    $result = $engine->applyTransition($instanceId, $transitionId, $payload, $userId);
    $response = ['success' => true, 'message' => 'Akcja została wykonana pomyślnie.', 'data' => $result];
}

echo json_encode($response);