<?php
    // Almost Heaven Radio Icecast details
    $server_ip      = 'cr3.broadcasturself.com';
    $server_port    = '6969';
    $admin_user     = 'Admin';
    $admin_password = '71yn3p8eyr6RjY8u';

    // Main live mount (if you ever use a live /stream mount)
    $mountpoint = '<source mount="/stream">';

    // Auto DJ mount (your current active one)
    $autopoint  = '<source mount="/autodj">';

    // Optional second AutoDJ / backup mount (leave as-is or remove if unused)
    $autobackup = '<source mount="/autodj2">';

    // Refresh every 60 seconds
    header("refresh: 60;");

    // Pull full stats XML from Icecast admin
    $IcecastWeb = @file_get_contents(
        "http://" . $admin_user . ":" . $admin_password . "@" .
        $server_ip . ":" . $server_port . "/admin/stats.xml"
    );

    if ($IcecastWeb === false) {
        echo "<center><p>Now Playing data unavailable.</p></center>";
        exit;
    }

    // Temp file (named after admin user)
    $file = $admin_user . '.txt';
    file_put_contents($file, $IcecastWeb);

    $RFile = file_get_contents($admin_user . '.txt');

    $currently = '';

    // Helper function to extract x_icy_title for a given mount marker
    function get_now_playing_for_mount($RFile, $mountMarker) {
        if (!str_contains($RFile, $mountMarker)) {
            return '';
        }

        $store  = strstr($RFile, $mountMarker);
        $store2 = strstr($store, '<x_icy_title>');
        if ($store2 === false) {
            return '';
        }

        $start = strpos($store2, '<x_icy_title>');
        $end   = strpos($store2, '</x_icy_title>');

        if ($start === false || $end === false) {
            return '';
        }

        $inner = substr($store2, $start + strlen('<x_icy_title>'), $end - ($start + strlen('<x_icy_title>')));
        return trim($inner);
    }

    // 1) Try main live mount /stream
    $currently = get_now_playing_for_mount($RFile, $mountpoint);

    // 2) If empty, try AutoDJ /autodj
    if ($currently === '') {
        $currently = get_now_playing_for_mount($RFile, $autopoint);
    }

    // 3) If still empty, try backup /autodj2 (if used)
    if ($currently === '') {
        $currently = get_now_playing_for_mount($RFile, $autobackup);
    }

    // Output
    if ($currently !== '') {
        echo "<center><p><strong>Now Playing:</strong> " . htmlspecialchars($currently) . "</p></center>";
    } else {
        echo "<center><p>No metadata available.</p></center>";
    }

    // Clean up temp file
    unlink($admin_user . '.txt');
?>
