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

$hostname = 'cr3.broadcasturself.com';
$port = 6660;
$mount = '/stream'; // or /autodj if that's your main
$url = "http://$hostname:$port/status-json.xsl";

$logFile = __DIR__ . '/data/recently_played.txt';
$lastFile = __DIR__ . '/data/last_played.txt';

$json = @file_get_contents($url);
$data = json_decode($json, true);

if (!$data || !isset($data['icestats']['source'])) {
  exit; // Icecast not responding
}

$source = $data['icestats']['source'];
if (isset($source['mount']) && $source['mount'] !== $mount) {
  // Multiple sources — find the right one
  foreach ((array)$source as $s) {
    if (isset($s['mount']) && $s['mount'] === $mount) {
      $source = $s;
      break;
    }
  }
}

$title = trim($source['title'] ?? '');
if ($title === '') exit;

$last = file_exists($lastFile) ? trim(file_get_contents($lastFile)) : '';
if ($title !== $last) {
  $timestamp = date('Y-m-d H:i');
  file_put_contents($logFile, "$timestamp|$title\n", FILE_APPEND);
  file_put_contents($lastFile, $title);
}
