<?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_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_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_mount'])) {
                $statsMount = '/' . ltrim(trim((string)$settings['stats_mount']), '/');
                $cfg['mount_auto'] = $statsMount;
            }
        }
    }

    $listenPath = parse_url((string)$cfg['listen_url'], PHP_URL_PATH);
    $listenMount = is_string($listenPath) && trim($listenPath) !== '' ? '/' . ltrim(trim($listenPath), '/') : '';
    if ($listenMount !== '') {
        $cfg['mount_main'] = $listenMount;
        if ($cfg['mount_auto'] === $listenMount) {
            $cfg['mount_auto'] = $listenMount === '/stream' ? '/autodj' : '/stream';
        }
    }

    return $cfg;
}
}

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

if (!function_exists('ugfx_fetch_icecast_xml')) {
function ugfx_fetch_icecast_xml(): string {
    $cfg = ugfx_get_stream_config();
    $hostname = trim((string)($cfg['server_ip'] ?? ''));
    $port = trim((string)($cfg['server_port'] ?? ''));
    $user = (string)($cfg['admin_user'] ?? '');
    $pass = (string)($cfg['admin_password'] ?? '');
    if ($hostname === '' || $port === '' || $user === '' || $pass === '') return '';

    $urls = [];
    foreach ([
        $cfg['stats_url'] ?? '',
        "http://{$hostname}:{$port}/admin/stats",
        "http://{$hostname}:{$port}/admin/stats.xml",
    ] as $url) {
        $url = trim((string)$url);
        if ($url !== '' && !in_array($url, $urls, true)) $urls[] = $url;
    }

    foreach ($urls as $url) {
        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_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 = trim((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)) {
                $maybeArtist = trim((string)$source->artist);
                $maybeTitle = trim((string)$source->title);
                if ($maybeArtist !== '' && $maybeTitle !== '') $title = $maybeArtist . ' - ' . $maybeTitle;
            }
            $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($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 = array_values(array_unique(array_filter([
        trim((string)($cfg['mount_main'] ?? '/stream')),
        trim((string)($cfg['mount_auto'] ?? '/autodj')),
        trim((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;
        }
    }

    usort($sources, function(array $a, array $b): int {
        return ((int)($b['listeners'] ?? 0) <=> (int)($a['listeners'] ?? 0));
    });
    foreach ($sources as $source) {
        if (trim((string)($source['title'] ?? '')) !== '') return $source;
    }
    return $sources[0] ?? null;
}
}
