39481-vm/api/channels.php
Flatlogic Bot cc09913585 v2
2026-04-05 11:27:52 +00:00

75 lines
2.7 KiB
PHP

<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../app/channel_data.php';
function respond(int $status, array $payload): void
{
http_response_code($status);
echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
channel_app_bootstrap();
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$userId = channel_current_user_id();
try {
if ($method === 'GET') {
if (isset($_GET['stats'])) {
respond(200, ['success' => true, 'data' => channel_stats()]);
}
if (isset($_GET['history_for'])) {
respond(200, ['success' => true, 'data' => channel_history((int) $_GET['history_for'])]);
}
if (isset($_GET['id'])) {
$channel = channel_get((int) $_GET['id']);
if (!$channel) {
respond(404, ['success' => false, 'error' => 'Channel not found.']);
}
respond(200, ['success' => true, 'data' => $channel, 'meta' => [
'editable_fields' => CHANNEL_EDITABLE_FIELDS,
'locked_fields' => CHANNEL_LOCKED_FIELDS,
'options' => channel_distinct_options(CHANNEL_FILTER_OPTION_FIELDS),
]]);
}
respond(200, ['success' => true, 'data' => channel_list($_GET)]);
}
$rawBody = file_get_contents('php://input');
$payload = $rawBody ? json_decode($rawBody, true) : [];
if (!is_array($payload)) {
$payload = [];
}
if ($method === 'PATCH') {
if (isset($_GET['bulk'])) {
$result = channel_bulk_patch($payload['ids'] ?? [], $payload['fields'] ?? [], $userId);
respond(200, ['success' => true, 'message' => 'Bulk update applied.', 'data' => $result]);
}
if (!isset($_GET['id'])) {
respond(400, ['success' => false, 'error' => 'Missing channel id.']);
}
$result = channel_patch((int) $_GET['id'], $payload['fields'] ?? $payload, $userId);
respond(200, ['success' => true, 'message' => 'Channel updated.', 'data' => $result]);
}
respond(405, ['success' => false, 'error' => 'Method not allowed.']);
} catch (RuntimeException $e) {
if (str_starts_with($e->getMessage(), 'FORBIDDEN_FIELD:')) {
respond(403, ['success' => false, 'error' => 'Attempted to modify a locked system field.']);
}
respond(500, ['success' => false, 'error' => $e->getMessage() ?: 'Unexpected runtime error.']);
} catch (InvalidArgumentException $e) {
respond(422, ['success' => false, 'error' => $e->getMessage()]);
} catch (Throwable $e) {
respond(500, ['success' => false, 'error' => 'Unexpected server error.']);
}