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

$settingsFile = __DIR__ . '/../data/settings.json';
$settings = smurf_load_settings($settingsFile);
$topFile = __DIR__ . '/../data/top50.json';
$stateFile = __DIR__ . '/../data/top50_state.json';
$historyFile = __DIR__ . '/../data/charts_history.json';
$logFile = __DIR__ . '/../data/chart_plays.log';

$state = smurf_read_json($stateFile, []);
if (!is_array($state)) $state = [];
$history = smurf_read_json($historyFile, []);
if (!is_array($history)) $history = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!$CAN_EDIT) smurf_admin_denied();

  if (isset($_POST['save_top50'])) {
    $settings['top50_enabled'] = !empty($_POST['top50_enabled']);
    $settings['top50_show_in_nav'] = !empty($_POST['top50_show_in_nav']);
    smurf_save_settings($settingsFile, $settings);

    $label = trim((string)($_POST['current_week_label'] ?? ''));
    $state['current_week_label'] = $label !== '' ? $label : 'Current Weekly Chart';
    if (empty($state['last_reset_at'])) $state['last_reset_at'] = date('Y-m-d H:i:s');
    smurf_write_json($stateFile, $state);

    smurf_redirect_self(['saved'=>1]);
  }

  if (isset($_POST['publish_reset_chart'])) {
    $rows = smurf_top50_rebuild($topFile, $stateFile, $logFile);
    $label = trim((string)($_POST['archive_label'] ?? ''));
    if ($label === '') $label = trim((string)($state['current_week_label'] ?? 'Weekly Chart')) ?: 'Weekly Chart';
    $historyItem = [
      'label' => $label,
      'published_at' => date('Y-m-d H:i:s'),
      'rows' => $rows,
    ];
    array_unshift($history, $historyItem);
    $history = array_slice($history, 0, 12);
    smurf_write_json($historyFile, $history);

    $newLabel = trim((string)($_POST['next_week_label'] ?? ''));
    $state = [
      'current_week_label' => $newLabel !== '' ? $newLabel : 'Current Weekly Chart',
      'last_reset_at' => date('Y-m-d H:i:s'),
      'last_title' => '',
      'last_seen_ts' => 0,
    ];
    @file_put_contents($topFile, json_encode([], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
    @file_put_contents($stateFile, json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
    smurf_redirect_self(['published'=>1]);
  }
}

$current = smurf_chart_log_play($logFile, $stateFile);
$rows = smurf_top50_rebuild($topFile, $stateFile, $logFile);
$state = smurf_read_json($stateFile, []);
if (!is_array($state)) $state = [];
$history = smurf_read_json($historyFile, []);
if (!is_array($history)) $history = [];
$currentLabel = trim((string)($state['current_week_label'] ?? ''));
if ($currentLabel === '') $currentLabel = 'Current Weekly Chart';
include __DIR__ . '/includes/admin_header.php';
?>
<section class="content-card">
  <h1 class="admin-title">📈 Charts</h1>
  <?php if (!empty($_GET['saved'])): ?><div class="msg success">Saved.</div><?php endif; ?>
  <?php if (!empty($_GET['published'])): ?><div class="msg success">Weekly chart archived and reset.</div><?php endif; ?>
  <div class="admin-wrap stack" style="margin-top:10px;">
    <section class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;">Chart Settings</h3>
      <form method="post" class="form">
        <input type="hidden" name="save_top50" value="1">
        <label style="display:block;margin:10px 0;"><input type="checkbox" name="top50_enabled" <?= !array_key_exists('top50_enabled',$settings) || !empty($settings['top50_enabled']) ? 'checked':''; ?>> Enable Charts page</label>
        <label style="display:block;margin:10px 0;"><input type="checkbox" name="top50_show_in_nav" <?= !array_key_exists('top50_show_in_nav',$settings) || !empty($settings['top50_show_in_nav']) ? 'checked':''; ?>> Show Charts in navigation</label>
        <label class="admin-label" for="current_week_label">Current chart title</label>
        <input class="admin-input" type="text" id="current_week_label" name="current_week_label" value="<?= smurf_h($currentLabel) ?>" placeholder="Week Ending 22 March 2026">
        <?php if ($CAN_EDIT): ?><button class="admin-btn primary" type="submit">Save Settings</button><?php endif; ?>
      </form>

      <hr style="opacity:.2;margin:18px 0;">
      <h3 style="margin-top:0;">Publish and Reset Weekly Chart</h3>
      <p style="opacity:.82;">Use this when you want to close the current chart week manually and start a new one.</p>
      <form method="post" onsubmit="return confirm('Archive the current chart and start a new week?');">
        <input type="hidden" name="publish_reset_chart" value="1">
        <label class="admin-label" for="archive_label">Archive label</label>
        <input class="admin-input" type="text" id="archive_label" name="archive_label" value="<?= smurf_h($currentLabel) ?>" placeholder="Week Ending 22 March 2026">
        <label class="admin-label" for="next_week_label">Next chart title</label>
        <input class="admin-input" type="text" id="next_week_label" name="next_week_label" placeholder="Week Ending 29 March 2026">
        <?php if ($CAN_EDIT): ?><button class="admin-btn" type="submit">Publish &amp; Reset Weekly Chart</button><?php endif; ?>
      </form>

      <?php if ($current): ?><p style="margin-top:12px;"><strong>Currently tracking:</strong> <?= smurf_h($current) ?></p><?php endif; ?>
      <?php if (!empty($state['last_reset_at'])): ?><p><strong>Current week started:</strong> <?= smurf_h((string)$state['last_reset_at']) ?></p><?php endif; ?>
    </section>

    <section class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;">Current Chart</h3>
      <?php if (empty($rows)): ?><p>No chart data yet.</p><?php else: ?>
        <div class="top50-admin-list">
          <?php foreach ($rows as $idx => $row): ?>
            <div class="top50-admin-row"><strong>#<?= $idx+1 ?></strong> — <?= smurf_h($row['title'] ?? '') ?> <span style="opacity:.8;">(<?= (int)($row['count'] ?? 0) ?> spins)</span></div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </section>

    <section class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;">Archived Weeks</h3>
      <?php if (empty($history)): ?>
        <p>No archived chart weeks yet.</p>
      <?php else: ?>
        <div style="display:grid;gap:14px;">
          <?php foreach ($history as $item): ?>
            <div style="border:1px solid rgba(255,215,120,.2);border-radius:12px;padding:12px;">
              <strong><?= smurf_h((string)($item['label'] ?? 'Weekly Chart')) ?></strong><br>
              <span style="opacity:.78;">Published <?= smurf_h((string)($item['published_at'] ?? '')) ?></span>
              <?php $top = $item['rows'][0] ?? null; ?>
              <div style="margin-top:8px;"><?= $top ? ('No. 1: ' . smurf_h((string)($top['title'] ?? '')) . ' (' . (int)($top['count'] ?? 0) . ' spins)') : 'No saved rows in that archive.' ?></div>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </section>
  </div>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
