<?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;
$message = $_POST['message'] ?? null;
$userId = $_SESSION['user_id'];

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

$workflowEngine = new WorkflowEngine();
$workflowEngine->addNote((int)$instanceId, $message, (int)$userId);

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