<?php
require_once __DIR__ . '/includes/stream_lib.php';
include __DIR__ . '/includes/header.php';

$topFile = __DIR__ . '/data/top50.json';
$stateFile = __DIR__ . '/data/top50_state.json';
$historyFile = __DIR__ . '/data/charts_history.json';
$logFile = __DIR__ . '/data/chart_plays.log';

$settings = smurf_load_public_settings();
if (array_key_exists('top50_enabled', $settings) && empty($settings['top50_enabled'])) {
    http_response_code(404);
    echo '<div class="container content-box mt-5"><div class="bg-light p-4 rounded"><h1>Charts are currently offline</h1><p>Please check back later.</p></div></div>';
    include __DIR__ . '/includes/footer.php';
    return;
}

smurf_chart_log_play($logFile, $stateFile);
$rows = smurf_top50_rebuild($topFile, $stateFile, $logFile);
$state = is_file($stateFile) ? json_decode((string)file_get_contents($stateFile), true) : [];
if (!is_array($state)) $state = [];
$history = is_file($historyFile) ? json_decode((string)file_get_contents($historyFile), true) : [];
if (!is_array($history)) $history = [];
$latestWeek = $history[0] ?? null;
$currentLabel = trim((string)($state['current_week_label'] ?? ''));
if ($currentLabel === '') $currentLabel = 'Current Weekly Chart';
?>
<div class="container content-box mt-5">
  <div class="text-center mb-5">
    <h1>Charts</h1>
    <p class="subtext">Weekly chart tracking for Home Time Radio.</p>
  </div>

  <div class="htr-box mb-4">
    <div class="d-flex flex-wrap justify-content-between align-items-start gap-3">
      <div>
        <h3 class="mb-1"><?= htmlspecialchars($currentLabel, ENT_QUOTES, 'UTF-8') ?></h3>
        <p class="mb-0">This chart updates automatically from the station stream and can be reset manually in admin when a new chart week starts.</p>
      </div>
      <?php if (!empty($state['last_reset_at'])): ?>
        <div><strong>Week started:</strong> <?= htmlspecialchars((string)$state['last_reset_at'], ENT_QUOTES, 'UTF-8') ?></div>
      <?php endif; ?>
    </div>
  </div>

  <div class="htr-box mb-4">
    <?php if (!$rows): ?>
      <p>No chart data yet. Let the stream run and this week will start building automatically.</p>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table table-dark table-striped align-middle">
          <thead><tr><th>#</th><th>Track</th><th>Spins This Week</th><th>Last Seen</th></tr></thead>
          <tbody>
            <?php foreach ($rows as $i => $row): ?>
              <tr>
                <td><?= $i + 1 ?></td>
                <td><?= htmlspecialchars((string)($row['title'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                <td><?= (int)($row['count'] ?? 0) ?></td>
                <td><?= htmlspecialchars((string)($row['last_seen'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>

  <?php if ($latestWeek): ?>
    <div class="htr-box">
      <h3>Previous No. 1</h3>
      <p class="mb-1"><strong><?= htmlspecialchars((string)($latestWeek['label'] ?? 'Previous Week'), ENT_QUOTES, 'UTF-8') ?></strong></p>
      <?php $topTrack = $latestWeek['rows'][0] ?? null; ?>
      <?php if ($topTrack): ?>
        <p class="mb-0"><?= htmlspecialchars((string)($topTrack['title'] ?? ''), ENT_QUOTES, 'UTF-8') ?> — <?= (int)($topTrack['count'] ?? 0) ?> spins</p>
      <?php else: ?>
        <p class="mb-0">No archived chart rows yet.</p>
      <?php endif; ?>
    </div>
  <?php endif; ?>
</div>
<?php include __DIR__ . '/includes/footer.php'; ?>
