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

require_once 'db/config.php';
require_once 'WorkflowEngine.php';

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

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

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => ['message' => 'Authentication required.']]);
    exit;
}

$userId = $_SESSION['user_id'];
$personId = filter_input(INPUT_POST, 'person_id', FILTER_VALIDATE_INT);
$processDefinitionId = filter_input(INPUT_POST, 'process_id', FILTER_VALIDATE_INT);
$deleteExisting = filter_input(INPUT_POST, 'delete_existing');

if (!$personId || !$processDefinitionId) {
    // InvalidArgumentException will be caught by the handler and result in a 400 Bad Request
    throw new InvalidArgumentException('Invalid or missing person_id or process_id.');
}

$engine = new WorkflowEngine();

if($deleteExisting === '1') {
    $instance = $engine->getInstanceByDefId($personId, $processDefinitionId);
    if ($instance) {
        $engine->deleteInstance($instance['id']);
    }
}

// The getOrCreateInstanceByDefId method is now responsible for all checks:
// 1. Validating the process definition exists.
// 2. Checking if the process is active.
// 3. Checking if the person is eligible.
// 4. Creating the instance if it doesn't exist.
// It will throw specific exceptions (WorkflowNotFoundException, WorkflowNotAllowedException, WorkflowEligibilityException) which our ErrorHandler will turn into 404, 409, and 422 responses.
$instance = $engine->getOrCreateInstanceByDefId($personId, $processDefinitionId, $userId);

if ($instance) {
    echo json_encode(['success' => true, 'message' => 'Process initialized successfully.', 'instance_id' => $instance['id']]);
} else {
    // This case should not be reached if the engine works as expected, as failures should throw exceptions.
    throw new Exception("Failed to initialize process for an unknown reason.");
}