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

session_start();

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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    throw new WorkflowNotAllowedException('Method Not Allowed');
}

$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    throw new WorkflowRuleFailedException('Invalid JSON');
}

$instanceId = $input['instance_id'] ?? null;
$taskCode = $input['task_code'] ?? null;
$isChecked = $input['is_checked'] ?? null;
$userId = $_SESSION['user_id'];

if (!$instanceId || !$taskCode || $isChecked === null) {
    throw new WorkflowRuleFailedException('Missing required parameters: instance_id, task_code, is_checked');
}

$workflowEngine = new WorkflowEngine();
$result = $workflowEngine->updateChecklistStatus((int)$instanceId, $taskCode, (bool)$isChecked, (int)$userId);
echo json_encode($result);
exit;