<?php
require_once __DIR__ . '/config.php';

// Only authenticated Spaceship users may request temporary TURN credentials.
$me = must_auth();

$keyId = defined('CLOUDFLARE_TURN_KEY_ID') ? trim((string)CLOUDFLARE_TURN_KEY_ID) : '';
$apiToken = defined('CLOUDFLARE_TURN_API_TOKEN') ? trim((string)CLOUDFLARE_TURN_API_TOKEN) : '';
$ttl = defined('CLOUDFLARE_TURN_TTL') ? (int)CLOUDFLARE_TURN_TTL : 86400;

if ($keyId === '' || $apiToken === '') {
    fail('Cloudflare TURN is not configured. Set CLOUDFLARE_TURN_KEY_ID and CLOUDFLARE_TURN_API_TOKEN in api/config.php.', 500);
}

// Cloudflare currently allows TURN credential expiry up to 48 hours.
if ($ttl < 300) $ttl = 300;
if ($ttl > 172800) $ttl = 172800;

if (!function_exists('curl_init')) {
    fail('PHP cURL extension is not enabled. Enable extension=curl in php.ini, then restart Apache.', 500);
}

$url = 'https://rtc.live.cloudflare.com/v1/turn/keys/' . rawurlencode($keyId) . '/credentials/generate-ice-servers';
$payload = json_encode(array('ttl' => $ttl));

$ch = curl_init($url);
curl_setopt_array($ch, array(
    CURLOPT_POST           => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => array(
        'Authorization: Bearer ' . $apiToken,
        'Content-Type: application/json'
    ),
    CURLOPT_POSTFIELDS     => $payload,
    CURLOPT_TIMEOUT        => 15
));

$response = curl_exec($ch);
$error = curl_error($ch);
$httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($response === false) {
    fail('Cloudflare TURN request failed: ' . $error, 502);
}

$data = json_decode($response, true);
if ($httpCode < 200 || $httpCode >= 300 || !is_array($data)) {
    fail('Cloudflare TURN returned HTTP ' . $httpCode . ': ' . $response, 502);
}

$iceServers = array();
if (isset($data['iceServers']) && is_array($data['iceServers'])) {
    $iceServers = $data['iceServers'];
} elseif (isset($data['result']['iceServers']) && is_array($data['result']['iceServers'])) {
    $iceServers = $data['result']['iceServers'];
}

if (!$iceServers) {
    fail('Cloudflare TURN response did not contain iceServers.', 502);
}

// Port 53 entries can time out in browsers, so remove them for faster call setup.
foreach ($iceServers as &$server) {
    if (isset($server['urls'])) {
        $urls = is_array($server['urls']) ? $server['urls'] : array($server['urls']);
        $filtered = array();
        foreach ($urls as $u) {
            if (!preg_match('/:(53)(\\?|$)/', (string)$u)) {
                $filtered[] = $u;
            }
        }
        $server['urls'] = $filtered;
    }
}
unset($server);

$iceServers = array_values(array_filter($iceServers, function ($server) {
    return isset($server['urls']) && is_array($server['urls']) && count($server['urls']) > 0;
}));

echo json_encode($iceServers);
