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

echo '<meta http-equiv="refresh" content="30">';

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

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

function formatUptime($startIso) {
  if (!$startIso) return "N/A";
  try {
    $start = new DateTime($startIso);
    $now   = new DateTime("now");
    $diff  = $start->diff($now);
    return $diff->days . "d " . $diff->h . "h " . $diff->i . "m";
  } catch (Throwable $e) {
    return "N/A";
  }
}

function mountStatusColor($listeners) {
  return ($listeners > 0) ? "color:#4f4;" : "color:#f44;";
}

function fetchIcecastXml($hostname, $port, $user, $pass, &$error = null) {
  $error = null;

  if (!$hostname || !$port || !$user || $pass === '') {
    $error = 'Missing Icecast config values.';
    return false;
  }

  $url = "http://{$hostname}:{$port}/admin/stats";

  if (function_exists('curl_init')) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_HTTPAUTH       => CURLAUTH_BASIC,
      CURLOPT_USERPWD        => $user . ':' . $pass,
      CURLOPT_TIMEOUT        => 10,
      CURLOPT_CONNECTTIMEOUT => 5,
      CURLOPT_FAILONERROR    => false,
      CURLOPT_HTTPHEADER     => ['Accept: application/xml, text/xml, */*'],
    ]);

    $response = curl_exec($ch);
    $httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlErr  = curl_error($ch);
    curl_close($ch);

    if ($response === false) {
      $error = 'cURL error: ' . $curlErr;
      return false;
    }

    if ($httpCode >= 400) {
      $error = "Icecast returned HTTP {$httpCode}.";
      return false;
    }

    return $response;
  }

  $context = stream_context_create([
    'http' => [
      'method'  => 'GET',
      'timeout' => 10,
      'header'  => "Authorization: Basic " . base64_encode($user . ':' . $pass) . "\r\n" .
                   "Accept: application/xml, text/xml, */*\r\n",
      'ignore_errors' => true,
    ]
  ]);

  $response = @file_get_contents($url, false, $context);

  if ($response === false) {
    $last = error_get_last();
    $error = $last['message'] ?? 'Unknown HTTP fetch error.';
    return false;
  }

  if (!empty($http_response_header)) {
    foreach ($http_response_header as $hdr) {
      if (preg_match('~^HTTP/\S+\s+(\d{3})~', $hdr, $m)) {
        $code = (int)$m[1];
        if ($code >= 400) {
          $error = "Icecast returned HTTP {$code}.";
          return false;
        }
        break;
      }
    }
  }

  return $response;
}

function xmlNodeToArray(SimpleXMLElement $node) {
  $out = [];

  foreach ($node->attributes() as $attrName => $attrValue) {
    $out['@' . $attrName] = (string)$attrValue;
  }

  foreach ($node->children() as $child) {
    $name  = $child->getName();
    $value = (string)$child;

    if (count($child->children()) > 0 || count($child->attributes()) > 0) {
      $value = xmlNodeToArray($child);
    }

    if (array_key_exists($name, $out)) {
      if (!is_array($out[$name]) || !array_is_list($out[$name])) {
        $out[$name] = [$out[$name]];
      }
      $out[$name][] = $value;
    } else {
      $out[$name] = $value;
    }
  }

  return $out;
}

function prettyLabel($key) {
  $key = ltrim((string)$key, '@');
  $key = str_replace('_', ' ', $key);
  return ucwords($key);
}

function prettyValue($key, $value) {
  if (is_array($value)) {
    return null;
  }

  $value = trim((string)$value);

  if ($value === '') {
    return '(NULL)';
  }

  if ($key === 'server_start_iso8601' || $key === 'stream_start_iso8601') {
    return $value . ' (' . formatUptime($value) . ')';
  }

  return $value;
}

function renderStatsTable(array $rows) {
  if (!$rows) {
    echo '<p>No data returned.</p>';
    return;
  }

  echo '<div class="table-wrap">';
  echo '<table class="admin-table stats-table">';
  echo '<tbody>';

  foreach ($rows as $key => $value) {
    if (is_array($value)) {
      continue;
    }

    $pretty = prettyValue($key, $value);

    echo '<tr>';
    echo '<th style="width:240px;">' . smurf_h(prettyLabel($key)) . '</th>';
    echo '<td>' . smurf_h($pretty) . '</td>';
    echo '</tr>';
  }

  echo '</tbody>';
  echo '</table>';
  echo '</div>';
}

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://{$hostname}:{$port}/admin/killsource?mount=" . urlencode($killMount);

    if (function_exists('curl_init')) {
      $ch = curl_init($killUrl);
      curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPAUTH       => CURLAUTH_BASIC,
        CURLOPT_USERPWD        => $user . ':' . $pass,
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_CONNECTTIMEOUT => 5,
      ]);
      curl_exec($ch);
      curl_close($ch);
    }
  }

  header("Location: /admin/radiostats.php");
  exit;
}

$stats = null;
$fetchError = null;

if ($hostname && $port && $user && $pass !== '') {
  $xml = fetchIcecastXml($hostname, $port, $user, $pass, $fetchError);

  if ($xml !== false) {
    libxml_use_internal_errors(true);
    $stats = simplexml_load_string($xml);
    if ($stats === false) {
      $errs = libxml_get_errors();
      $fetchError = !empty($errs) ? trim($errs[0]->message) : 'Invalid XML returned by Icecast.';
      libxml_clear_errors();
    }
  }
}

include __DIR__ . '/includes/admin_header.php';
?>

<style>
.table-wrap {
  overflow-x: auto;
  margin-top: 10px;
}
.stats-table {
  width: 100%;
  border-collapse: collapse;
}
.stats-table th,
.stats-table td {
  padding: 10px 12px;
  border-bottom: 1px solid rgba(255,255,255,.10);
  text-align: left;
  vertical-align: top;
}
.stats-table th {
  font-weight: 700;
  color: #fff;
}
.stats-table td {
  color: rgba(255,255,255,.9);
}
.mount-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin: 12px 0 0;
}
</style>

<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.<br>
      <small><?= smurf_h($fetchError ?: 'Unknown error') ?></small>
    </div>

  <?php else: ?>
    <?php
      $globalStats = xmlNodeToArray($stats);
      unset($globalStats['source']);
    ?>

    <div class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;">🌐 Global Server Stats</h3>
      <?php renderStatsTable($globalStats); ?>
    </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
            $mountData      = xmlNodeToArray($source);
            $mount          = $mountData['@mount'] ?? '(unknown)';
            $liveListeners  = (int)($mountData['listeners'] ?? 0);
            $statusColor    = mountStatusColor($liveListeners);
            $streamName     = $mountData['server_name'] ?? $mountData['title'] ?? $mount;
          ?>
          <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 style="margin:0 0 10px;"><strong><?= smurf_h($streamName) ?></strong></p>

            <?php renderStatsTable($mountData); ?>

            <div class="mount-actions">
              <?php if (!empty($mountData['listenurl'])): ?>
                <a class="admin-btn" href="<?= smurf_h($mountData['listenurl']) ?>" target="_blank" rel="noopener">Listen URL</a>
              <?php endif; ?>

              <?php if (($_SESSION['role'] ?? '') === 'admin'): ?>
                <form method="POST" onsubmit="return confirm('Kill source for <?= smurf_h($mount) ?>?');" style="margin:0;">
                  <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: ?>
                <span style="opacity:.65;">View-only mode — Kill Source disabled.</span>
              <?php endif; ?>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    <?php else: ?>
      <p>No mountpoints returned.</p>
    <?php endif; ?>

  <?php endif; ?>
</section>

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