<?php
require_once 'lib/ErrorHandler.php';
require_once 'WorkflowEngine.php';

session_start();

if (!isset($_SESSION['user_id'])) {
    throw new WorkflowNotAllowedException('Unauthorized');
}

$instanceId = $_POST['instance_id'] ?? null;
$status = $_POST['status'] ?? null;
$reason = $_POST['reason'] ?? '';
$userId = $_SESSION['user_id'];

if (!$instanceId || !$status) {
    throw new WorkflowRuleFailedException('Missing parameters: instance_id and status are required.');
}

$workflowEngine = new WorkflowEngine();
$workflowEngine->applyManualStatus((int)$instanceId, $status, $reason, (int)$userId);

if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false) {
    header('Content-Type: application/json');
    echo json_encode(['message' => 'Status updated successfully.']);
} else {
    header('Location: index.php');
}
exit;
