<?php include 'includes/header.php'; ?>
<?php date_default_timezone_set('America/New_York'); ?>

<?php
// Icecast track fetch and logging
$server_ip = 'cr3.broadcasturself.com';
$server_port = '65001';
$admin_user = 'HomeTimeRadio';
$admin_password = 'KFnph5qQuBPXaT3VJ4jp';

$mounts = ['/stream', '/autodj', '/autodj2'];
$stats_url = "http://$admin_user:$admin_password@$server_ip:$server_port/admin/stats.xml";

$xml = @file_get_contents($stats_url);
if ($xml) {
  $track = '';
  foreach ($mounts as $mount) {
    $needle = '<source mount="' . $mount . '">';
    if (str_contains($xml, $needle)) {
      $section = strstr($xml, $needle);
      $titleBlock = strstr($section, '<title>');
      if ($titleBlock) {
        $start = strpos($titleBlock, '<title>') + 7;
        $end = strpos($titleBlock, '</title>');
        $track = trim(substr($titleBlock, $start, $end - $start));
        break;
      }
    }
  }

  if ($track !== '') {
    $lastTrackFile = 'last-track.txt';
    $playlistFile = 'playlist.txt';
    $lastTrack = file_exists($lastTrackFile) ? trim(file_get_contents($lastTrackFile)) : '';

    if ($track !== $lastTrack) {
      file_put_contents($playlistFile, $track . "\n", FILE_APPEND);
      file_put_contents($lastTrackFile, $track);
    }
  }
}
?>

<div class="container content-box mt-5">
  <div class="text-center mb-4">
    <h1>🎵 Recent Playlist 🎵</h1>
    <p class="subtext">📻 Top 50 tracks recently played on Home Time Radio 📻</p>
  </div>

  <div class="bg-light p-4 rounded shadow-sm">
    <?php
    $playlistFile = 'playlist.txt';
    if (file_exists($playlistFile)) {
      $tracks = file($playlistFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
      $recent = array_slice(array_reverse($tracks), 0, 50);
      echo "<ol class='list-group list-group-numbered'>";
      foreach ($recent as $track) {
        echo "<li class='list-group-item'>" . htmlspecialchars($track) . "</li>";
      }
      echo "</ol>";
    } else {
      echo "<p>No playlist data found.</p>";
    }
    ?>
  </div>
</div>

<?php include 'includes/footer.php'; ?>
