<?php
// Keep the original working metadata logic for the homepage.
$hostname = 'cr3.broadcasturself.com';
$port     = 6660;
$user     = 'Admin';
$pass     = 'RBtV72ZAr6pw';
$mount    = '/stream';

$statsUrl = "http://$hostname:$port/admin/stats";
$track    = 'Loading...';

$context = stream_context_create([
  'http' => [
    'timeout' => 3,
    'header'  => "Authorization: Basic " . base64_encode("$user:$pass")
  ]
]);

$response = @file_get_contents($statsUrl, false, $context);

if ($response) {
    $xml = @simplexml_load_string($response);

    if ($xml && isset($xml->source)) {
        $streamTitle = null;
        $autodjTitle = null;

        foreach ($xml->source as $source) {
            $mountName = (string)$source['mount'];
            $title     = trim((string)$source->title);

            if ($mountName === $mount && $title !== '') {
                $streamTitle = htmlspecialchars($title, ENT_QUOTES, 'UTF-8');
            }
            if ($mountName === '/autodj' && $title !== '') {
                $autodjTitle = htmlspecialchars($title, ENT_QUOTES, 'UTF-8');
            }
        }

        if ($streamTitle) {
            $track = $streamTitle;
        } elseif ($autodjTitle) {
            $track = $autodjTitle;
        }
    }
}
?>
<span id="track-text"><?= $track ?></span>
<script>
(function(){
  if (window.__tmrHomeNowPlayingInit) return;
  window.__tmrHomeNowPlayingInit = true;

  async function refreshHomeNowPlaying(){
    try{
      const res = await fetch('/api/nowplaying.php?ts=' + Date.now(), {cache:'no-store'});
      if(!res.ok) return;
      const data = await res.json();
      const el = document.getElementById('track-text');
      if(el && data && data.title){
        el.textContent = data.title;
      }
    }catch(e){}
  }

  setInterval(refreshHomeNowPlaying, 30000);
})();
</script>
