<?php
// Radio Galaxy FX now playing snippet.
// Safe for both direct requests and page includes.

$server_ip      = 'cr3.broadcasturself.com';
$server_port    = '1982';
$admin_user     = 'Admin';
$admin_password = '71yn3p8eyr6RjY8u';

$mountpoints = [
    '/stream',
    '/autodj',
    '/autodj2',
];

if (!function_exists('rgfx_nowplaying_is_direct_request')) {
    function rgfx_nowplaying_is_direct_request(): bool {
        if (!isset($_SERVER['SCRIPT_FILENAME'])) {
            return false;
        }
        return realpath((string)$_SERVER['SCRIPT_FILENAME']) === __FILE__;
    }
}

if (!function_exists('rgfx_nowplaying_output')) {
    function rgfx_nowplaying_output(string $message, bool $isError = false): void {
        $safe = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
        if ($isError) {
            echo "<center><p>" . $safe . "</p></center>";
            return;
        }
        echo "<center><p><strong>Now Playing:</strong> " . $safe . "</p></center>";
    }
}

if (!function_exists('rgfx_extract_mount_title')) {
    function rgfx_extract_mount_title(string $xml, string $mount): string {
        $quotedMount = preg_quote($mount, '#');
        $pattern = '#<source\s+mount="' . $quotedMount . '">(.*?)</source>#si';
        if (!preg_match($pattern, $xml, $match)) {
            return '';
        }
        if (!preg_match('#<x_icy_title>(.*?)</x_icy_title>#si', $match[1], $titleMatch)) {
            return '';
        }
        return trim(html_entity_decode(strip_tags($titleMatch[1]), ENT_QUOTES | ENT_XML1, 'UTF-8'));
    }
}

if (rgfx_nowplaying_is_direct_request() && !headers_sent()) {
    header('Content-Type: text/html; charset=UTF-8');
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header('Pragma: no-cache');
}

$statsUrl = 'http://' . rawurlencode($admin_user) . ':' . rawurlencode($admin_password) . '@' . $server_ip . ':' . $server_port . '/admin/stats.xml';
$context = stream_context_create([
    'http' => [
        'timeout' => 8,
        'ignore_errors' => true,
    ],
]);

$xml = @file_get_contents($statsUrl, false, $context);
if ($xml === false || trim($xml) === '') {
    rgfx_nowplaying_output('Now Playing data unavailable.', true);
    return;
}

$currently = '';
foreach ($mountpoints as $mount) {
    $currently = rgfx_extract_mount_title($xml, $mount);
    if ($currently !== '') {
        break;
    }
}

if ($currently !== '') {
    rgfx_nowplaying_output($currently, false);
} else {
    rgfx_nowplaying_output('No metadata available.', true);
}
