<?php
require_once __DIR__ . '/includes/stream_lib.php';
date_default_timezone_set('Australia/Sydney');
try {
  $cfg = smurf_get_stream_config();
  $server_ip = (string)($cfg['server_ip'] ?? '');
  $server_port = (string)($cfg['server_port'] ?? '');
  $admin_user = (string)($cfg['admin_user'] ?? '');
  $admin_password = (string)($cfg['admin_password'] ?? '');
  $mounts = array_values(array_filter([
    (string)($cfg['mount_main'] ?? '/stream'),
    (string)($cfg['mount_auto'] ?? '/autodj'),
    (string)($cfg['mount_backup'] ?? '/autodj2'),
  ]));
  if ($server_ip === '' || $server_port === '') return;
  $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__ . '/data/recently_played.txt';
  $stateFile = __DIR__ . '/last_logged.json';
  $lastLogged = @json_decode((string)@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 ($title === 'N/A') $title = getTagValue($sourceBlock, 'x_icy_title');
      if (!empty($title) && $title !== 'N/A') {
        $title = trim($title);
        if (!isset($lastLogged[$mount]) || $lastLogged[$mount] !== $title) {
          file_put_contents($logFile, "$title
", 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';
}
?>