<?php
if (!function_exists('smurf_get_stream_config')) {
function smurf_get_stream_config(): array {
    $settingsFile = dirname(__DIR__) . '/data/settings.json';
    $settings = [];
    if (is_file($settingsFile)) {
        $settings = json_decode((string)file_get_contents($settingsFile), true);
        if (!is_array($settings)) $settings = [];
    }
    $host = trim((string)($settings['stream_host'] ?? 'radio.undergroundfxradio.com'));
    $port = trim((string)($settings['stream_port'] ?? '9000'));
    $mount = trim((string)($settings['stream_mount'] ?? '/stream'));
    if ($mount === '') $mount = '/stream';
    if ($mount[0] !== '/') $mount = '/' . $mount;
    return [
        'server_ip' => $host,
        'server_port' => $port,
        'admin_user' => trim((string)($settings['admin_user'] ?? 'admin')),
        'admin_password' => trim((string)($settings['admin_password'] ?? 'TxHL7RqdSjQbSB')),
        'mount_main' => $mount,
        'mount_auto' => '/autodj',
        'mount_backup' => '/live',
        'listen_url' => trim((string)($settings['stream_url'] ?? ('http://' . $host . ':' . $port . $mount))),
        'status_json_url' => 'http://' . $host . ':' . $port . '/status-json.xsl',
        'seven_html_url' => 'http://' . $host . ':' . $port . '/7.html',
    ];
}
}

if (!function_exists('smurf_http_get')) {
function smurf_http_get(string $url, array $headers = [], int $timeout = 6, ?string $user = null, ?string $pass = null): string {
    if ($url === '') return '';
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        $opts = [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_CONNECTTIMEOUT => min(4, $timeout),
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_FAILONERROR => false,
            CURLOPT_HTTPHEADER => $headers,
        ];
        if ($user !== null && $pass !== null) {
            $opts[CURLOPT_HTTPAUTH] = CURLAUTH_BASIC;
            $opts[CURLOPT_USERPWD] = $user . ':' . $pass;
        }
        curl_setopt_array($ch, $opts);
        $raw = curl_exec($ch);
        $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if (is_string($raw) && trim($raw) !== '' && $code < 500) return $raw;
    }
    $headerText = '';
    if ($user !== null && $pass !== null) {
        $headers[] = 'Authorization: Basic ' . base64_encode($user . ':' . $pass);
    }
    if ($headers) $headerText = implode("\r\n", $headers) . "\r\n";
    $ctx = stream_context_create(['http' => ['timeout' => $timeout, 'ignore_errors' => true, 'header' => $headerText]]);
    $raw = @file_get_contents($url, false, $ctx);
    return is_string($raw) ? $raw : '';
}
}

if (!function_exists('smurf_fetch_icecast_xml')) {
function smurf_fetch_icecast_xml(): string {
    $cfg = smurf_get_stream_config();
    foreach ([
        'http://' . $cfg['server_ip'] . ':' . $cfg['server_port'] . '/admin/stats',
        'http://' . $cfg['server_ip'] . ':' . $cfg['server_port'] . '/admin/stats.xml',
    ] as $url) {
        $raw = smurf_http_get($url, ['Accept: application/xml, text/xml, */*'], 6, $cfg['admin_user'], $cfg['admin_password']);
        if (trim($raw) !== '') return $raw;
    }
    return '';
}
}

if (!function_exists('smurf_parse_icecast_data')) {
function smurf_parse_icecast_data(string $xml): array {
    $result = ['global' => [], 'sources' => []];
    if (trim($xml) === '') return $result;
    libxml_use_internal_errors(true);
    $sx = @simplexml_load_string($xml);
    if (!$sx) { libxml_clear_errors(); return $result; }
    $result['global'] = [
        'listeners' => isset($sx->listeners) ? (int)$sx->listeners : 0,
        'listener_connections' => isset($sx->listener_connections) ? (int)$sx->listener_connections : 0,
        'clients' => isset($sx->clients) ? (int)$sx->clients : 0,
        'sources' => isset($sx->sources) ? (int)$sx->sources : 0,
        'host' => trim((string)($sx->host ?? '')),
        'server_id' => trim((string)($sx->server_id ?? '')),
        'server_start' => trim((string)($sx->server_start_iso8601 ?? $sx->server_start ?? '')),
    ];
    foreach ($sx->source ?? [] as $source) {
        $mount = trim((string)$source['mount']);
        $title = trim((string)($source->title ?? $source->artist ?? ''));
        if ($title === '' && isset($source->x_icy_title)) $title = trim((string)$source->x_icy_title);
        $result['sources'][] = [
            'mount' => $mount,
            'title' => html_entity_decode($title, ENT_QUOTES, 'UTF-8'),
            'listeners' => isset($source->listeners) ? (int)$source->listeners : 0,
            'server_name' => trim((string)($source->server_name ?? '')),
            'listenurl' => trim((string)($source->listenurl ?? '')),
            'is_active' => trim((string)($source->server_name ?? '')) !== '' || trim((string)($source->title ?? '')) !== '' || (int)($source->listeners ?? 0) > 0,
        ];
    }
    libxml_clear_errors();
    return $result;
}
}

if (!function_exists('smurf_parse_icecast_sources')) {
function smurf_parse_icecast_sources(string $xml): array {
    $parsed = smurf_parse_icecast_data($xml);
    return $parsed['sources'] ?? [];
}
}

if (!function_exists('smurf_pick_preferred_source')) {
function smurf_pick_preferred_source(array $sources): ?array {
    if (!$sources) return null;
    $cfg = smurf_get_stream_config();
    $mounts = [$cfg['mount_main'], $cfg['mount_auto'], $cfg['mount_backup']];
    foreach ($mounts as $mount) {
        foreach ($sources as $source) {
            if (($source['mount'] ?? '') === $mount && trim((string)($source['title'] ?? '')) !== '') return $source;
        }
    }
    foreach ($sources as $source) if (trim((string)($source['title'] ?? '')) !== '') return $source;
    return $sources[0] ?? null;
}
}

if (!function_exists('smurf_get_preferred_source')) {
function smurf_get_preferred_source(): ?array {
    $xml = smurf_fetch_icecast_xml();
    if ($xml === '') return null;
    return smurf_pick_preferred_source(smurf_parse_icecast_sources($xml));
}
}

if (!function_exists('smurf_get_nowplaying_title')) {
function smurf_get_nowplaying_title(): string {
    $source = smurf_get_preferred_source();
    return trim((string)($source['title'] ?? ''));
}
}

if (!function_exists('smurf_get_global_listener_count')) {
function smurf_get_global_listener_count(): int {
    $xml = smurf_fetch_icecast_xml();
    if ($xml === '') return 0;
    $parsed = smurf_parse_icecast_data($xml);
    return (int)($parsed['global']['listener_connections'] ?? ($parsed['global']['listeners'] ?? 0));
}
}
