<?php
require_once 'includes/auth.php';
header("Refresh: 30");
include 'includes/header.php';

date_default_timezone_set('America/New_York');

$server_ip = 'cr3.broadcasturself.com';
$server_port = '65001';
$admin_user = 'HomeTimeRadio';
$admin_password = 'KFnph5qQuBPXaT3VJ4jp';

$stats_url = "http://$admin_user:$admin_password@$server_ip:$server_port/admin/stats.xml";

// Kill source if requested
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['kill_mount']) && canControlPage()) {
  $kill_url = "http://$admin_user:$admin_password@$server_ip:$server_port/admin/killsource?mount=" . urlencode($_POST['kill_mount']);
  @file_get_contents($kill_url);
  echo "<div class='alert alert-warning text-center'>Source for {$_POST['kill_mount']} has been terminated.</div>";
}

// Load XML
$xml = @file_get_contents($stats_url);
$stats = @simplexml_load_string($xml);
?>

<div class="container content-box mt-5">
  <div class="text-center mb-5">
    <h1>Icecast Admin Panel</h1>
    <p class="subtext">Monitor and control your live streams</p>
  </div>

<?php
if (!$stats) {
  echo "<div class='alert alert-danger text-center'>Unable to fetch Icecast stats.</div>";
} else {
  // GLOBAL STATS
  echo "<div class='mb-5'>";
  echo "<div class='bg-dark text-white p-4 rounded'>";
  echo "<h4 class='mb-3'>🌐 Global Server Stats</h4>";
  $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 "<p><strong>$field:</strong> " . ($stats->$field ?? 'N/A') . "</p>";
  }
  echo "</div></div>";

  // MOUNTPOINT STATS
  if (isset($stats->source)) {
    echo "<div class='row'>";
    foreach ($stats->source as $source) {
      $mount = (string) $source['mount'];
      echo "<div class='col-md-6 mb-4'>";
      echo "<div class='bg-light p-4 rounded'>";
      echo "<h4>Mountpoint: <code>$mount</code></h4>";

      $fields = ['audio_info','bitrate','genre','ice-bitrate','ice-channels','ice-samplerate','listener_peak','listeners','listenurl','max_listeners','public','server_description','server_name','server_type','server_url','slow_listeners','source_ip','stream_start','stream_start_iso8601','title','total_bytes_read','total_bytes_sent'];
      foreach ($fields as $field) {
        echo "<p><strong>$field:</strong> " . ($source->$field ?? 'N/A') . "</p>";
      }

      if (canControlPage()) {
        echo "<form method='POST'>";
        echo "<input type='hidden' name='kill_mount' value='$mount'>";
        echo "<button type='submit' class='btn btn-danger' onclick=\"return confirm('Kill source for $mount?')\">Kill Source</button>";
        echo "</form>";
      }

      echo "</div></div>";
    }
    echo "</div>";
  }
}
?>

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