<?php
session_start();
include __DIR__ . '/auth.php'; // sets $CAN_EDIT

include __DIR__ . '/includes/header.php';

// Auto-refresh every 30 seconds (always on)
echo '<meta http-equiv="refresh" content="30">';

/* ------------------------------------------------------------
   ICECAST CONFIG
------------------------------------------------------------ */
$hostname = 'cr3.broadcasturself.com';
$port     = 23990;
$user     = 'YourOldiesRadio';
$pass     = 'Q5DbUrjK7z9REsqXa';

$statsURL = "http://$user:$pass@$hostname:$port/admin/stats.xml";

/* ------------------------------------------------------------
   HELPER FUNCTIONS
------------------------------------------------------------ */
function formatUptime($startIso) {
    if (!$startIso) return "N/A";
    $start = new DateTime($startIso);
    $now = new DateTime("now");
    $diff = $now->diff($start);
    return $diff->days . "d " . $diff->h . "h " . $diff->i . "m";
}

function mountStatusColor($listeners) {
    return ($listeners > 0) ? "color:#4f4;" : "color:#f44;";
}

/* ------------------------------------------------------------
   KILL SOURCE (ADMIN ONLY)
------------------------------------------------------------ */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['kill_mount'])) {

    if ($_SESSION['role'] !== 'admin') {
        die("<h1>Access Denied</h1><p>Only administrators can kill a source.</p>");
    }

    $killMount = $_POST['kill_mount'];
    $killURL = "http://$user:$pass@$hostname:$port/admin/killsource?mount=" . urlencode($killMount);
    @file_get_contents($killURL);

    header("Location: radiostats.php");
    exit;
}

/* ------------------------------------------------------------
   FETCH XML STATS
------------------------------------------------------------ */
$xml = @file_get_contents($statsURL);
$stats = @simplexml_load_string($xml);
?>

<div class="main-wrap">
    <div class="content-panel">

        <h1 class="section-title center-text">📡 Icecast Stream Monitor</h1>

        <div class="vinyl-divider center-divider"></div>

        <div class="content-box">

            <?php if (!$stats): ?>
                <div class="msg error center-text">Unable to fetch Icecast stats.</div>

            <?php else: ?>

                <!-- GLOBAL SERVER STATS -->
                <h3 class="center-text">🌐 Global Server Stats</h3>

                <div class="admin-card">
                    <p><strong>Server Uptime:</strong>
                        <?= formatUptime($stats->{'server_start_iso8601'} ?? null) ?>
                    </p>

                    <?php
                    $globalFields = [
                        'admin','client_connections','clients','connections','file_connections','host',
                        'listener_connections','listeners','location','server_id','server_start',
                        'server_start_iso8601','source_client_connections','source_relay_connections',
                        'source_total_connections','sources','stats','stats_connections'
                    ];

                    foreach ($globalFields as $field) {
                        echo "<p><strong>$field:</strong> " . ($stats->$field ?? 'N/A') . "</p>";
                    }
                    ?>
                </div>

                <div class="vinyl-divider center-divider"></div>

                <!-- MOUNTPOINT STATS -->
                <h3 class="center-text">🎶 Mountpoint Stats</h3>

                <?php if (isset($stats->source)): ?>
                    <div class="admin-grid">

                        <?php foreach ($stats->source as $source): ?>
                            <?php
                                $mount = (string)$source['mount'];
                                $liveListeners = (int)($source->listeners ?? 0);
                                $statusColor = mountStatusColor($liveListeners);
                            ?>

                            <div class="admin-card">

                                <h3>
                                    Mount: <code><?= $mount ?></code>
                                    <span style="<?= $statusColor ?>; font-weight:bold; margin-left:10px;">
                                        ● <?= $liveListeners > 0 ? "LIVE" : "OFFLINE" ?>
                                    </span>
                                </h3>

                                <p><strong>Live Listeners:</strong>
                                    <span style="font-size:1.2em; font-weight:bold; <?= $statusColor ?>">
                                        <?= $liveListeners ?>
                                    </span>
                                </p>

                                <p><strong>Stream Uptime:</strong>
                                    <?= formatUptime($source->{'stream_start_iso8601'} ?? null) ?>
                                </p>

                                <?php
                                $fields = [
                                    'audio_info','bitrate','genre','ice-bitrate','ice-channels','ice-samplerate',
                                    'listener_peak','listenurl','max_listeners','public',
                                    'server_description','server_name','server_type','server_url',
                                    'slow_listeners','source_ip','total_bytes_read','total_bytes_sent'
                                ];

                                foreach ($fields as $field) {
                                    echo "<p><strong>$field:</strong> " . ($source->$field ?? 'N/A') . "</p>";
                                }
                                ?>

                                <?php if ($_SESSION['role'] === 'admin'): ?>
                                    <form method="POST" onsubmit="return confirm('Kill source for <?= $mount ?>?');">
                                        <input type="hidden" name="kill_mount" value="<?= $mount ?>">
                                        <button class="button" style="background:#900;color:#fff;">Kill Source</button>
                                    </form>
                                <?php else: ?>
                                    <p style="opacity:0.6;">View‑only mode — Kill Source disabled.</p>
                                <?php endif; ?>

                            </div>
                        <?php endforeach; ?>

                    </div>
                <?php endif; ?>

            <?php endif; ?>

        </div>

    </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
