<?php
date_default_timezone_set('Australia/Sydney');

try {
  $server_ip = 'cr3.broadcasturself.com';
  $server_port = '6660';
  $admin_user = 'Admin';
  $admin_password = 'RBtV72ZAr6pw';

  $mounts = ['/stream', '/autodj'];
  $auth = base64_encode("$admin_user:$admin_password");
  $context = stream_context_create([
    'http' => [
      'header' => "Authorization: Basic $auth"
    ]
  ]);

  $xml = @file_get_contents("http://$server_ip:$server_port/admin/stats.xml", false, $context);
  if (!$xml) return;

  $logFile = __DIR__ . '/recently_played.txt';
  $stateFile = __DIR__ . '/last_logged.json';

  $lastLogged = @json_decode(@file_get_contents($stateFile), true);
  if (!is_array($lastLogged)) $lastLogged = [];

  foreach ($mounts as $mount) {
    $needle = '<source mount="' . $mount . '">';
    if (str_contains($xml, $needle)) {
      $section = strstr($xml, $needle);
      $end = strpos($section, '</source>');
      $sourceBlock = substr($section, 0, $end + 9);

      $title = getTagValue($sourceBlock, 'title');
      if (!empty($title) && $title !== 'N/A') {
        $title = trim($title);
        if (!isset($lastLogged[$mount]) || $lastLogged[$mount] !== $title) {
          file_put_contents($logFile, "$title\n", FILE_APPEND);
          $lastLogged[$mount] = $title;
          file_put_contents($stateFile, json_encode($lastLogged));
        }
      }
    }
  }
} catch (Throwable $e) {
  error_log("Track logger error: " . $e->getMessage());
}

function getTagValue($block, $tag) {
  $start = strpos($block, "<$tag>");
  $end = strpos($block, "</$tag>");
  if ($start !== false && $end !== false) {
    return trim(substr($block, $start + strlen($tag) + 2, $end - $start - strlen($tag) - 2));
  }
  return 'N/A';
}
?>
