<?php
session_start();
require __DIR__ . '/auth.php';
require __DIR__ . '/includes/admin_lib.php';
require_once __DIR__ . '/../includes/stream_lib.php';
$pageTitle = 'Icecast Monitor — Admin';
include __DIR__ . '/includes/admin_header.php';

date_default_timezone_set('Australia/Sydney');
$cfg = smurf_get_stream_config();
$server_ip = (string)($cfg['server_ip'] ?? '');
$server_port = (string)($cfg['server_port'] ?? '');
$admin_user = (string)($cfg['admin_user'] ?? '');
$admin_password = (string)($cfg['admin_password'] ?? '');
$mounts = array_values(array_filter([
  (string)($cfg['mount_main'] ?? '/stream'),
  (string)($cfg['mount_auto'] ?? '/autodj'),
  (string)($cfg['mount_backup'] ?? '/autodj2'),
]));
$auth = base64_encode("$admin_user:$admin_password");
$context = stream_context_create(['http' => ['header' => "Authorization: Basic $auth"]]);
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['kill_mount'])) {
  if (($_SESSION['role'] ?? $_SESSION['admin_role'] ?? '') === 'admin' || ($_SESSION['role'] ?? '') === 'master') {
    $kill_url = "http://$server_ip:$server_port/admin/killsource?mount=" . urlencode((string)$_POST['kill_mount']);
    @file_get_contents($kill_url, false, $context);
    header('Location: icecast.php?killed=1');
    exit;
  }
  header('Location: icecast.php?denied=1');
  exit;
}
$xml = @file_get_contents("http://$server_ip:$server_port/admin/stats.xml", false, $context);
$stats = @simplexml_load_string((string)$xml);
?>
<section class="content-card">
  <h1 class="admin-title">📡 Icecast Stream Monitor</h1>
  <p style="opacity:.85;">This tool uses Almost Heaven's stream settings and sits inside the Heaven admin shell.</p>
  <?php if (!empty($_GET['killed'])): ?><div class="msg success">Source terminated.</div><?php endif; ?>
  <?php if (!empty($_GET['denied'])): ?><div class="msg error">Access denied: only full admins can kill sources.</div><?php endif; ?>
  <?php if (!$stats): ?>
    <div class="content-card" style="border-color:rgba(255,120,120,.55);">Unable to connect to the Icecast server or retrieve stats right now.</div>
  <?php else: ?>
    <div class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;">Global Server Stats</h3>
      <table class="admin-table"><tbody>
        <?php foreach (['host','server_id','server_start','listeners','listener_connections','sources','connections'] as $field): ?>
          <tr><th><?= smurf_h($field) ?></th><td><?= smurf_h((string)($stats->$field ?? 'N/A')) ?></td></tr>
        <?php endforeach; ?>
      </tbody></table>
    </div>
    <?php foreach ($stats->source as $source): $mount = (string)$source['mount']; if (!in_array($mount, $mounts, true)) continue; $streamStart = (string)($source->stream_start ?? ''); $localTime = $streamStart ? date('D, d M Y H:i:s', strtotime($streamStart)) : 'N/A'; ?>
      <div class="content-card" style="text-align:left; margin-top:16px;">
        <div style="display:flex;justify-content:space-between;gap:10px;align-items:center;flex-wrap:wrap;">
          <h3 style="margin:0;">🎧 <?= smurf_h($mount) ?></h3>
          <?php if (in_array((string)($_SESSION['role'] ?? ''), ['admin','master'], true)): ?>
            <form method="post" onsubmit="return confirm('Kill source for <?= smurf_h($mount) ?>?');">
              <input type="hidden" name="kill_mount" value="<?= smurf_h($mount) ?>">
              <button type="submit" class="admin-btn danger">Kill Source</button>
            </form>
          <?php else: ?><span style="opacity:.8;">View only</span><?php endif; ?>
        </div>
        <table class="admin-table" style="margin-top:10px;"><tbody>
          <?php foreach (['title','server_name','server_description','bitrate','listeners','listener_peak','genre','listenurl','server_url','stream_start'] as $field): $value = (string)($source->$field ?? 'N/A'); if ($field === 'stream_start') $value = $localTime; ?>
            <tr><th><?= smurf_h($field) ?></th><td><?= smurf_h($value) ?></td></tr>
          <?php endforeach; ?>
        </tbody></table>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>