<?php
if (!function_exists('smurf_fetch_nowplaying_title')) {
function smurf_fetch_nowplaying_title(): string {
    require_once __DIR__ . '/stream_lib.php';

    $title = '';
    if (function_exists('smurf_get_nowplaying_title')) {
        $title = trim((string)smurf_get_nowplaying_title());
        if ($title !== '') {
            return $title;
        }
    }

    $cfg = smurf_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'] ?? '');
    $mounts   = [
        trim((string)($cfg['mount_main'] ?? '/stream')),
        trim((string)($cfg['mount_auto'] ?? '/autodj')),
        trim((string)($cfg['mount_backup'] ?? '/autodj2')),
    ];

    if ($hostname === '' || $port === '' || $user === '' || $pass === '') {
        return 'Now Playing data unavailable.';
    }

    $track = 'Now Playing data unavailable.';
    $authHeader = "Authorization: Basic " . base64_encode("{$user}:{$pass}");

    foreach (["http://{$hostname}:{$port}/admin/stats", "http://{$hostname}:{$port}/admin/stats.xml"] as $statsUrl) {
        $context = stream_context_create([
            'http' => [
                'timeout' => 4,
                'ignore_errors' => true,
                'header'  => $authHeader,
            ]
        ]);

        $response = @file_get_contents($statsUrl, false, $context);
        if (!is_string($response) || trim($response) === '') {
            continue;
        }

        $xml = @simplexml_load_string($response);
        if (!$xml || !isset($xml->source)) {
            continue;
        }

        $titles = [];
        foreach ($xml->source as $source) {
            $mountName = 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 !== '') {
                $titles[$mountName] = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
            }
        }

        foreach ($mounts as $mount) {
            if ($mount !== '' && !empty($titles[$mount])) {
                return $titles[$mount];
            }
        }

        foreach ($titles as $title) {
            if ($title !== '') {
                return $title;
            }
        }
    }

    return $track;
}
}
