<?php include 'auth.php'; ?>
<?php include '../includes/header.php'; ?>
<?php include '../includes/menu.php'; ?>

<?php
echo '<meta http-equiv="refresh" content="30">';
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"
  ]
]);

$xml = @file_get_contents("http://$server_ip:$server_port/admin/stats.xml", false, $context);
$stats = @simplexml_load_string($xml);

// 🔐 Kill source logic — only admins can trigger
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($_POST['kill_mount']);
    @file_get_contents($kill_url, false, $context);
    echo "<div class='alert alert-warning text-center'>Source for {$_POST['kill_mount']} has been terminated.</div>";
  } else {
    echo "<div class='alert alert-danger text-center'>Access denied: You do not have permission to kill sources.</div>";
  }
}
?>

<div class="container mt-5">
  <div class="content-box">
    <h2>🎶 Icecast Stream Monitor</h2>
    <p class="mb-4">Live stats from <strong><?= htmlspecialchars($server_ip) ?></strong> (Port <?= $server_port ?>)</p>

    <?php if (!$stats): ?>
      <div class="alert alert-danger">Unable to connect to Icecast server or retrieve stats.</div>
    <?php else: ?>

      <!-- Global Server Stats -->
      <div class="table-responsive mb-5">
        <h4>🌐 Global Server Stats</h4>
        <table class="table table-bordered">
          <tbody>
            <?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 "<tr><th>$field</th><td>" . ($stats->$field ?? 'N/A') . "</td></tr>";
            }
            ?>
          </tbody>
        </table>
      </div>

      <!-- Mountpoint Stats -->
      <div class="accordion mb-5" id="mountAccordion">
        <?php
        $index = 0;
        foreach ($stats->source as $source) {
          $mount = (string) $source['mount'];
          if (!in_array($mount, $mounts)) continue;

          $streamStart = $source->stream_start ?? '';
          $localTime = $streamStart ? date('D, d M Y H:i:s', strtotime((string)$streamStart)) : 'N/A';

          echo "<div class='accordion-item'>";
          echo "<h2 class='accordion-header' id='heading$index'>";
          echo "<button class='accordion-button ".($index > 0 ? 'collapsed' : '')."' type='button' data-bs-toggle='collapse' data-bs-target='#collapse$index' aria-expanded='".($index === 0 ? 'true' : 'false')."' aria-controls='collapse$index'>";
          echo "🎧 Mountpoint: <code>$mount</code>";
          echo "</button></h2>";
          echo "<div id='collapse$index' class='accordion-collapse collapse ".($index === 0 ? 'show' : '')."' aria-labelledby='heading$index' data-bs-parent='#mountAccordion'>";
          echo "<div class='accordion-body'>";
          echo "<table class='table table-bordered'>";
          echo "<tbody>";

          $fields = [
            'title','bitrate','genre','audio_info','listeners','listener_peak','slow_listeners','stream_start','stream_start_iso8601',
            'server_name','server_description','server_type','server_url','listenurl','max_listeners','public','source_ip',
            'total_bytes_read','total_bytes_sent'
          ];

          foreach ($fields as $field) {
            $value = $source->$field ?? 'N/A';
            if ($field === 'stream_start') $value = $localTime;
            echo "<tr><th>$field</th><td>$value</td></tr>";
          }

          echo "<tr><th>Actions</th><td>";
          if ($_SESSION['admin_role'] === 'admin') {
            echo "<form method='POST' class='d-inline'>
                    <input type='hidden' name='kill_mount' value='$mount'>
                    <button type='submit' class='btn btn-sm btn-danger' onclick=\"return confirm('Kill source for $mount?')\">Kill Source</button>
                  </form>";
          } else {
            echo "<span class='text-muted'>View only</span>";
          }
          echo "</td></tr>";

          echo "</tbody></table>";
          echo "</div></div></div>";
          $index++;
        }
        ?>
      </div>

      <!-- Listener Trends Graph -->
      <div class="text-center mb-5">
        <h4>📈 Listener Trends</h4>
        <img src="../assets/icecast_listener_trends.png" alt="Listener Trends Graph" class="img-fluid" style="max-width: 800px;">
        <p class="text-muted">Graph updates every 30 minutes. Data pulled from listener logs.</p>
      </div>
    <?php endif; ?>
  </div>
</div>

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