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

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

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

/* ------------------------------------------------------------
   HELPER FUNCTIONS
------------------------------------------------------------ */
function formatUptime($startIso) {
    if (!$startIso) return "N/A";

    try {
        $start = new DateTime($startIso);
        $now   = new DateTime("now");
        $diff  = $start->diff($now);
        return $diff->days . "d " . $diff->h . "h " . $diff->i . "m";
    } catch (Exception $e) {
        return "N/A";
    }
}

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

function fetchIcecastXML($url, $user, $pass) {
    $result = [
        'ok'        => false,
        'xml_raw'   => null,
        'xml_obj'   => false,
        'http_code' => 0,
        'error'     => null,
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $pass);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_FAILONERROR, false);

    $response = curl_exec($ch);
    $curlErr  = curl_error($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);

    $result['xml_raw']   = $response;
    $result['http_code'] = $httpCode;

    if ($response === false) {
        $result['error'] = 'cURL error: ' . $curlErr;
        return $result;
    }

    if ($httpCode !== 200) {
        $result['error'] = 'Icecast returned HTTP ' . $httpCode;
        return $result;
    }

    libxml_use_internal_errors(true);
    $xml = simplexml_load_string($response);

    if ($xml === false) {
        $errors = libxml_get_errors();
        $msg = [];
        foreach ($errors as $err) {
            $msg[] = trim($err->message);
        }
        libxml_clear_errors();

        $result['error'] = 'XML parse error: ' . implode(' | ', $msg);
        return $result;
    }

    $result['ok']      = true;
    $result['xml_obj'] = $xml;

    return $result;
}

function callIcecastAdmin($url, $user, $pass) {
    $result = [
        'ok'        => false,
        'response'  => null,
        'http_code' => 0,
        'error'     => null,
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $pass);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_FAILONERROR, false);

    $response = curl_exec($ch);
    $curlErr  = curl_error($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);

    $result['response']  = $response;
    $result['http_code'] = $httpCode;

    if ($response === false) {
        $result['error'] = 'cURL error: ' . $curlErr;
        return $result;
    }

    if ($httpCode !== 200) {
        $result['error'] = 'Icecast returned HTTP ' . $httpCode;
        return $result;
    }

    $result['ok'] = true;
    return $result;
}

/* ------------------------------------------------------------
   URLS
------------------------------------------------------------ */
$statsURL = "http://{$hostname}:{$port}/admin/stats.xml";

/* ------------------------------------------------------------
   KILL SOURCE (ADMIN ONLY)
------------------------------------------------------------ */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['kill_mount'])) {
    if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
        die("<h1>Access Denied</h1><p>Only administrators can kill a source.</p>");
    }

    $killMount = trim($_POST['kill_mount']);
    $killURL   = "http://{$hostname}:{$port}/admin/killsource?mount=" . urlencode($killMount);

    $killResult = callIcecastAdmin($killURL, $user, $pass);

    if (!$killResult['ok']) {
        $_SESSION['icecast_error'] = $killResult['error'];
    } else {
        $_SESSION['icecast_success'] = "Source killed successfully for mount: {$killMount}";
    }

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

/* ------------------------------------------------------------
   FETCH XML STATS
------------------------------------------------------------ */
$fetchResult = fetchIcecastXML($statsURL, $user, $pass);
$stats       = $fetchResult['xml_obj'];
?>

<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 (!empty($_SESSION['icecast_error'])): ?>
                <div class="msg error center-text">
                    <?= htmlspecialchars($_SESSION['icecast_error']) ?>
                </div>
                <?php unset($_SESSION['icecast_error']); ?>
            <?php endif; ?>

            <?php if (!empty($_SESSION['icecast_success'])): ?>
                <div class="msg success center-text">
                    <?= htmlspecialchars($_SESSION['icecast_success']) ?>
                </div>
                <?php unset($_SESSION['icecast_success']); ?>
            <?php endif; ?>

            <?php if (!$fetchResult['ok']): ?>
                <div class="msg error center-text">
                    Unable to fetch Icecast stats.<br>
                    <small><?= htmlspecialchars($fetchResult['error'] ?? 'Unknown error') ?></small>
                    <?php if (!empty($fetchResult['http_code'])): ?>
                        <br><small>HTTP Code: <?= (int)$fetchResult['http_code'] ?></small>
                    <?php endif; ?>
                </div>

                <?php if (!empty($fetchResult['xml_raw'])): ?>
                    <div class="admin-card" style="margin-top:20px;">
                        <h3>Raw Response</h3>
                        <pre style="white-space:pre-wrap; overflow:auto;"><?= htmlspecialchars($fetchResult['xml_raw']) ?></pre>
                    </div>
                <?php endif; ?>

            <?php else: ?>

                <h3 class="center-text">🌐 Global Server Stats</h3>

                <div class="admin-card">
                    <p><strong>Server Uptime:</strong>
                        <?= formatUptime((string)($stats->{'server_start_iso8601'} ?? '')) ?>
                    </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) {
                        $value = isset($stats->$field) ? (string)$stats->$field : 'N/A';
                        echo "<p><strong>" . htmlspecialchars($field) . ":</strong> " . htmlspecialchars($value) . "</p>";
                    }
                    ?>
                </div>

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

                <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><?= htmlspecialchars($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((string)($source->{'stream_start_iso8601'} ?? '')) ?>
                                </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) {
                                    $value = isset($source->$field) ? (string)$source->$field : 'N/A';
                                    echo "<p><strong>" . htmlspecialchars($field) . ":</strong> " . htmlspecialchars($value) . "</p>";
                                }
                                ?>

                                <?php if (isset($_SESSION['role']) && $_SESSION['role'] === 'admin'): ?>
                                    <form method="POST" onsubmit="return confirm('Kill source for <?= htmlspecialchars($mount, ENT_QUOTES) ?>?');">
                                        <input type="hidden" name="kill_mount" value="<?= htmlspecialchars($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 else: ?>
                    <div class="msg error center-text">No mountpoint data found in Icecast response.</div>
                <?php endif; ?>

            <?php endif; ?>

        </div>
    </div>
</div>

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