<?php
if (!function_exists('ugfx_get_stream_config')) {
function ugfx_get_stream_config(): array {
    $cfg = [
        'server_ip' => 'cr2.broadcasturself.com',
        'server_port' => '9000',
        'admin_user' => 'UndergroundFx',
        'admin_password' => 'TxHL7RqdSjQbSB',
        'mount_main' => '/stream',
        'mount_auto' => '/autodj',
        'mount_backup' => '/stream2',
        'listen_url' => 'http://radio.undergroundfxradio.com:9000/stream',
        'stats_url' => 'http://cr2.broadcasturself.com:9000/admin/stats',
        'stats_xsl_url' => 'http://cr2.broadcasturself.com:9000/admin/stats.xsl?showall=true',
    ];

    $settingsFile = dirname(__DIR__) . '/data/settings.json';
    if (is_file($settingsFile)) {
        $settings = json_decode((string)file_get_contents($settingsFile), true);
        if (is_array($settings)) {
            if (!empty($settings['public_stream_url'])) {
                $cfg['listen_url'] = trim((string)$settings['public_stream_url']);
            } elseif (!empty($settings['stream_url'])) {
                $cfg['listen_url'] = trim((string)$settings['stream_url']);
            }
            if (!empty($settings['stats_url'])) $cfg['stats_url'] = trim((string)$settings['stats_url']);
            if (!empty($settings['stats_xsl_url'])) $cfg['stats_xsl_url'] = trim((string)$settings['stats_xsl_url']);
            if (!empty($settings['stats_user'])) $cfg['admin_user'] = trim((string)$settings['stats_user']);
            if (!empty($settings['stats_password'])) $cfg['admin_password'] = trim((string)$settings['stats_password']);
            if (!empty($settings['stats_mount'])) $cfg['mount_main'] = ugfx_normalize_mount((string)$settings['stats_mount']);
        }
    }

    $listenParts = @parse_url($cfg['listen_url']);
    if (is_array($listenParts)) {
        $listenMount = ugfx_normalize_mount((string)($listenParts['path'] ?? ''));
        if ($listenMount !== '/') {
            $cfg['mount_main'] = $listenMount;
            if ($cfg['mount_auto'] === $cfg['mount_main']) {
                $cfg['mount_auto'] = ($cfg['mount_main'] === '/stream') ? '/autodj' : '/stream';
            }
        }
    }

    return $cfg;
}
}

if (!function_exists('ugfx_normalize_mount')) {
function ugfx_normalize_mount(string $mount): string {
    $mount = trim($mount);
    if ($mount === '') return '/stream';
    return '/' . ltrim($mount, '/');
}
}

if (!function_exists('ugfx_get_stats_urls')) {
function ugfx_get_stats_urls(): array {
    $cfg = ugfx_get_stream_config();
    $urls = [];
    foreach (['stats_url', 'stats_xsl_url'] as $key) {
        $url = trim((string)($cfg[$key] ?? ''));
        if ($url !== '') $urls[] = $url;
    }
    $hostname = trim((string)($cfg['server_ip'] ?? ''));
    $port = trim((string)($cfg['server_port'] ?? ''));
    if ($hostname !== '' && $port !== '') {
        $urls[] = "http://{$hostname}:{$port}/admin/stats";
        $urls[] = "http://{$hostname}:{$port}/admin/stats.xml";
        $urls[] = "http://{$hostname}:{$port}/admin/stats.xsl?showall=true";
    }
    return array_values(array_unique($urls));
}
}

if (!function_exists('ugfx_fetch_icecast_xml')) {
function ugfx_fetch_icecast_xml(): string {
    $cfg = ugfx_get_stream_config();
    $user = (string)($cfg['admin_user'] ?? '');
    $pass = (string)($cfg['admin_password'] ?? '');
    if ($user === '' || $pass === '') return '';
    foreach (ugfx_get_stats_urls() as $url) {
        if (stripos($url, 'stats.xsl') !== false) continue;
        if (function_exists('curl_init')) {
            $ch = curl_init($url);
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
                CURLOPT_USERPWD => $user . ':' . $pass,
                CURLOPT_TIMEOUT => 6,
                CURLOPT_CONNECTTIMEOUT => 4,
                CURLOPT_FAILONERROR => false,
                CURLOPT_HTTPHEADER => ['Accept: application/xml, text/xml, */*'],
            ]);
            $raw = curl_exec($ch);
            $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            if (is_string($raw) && trim($raw) !== '' && $code < 400 && strpos(ltrim($raw), '<') === 0) return $raw;
        }
        $ctx = stream_context_create(['http' => [
            'timeout' => 6,
            'ignore_errors' => true,
            'header' => "Authorization: Basic " . base64_encode($user . ':' . $pass) . "
" .
                        "Accept: application/xml, text/xml, */*
",
        ]]);
        $raw = @file_get_contents($url, false, $ctx);
        if (is_string($raw) && trim($raw) !== '' && strpos(ltrim($raw), '<') === 0) return $raw;
    }
    return '';
}
}

if (!function_exists('ugfx_fetch_icecast_xsl')) {
function ugfx_fetch_icecast_xsl(): string {
    $cfg = ugfx_get_stream_config();
    $user = (string)($cfg['admin_user'] ?? '');
    $pass = (string)($cfg['admin_password'] ?? '');
    if ($user === '' || $pass === '') return '';
    foreach (ugfx_get_stats_urls() as $url) {
        if (stripos($url, 'stats.xsl') === false) continue;
        if (function_exists('curl_init')) {
            $ch = curl_init($url);
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
                CURLOPT_USERPWD => $user . ':' . $pass,
                CURLOPT_TIMEOUT => 6,
                CURLOPT_CONNECTTIMEOUT => 4,
                CURLOPT_FAILONERROR => false,
                CURLOPT_HTTPHEADER => ['Accept: text/html, */*'],
            ]);
            $raw = curl_exec($ch);
            $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            if (is_string($raw) && trim($raw) !== '' && $code < 400) return $raw;
        }
        $ctx = stream_context_create(['http' => [
            'timeout' => 6,
            'ignore_errors' => true,
            'header' => "Authorization: Basic " . base64_encode($user . ':' . $pass) . "
" .
                        "Accept: text/html, */*
",
        ]]);
        $raw = @file_get_contents($url, false, $ctx);
        if (is_string($raw) && trim($raw) !== '') return $raw;
    }
    return '';
}
}

if (!function_exists('ugfx_parse_icecast_data')) {
function ugfx_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 ?? '')),
    ];
    if (isset($sx->source)) {
        foreach ($sx->source as $source) {
            $mount = ugfx_normalize_mount((string)$source['mount']);
            $title = trim((string)$source->title);
            if ($title === '' && isset($source->x_icy_title)) $title = trim((string)$source->x_icy_title);
            if ($title === '' && isset($source->{'x-icy-title'})) $title = trim((string)$source->{'x-icy-title'});
            if ($title === '' && isset($source->artist) && isset($source->title)) {
                $title = trim((string)$source->artist) . ' - ' . trim((string)$source->title);
            }
            $listeners = isset($source->listeners) ? (int)$source->listeners : 0;
            $streamStart = trim((string)($source->stream_start_iso8601 ?? $source->stream_start ?? ''));
            $sourceIp = trim((string)($source->source_ip ?? ''));
            $listenUrl = trim((string)($source->listenurl ?? ''));
            $serverName = trim((string)($source->server_name ?? ''));
            $serverDescription = trim((string)($source->server_description ?? ''));
            $isActive = ($listeners > 0 || $title !== '' || $sourceIp !== '' || $streamStart !== '');
            $result['sources'][] = [
                'mount' => $mount,
                'title' => html_entity_decode(trim($title), ENT_QUOTES, 'UTF-8'),
                'listeners' => $listeners,
                'stream_start' => $streamStart,
                'source_ip' => $sourceIp,
                'listenurl' => $listenUrl,
                'server_name' => $serverName,
                'server_description' => $serverDescription,
                'is_active' => $isActive,
            ];
        }
    }
    libxml_clear_errors();
    return $result;
}
}

if (!function_exists('ugfx_pick_preferred_source')) {
function ugfx_pick_preferred_source(array $sources): ?array {
    if (!$sources) return null;
    $cfg = ugfx_get_stream_config();
    $preferredMounts = [
        ugfx_normalize_mount((string)($cfg['mount_main'] ?? '/stream')),
        ugfx_normalize_mount((string)($cfg['mount_auto'] ?? '/autodj')),
        ugfx_normalize_mount((string)($cfg['mount_backup'] ?? '/stream2')),
    ];
    foreach ($preferredMounts as $mount) {
        foreach ($sources as $source) {
            if (($source['mount'] ?? '') === $mount && !empty($source['is_active']) && trim((string)($source['title'] ?? '')) !== '' && (int)($source['listeners'] ?? 0) > 0) return $source;
        }
    }
    foreach ($preferredMounts as $mount) {
        foreach ($sources as $source) {
            if (($source['mount'] ?? '') === $mount && !empty($source['is_active']) && trim((string)($source['title'] ?? '')) !== '') return $source;
        }
    }
    foreach ($preferredMounts as $mount) {
        foreach ($sources as $source) {
            if (($source['mount'] ?? '') === $mount && !empty($source['is_active'])) return $source;
        }
    }
    foreach ($sources as $source) {
        if (trim((string)($source['title'] ?? '')) !== '') return $source;
    }
    return $sources[0] ?? null;
}
}

if (!function_exists('ugfx_get_player_urls')) {
function ugfx_get_player_urls(): array {
    $cfg = ugfx_get_stream_config();
    $rawUrl = trim((string)($cfg['listen_url'] ?? ''));
    return [
        'raw' => $rawUrl,
        'proxy' => '/stream-proxy.php',
        'preferred' => $rawUrl !== '' ? $rawUrl : '/stream-proxy.php',
        'using_proxy' => false,
    ];
}
}
