<?php
session_start();
require __DIR__ . '/auth.php';
require __DIR__ . '/includes/admin_lib.php';


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

$cfgPath = __DIR__ . '/config/icecast.php';
$cfg = file_exists($cfgPath) ? include $cfgPath : ['hostname'=>'','port'=>0,'user'=>'','pass'=>''];

$hostname = $cfg['hostname'] ?? '';
$port     = (int)($cfg['port'] ?? 0);
$user     = $cfg['user'] ?? '';
$pass     = $cfg['pass'] ?? '';

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;";
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['kill_mount'])) {
  if (($_SESSION['role'] ?? '') !== 'admin') {
    smurf_admin_denied('Only administrators can kill a source.');
  }

  if ($hostname && $port && $user && $pass) {
    $killMount = $_POST['kill_mount'];
    $killURL = "http://$user:$pass@$hostname:$port/admin/killsource?mount=" . urlencode($killMount);
    @file_get_contents($killURL);
  }
  header("Location: /admin/radiostats.php");
  exit;
}

$stats = null;
if ($hostname && $port && $user && $pass) {
  $statsURL = "http://$user:$pass@$hostname:$port/admin/stats.xml";
  $xml = @file_get_contents($statsURL);
  if ($xml) $stats = @simplexml_load_string($xml);
}
include __DIR__ . '/includes/admin_header.php';
?>
<section class="content-card">
  <h1 class="admin-title">📡 Icecast Stream Monitor</h1>
  <p style="opacity:.8;">Config: <code>/admin/config/icecast.php</code> • Auto-refresh: 30s</p>

  <?php if (!$hostname || !$port || !$user || !$pass): ?>
    <div class="msg error">
      Icecast credentials not set yet. Edit <code>/admin/config/icecast.php</code> and fill in hostname/port/user/pass.
    </div>
  <?php elseif (!$stats): ?>
    <div class="msg error">Unable to fetch Icecast stats.</div>
  <?php else: ?>

    <div class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;">🌐 Global Server Stats</h3>
      <p><strong>Server Uptime:</strong> <?= formatUptime($stats->{'server_start_iso8601'} ?? null) ?></p>
      <p><strong>Listeners:</strong> <?= (int)($stats->listeners ?? 0) ?></p>
      <p><strong>Sources:</strong> <?= (int)($stats->sources ?? 0) ?></p>
      <p><strong>Host:</strong> <?= smurf_h((string)($stats->host ?? '')) ?></p>
    </div>

    <div class="smurf-divider"></div>

    <h3 style="margin:0 0 10px;">🎶 Mountpoints</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="content-card" style="text-align:left;">
            <h3 style="margin-top:0;">
              <code><?= smurf_h($mount) ?></code>
              <span style="<?= $statusColor ?>; font-weight:bold; margin-left:10px;">
                ● <?= $liveListeners > 0 ? "LIVE" : "OFFLINE" ?>
              </span>
            </h3>
            <p><strong>Live listeners:</strong> <span style="<?= $statusColor ?>;font-weight:900;"><?= $liveListeners ?></span></p>
            <p><strong>Stream uptime:</strong> <?= formatUptime($source->{'stream_start_iso8601'} ?? null) ?></p>
            <p><strong>Now playing:</strong> <?= smurf_h((string)($source->title ?? $source->server_name ?? '')) ?></p>

            <?php if (($_SESSION['role'] ?? '') === 'admin'): ?>
              <form method="POST" onsubmit="return confirm('Kill source for <?= smurf_h($mount) ?>?');">
                <input type="hidden" name="kill_mount" value="<?= smurf_h($mount) ?>">
                <button class="admin-btn" style="background:rgba(255,0,80,.25);border-color:rgba(255,0,80,.5);">Kill Source</button>
              </form>
            <?php else: ?>
              <p style="opacity:0.65;">View-only mode — Kill Source disabled.</p>
            <?php endif; ?>
          </div>
        <?php endforeach; ?>
      </div>
    <?php else: ?>
      <p>No mountpoints returned.</p>
    <?php endif; ?>

  <?php endif; ?>
</section>

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