<?php
declare(strict_types=1);
require_once __DIR__ . '/../../src/bootstrap.php';

header('Content-Type: application/json; charset=utf-8');

$method = strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET'));
$action = '';
$body = [];

if ($method === 'GET') {
    $action = trim((string) ($_GET['action'] ?? 'active'));
} else {
    $raw = file_get_contents('php://input') ?: '';
    $body = json_decode($raw, true);
    if (!is_array($body)) {
        json_out(['ok' => false, 'error' => 'invalid_json'], 400);
    }
    $action = trim((string) ($body['action'] ?? ''));
}

$public = ($method === 'GET' && $action === 'session')
    || ($method === 'POST' && $action === 'join_event');

if ($method === 'POST' && in_array($action, ['create_intent', 'heartbeat'], true)) {
    $platform = strtolower(trim((string) ($body['platform'] ?? '')));
    if ($action === 'create_intent' && str_starts_with($platform, 'education')) {
        $public = true;
    }
    if ($action === 'heartbeat') {
        $sid = trim((string) ($body['session_id'] ?? ''));
        if ($sid !== '') {
            $existing = LiveCastRepository::sessionById($sid);
            $existingPlatform = strtolower((string) ($existing['platform'] ?? ''));
            if ($existing !== null && str_starts_with($existingPlatform, 'education')) {
                $public = true;
            }
        }
    }
}

if (!$public) {
    Auth::check();
}
$actor = Auth::user() ?? [];

if ($method === 'GET') {
    if ($action === 'active') {
        $platform = trim((string) ($_GET['platform'] ?? ''));
        $rows = LiveCastRepository::activeSessions($actor, $platform !== '' ? $platform : null);
        json_out(['ok' => true, 'sessions' => $rows]);
    }
    if ($action === 'analytics') {
        $days = (int) ($_GET['days'] ?? 14);
        $payload = LiveCastRepository::analytics($days, $actor);
        json_out(['ok' => true, 'data' => $payload]);
    }
    if ($action === 'list') {
        $days = (int) ($_GET['days'] ?? 14);
        $limit = (int) ($_GET['limit'] ?? 200);
        $rows = LiveCastRepository::listSessions($days, $actor, $limit);
        json_out(['ok' => true, 'sessions' => $rows]);
    }
    if ($action === 'session') {
        $sessionId = trim((string) ($_GET['session_id'] ?? ''));
        if ($sessionId === '') {
            json_out(['ok' => false, 'error' => 'missing_session_id'], 400);
        }
        $row = LiveCastRepository::publicSession($sessionId);
        if ($row === null) {
            json_out(['ok' => false, 'error' => 'not_found'], 404);
        }
        json_out(['ok' => true, 'session' => $row]);
    }
    json_out(['ok' => false, 'error' => 'unknown_action'], 400);
}

if ($method !== 'POST') {
    json_out(['ok' => false, 'error' => 'method_not_allowed'], 405);
}

if ($action === 'create_intent') {
    $row = LiveCastRepository::createIntent($body, $actor);
    if ($row === []) {
        json_out(['ok' => false, 'error' => 'create_failed'], 500);
    }
    json_out(['ok' => true, 'session' => $row]);
}

if ($action === 'heartbeat') {
    $sessionId = trim((string) ($body['session_id'] ?? ''));
    if ($sessionId === '') {
        json_out(['ok' => false, 'error' => 'missing_session_id'], 400);
    }
    $row = LiveCastRepository::heartbeat($sessionId, $body, $actor);
    if ($row === null) {
        json_out(['ok' => false, 'error' => 'not_found'], 404);
    }
    json_out(['ok' => true, 'session' => $row]);
}

if ($action === 'join_event') {
    $sessionId = trim((string) ($body['session_id'] ?? ''));
    if ($sessionId === '') {
        json_out(['ok' => false, 'error' => 'missing_session_id'], 400);
    }
    $ok = LiveCastRepository::registerJoin($sessionId, $body, $actor);
    if (!$ok) {
        json_out(['ok' => false, 'error' => 'not_found'], 404);
    }
    json_out(['ok' => true]);
}

json_out(['ok' => false, 'error' => 'unknown_action'], 400);
