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

date_default_timezone_set('Australia/Sydney');
$server_ip = 'cr3.broadcasturself.com';
$server_port = '6660';
$admin_user = 'Admin';
$admin_password = 'RBtV72ZAr6pw';
$mounts = ['/stream', '/autodj'];
$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['admin_role'] ?? '') === 'admin') {
    $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 admin tool now sits inside the Thunder admin shell and reads the same live server data the public player relies on.</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 (($_SESSION['admin_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 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'; ?>
