true, 'data' => $data, ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit(); } /** * Send a JSON error response. */ function api_error(string $message, int $statusCode = 400, array $details = []): void { http_response_code($statusCode); $response = [ 'success' => false, 'error' => [ 'message' => $message, 'code' => $statusCode, ], ]; if (!empty($details)) { $response['error']['details'] = $details; } echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit(); } /** * Get JSON body from request. */ function api_get_json_body(): array { $rawBody = file_get_contents('php://input'); if ($rawBody === '' || $rawBody === false) { return []; } $decoded = json_decode($rawBody, true); if (!is_array($decoded)) { return []; } return $decoded; } /** * Require specific fields in request body. */ function api_require_fields(array $body, array $fields): void { $missing = []; foreach ($fields as $field) { if (!isset($body[$field]) || (is_string($body[$field]) && trim($body[$field]) === '')) { $missing[] = $field; } } if (!empty($missing)) { api_error('Missing required fields: ' . implode(', ', $missing), 422); } }