['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); 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(); // 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."); }