<?php
session_start();
$role = $_SESSION['role'] ?? 'guest';
$username = $_SESSION['username'] ?? 'Admin';
if (!in_array($role, ['master','admin'])) {
  header('Location: /login/index.php');
  exit;
}

include('../header.php');
include('../menu.php');
?>
<link rel="stylesheet" href="/css/style.css?v=1">

<main class="main-container">
  <section class="admin-card">
    <h2 class="text-warning">🎚️ Icecast Admin</h2>
    <p class="text-muted">Logged in as <strong><?= htmlspecialchars($username) ?></strong> (<?= $role ?>)</p>

    <?php
    // Icecast server details
    $icecastUrl = "http://cr3.broadcasturself.com:6969/admin/stats";
    $icecastUser = "AlmostHeavenRadio";
    $icecastPass = "f846z35Frqm";

    // Fetch stats XML
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $icecastUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERPWD, "$icecastUser:$icecastPass");
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    $response = curl_exec($ch);
    curl_close($ch);

    if ($response === false) {
      echo "<p class='text-danger'>Unable to connect to Icecast server.</p>";
    } else {
      $xml = simplexml_load_string($response);
      if ($xml === false) {
        echo "<p class='text-danger'>Failed to parse Icecast stats.</p>";
      } else {
        // Global stats
        echo "<h3 class='mb-3 text-warning'>Global Server Stats</h3>";
        echo "<table class='admin-table mb-4'>";
        foreach ($xml as $key => $value) {
          if ($key != 'source') {
            echo "<tr><td><strong>$key</strong></td><td>$value</td></tr>";
          }
        }
        echo "</table>";

        // Mountpoints
        if (!empty($xml->source)) {
          echo "<h3 class='mb-3 text-warning'>Mountpoints</h3>";
          foreach ($xml->source as $source) {
            $mount = (string)$source['mount'];
            $currentTrack = (string)$source->title;

            echo "<div class='admin-mount-card mb-4'>";
            echo "<h4 class='text-warning'>Mountpoint: $mount</h4>";
            echo "<ul class='admin-list'>";
            foreach ($source as $sKey => $sVal) {
              echo "<li><strong>$sKey:</strong> $sVal</li>";
            }
            echo "</ul>";

            // Logging system
            $logFile = __DIR__ . '/../data/played.txt';
            if ($currentTrack) {
              $lines = file_exists($logFile) ? file($logFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : [];
              $lastLine = end($lines);
              $lastTrack = $lastLine ? explode(" | ", $lastLine, 2)[1] ?? '' : '';

              if ($currentTrack !== $lastTrack) {
                $lines[] = date('Y-m-d H:i:s') . " | " . $currentTrack;
              }
              if (count($lines) > 1000) {
                $lines = array_slice($lines, -1000);
              }
              file_put_contents($logFile, implode("\n", $lines));
            }

            // Show last 50
            $lines = file_exists($logFile) ? file($logFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : [];
            $last50 = array_slice($lines, -50);
            echo "<h5 class='text-warning mt-3'>🎶 Last 50 Songs Played</h5>";
            echo "<ol class='chart-list'>";
            foreach ($last50 as $line) {
              echo "<li>" . htmlspecialchars($line) . "</li>";
            }
            echo "</ol>";

            echo "<div class='mt-2'>";
            $baseUrl = "http://cr3.broadcasturself.com:6969/admin";
            echo "<a href='$baseUrl/killsource?mount=$mount' target='_blank' class='btn btn-danger btn-sm'>Kill Source</a> ";
            echo "<a href='$baseUrl/listclients?mount=$mount' target='_blank' class='btn btn-dark btn-sm'>List Clients</a>";
            echo "</div>";

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

<?php include('../footer.php'); ?>
