$success]; if ($success) { $response['data'] = $dataOrError; } else { $response['error'] = $dataOrError; } echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR); exit; } try { // Only POST allowed if ($_SERVER['REQUEST_METHOD'] !== 'POST') { sendResponse(false, ['code' => 'METHOD_NOT_ALLOWED', 'message' => 'Only POST requests are allowed.'], 405); } // Read JSON input $input = file_get_contents('php://input'); $data = json_decode($input, true); if (json_last_error() !== JSON_ERROR_NONE) { sendResponse(false, ['code' => 'INVALID_JSON', 'message' => 'Invalid JSON input.'], 400); } // Validate action $action = $data['action'] ?? null; if (!$action) { sendResponse(false, ['code' => 'MISSING_ACTION', 'message' => 'Action is required.'], 400); } // Check X-User-ID header (except for initSession if we want to allow it) $userId = $_SERVER['HTTP_X_USER_ID'] ?? null; if (!$userId && $action !== 'initSession') { sendResponse(false, ['code' => 'UNAUTHORIZED', 'message' => 'X-User-ID header is missing.'], 401); } // Router $projectActions = new \App\Actions\ProjectActions(); $consentService = new \App\Services\ConsentService(); switch ($action) { case 'ping': sendResponse(true, ['message' => 'pong', 'timestamp' => time()]); break; case 'initSession': sendResponse(true, $projectActions->initSession()); break; case 'createProject': sendResponse(true, $projectActions->createProject($userId)); break; case 'listProjects': sendResponse(true, $projectActions->listProjects($userId)); break; case 'getProjectStatus': $projectId = $data['project_id'] ?? null; if (!$projectId) { sendResponse(false, ['code' => 'MISSING_PROJECT_ID', 'message' => 'Project ID is required.'], 400); } sendResponse(true, $projectActions->getProjectStatus($userId, $projectId)); break; case 'saveConsent': $projectId = $data['project_id'] ?? null; $consentText = $data['payload']['consent_text'] ?? null; if (!$projectId || !$consentText) { sendResponse(false, ['code' => 'MISSING_DATA', 'message' => 'Project ID and consent text are required.'], 400); } $success = $consentService->saveConsent($projectId, $userId, $consentText); sendResponse($success, ['message' => 'Consent saved successfully.']); break; default: sendResponse(false, ['code' => 'UNKNOWN_ACTION', 'message' => "Action '$action' is not defined."], 404); break; } } catch (Throwable $e) { sendResponse(false, [ 'code' => 'INTERNAL_SERVER_ERROR', 'message' => $e->getMessage() ], 500); }