<?php
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

$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 = $title;
            }
            if ($mountName === '/autodj' && $title !== '') {
                $autodjTitle = $title;
            }
        }

        if ($streamTitle) {
            $track = $streamTitle;
        } elseif ($autodjTitle) {
            $track = $autodjTitle;
        }
    }
}

echo json_encode(['title' => $track], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
