<?php require_once __DIR__ . '/includes/admin_bootstrap.php';
ugfx_require_permission('charts');
$message = '';
$editing = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? 'save');

    if ($action === 'sync_now') {
        $sync = ugfx_chart_autoupdate(true);
        $message = !empty($sync['recorded'])
            ? 'Live chart sync captured the current track and updated the chart.'
            : 'Live chart sync ran, but there was no new track change to record.';
    } elseif ($action === 'rebuild_history') {
        $days = max(1, (int)($_POST['window_days'] ?? 30));
        ugfx_chart_rebuild_from_history($days);
        $message = 'Chart rebuilt from auto-capture history.';
    } elseif ($action === 'delete') {
        $title = trim((string)($_POST['title'] ?? ''));
        $items = ugfx_top50_all();
        $items = array_values(array_filter($items, fn($item) => strcasecmp((string)($item['title'] ?? ''), $title) !== 0));
        ugfx_save_top50($items);
        $message = 'Chart entry deleted.';
    } elseif ($action === 'clear_all') {
        ugfx_save_top50([]);
        $message = 'All chart entries cleared.';
    } elseif ($action === 'bulk_import') {
        $items = ugfx_top50_all();
        $mode = trim((string)($_POST['import_mode'] ?? 'replace'));
        $parsed = ugfx_top50_parse_bulk((string)($_POST['bulk_data'] ?? ''));
        if ($mode === 'append') {
            $merged = [];
            foreach ($items as $row) {
                $merged[strtolower((string)($row['title'] ?? ''))] = $row;
            }
            foreach ($parsed as $row) {
                $key = strtolower((string)($row['title'] ?? ''));
                if (isset($merged[$key])) {
                    $existing = $merged[$key];
                    $row['first_seen'] = $existing['first_seen'] ?? ($row['first_seen'] ?? '');
                }
                $merged[$key] = $row;
            }
            ugfx_save_top50(array_values($merged));
            $message = 'Bulk import appended to chart data.';
        } else {
            ugfx_save_top50($parsed);
            $message = 'Bulk import replaced chart data.';
        }
    } else {
        $items = ugfx_top50_all();
        $title = trim((string)($_POST['title'] ?? ''));
        $artist = trim((string)($_POST['artist'] ?? ''));
        $song = trim((string)($_POST['song'] ?? ''));
        if ($title === '' && $artist !== '' && $song !== '') {
            $title = $artist . ' - ' . $song;
        }
        if ($title !== '') {
            $entry = ugfx_top50_normalize_item([
                'title' => $title,
                'artist' => $artist,
                'song' => $song,
                'count' => (int)($_POST['count'] ?? 0),
                'first_seen' => trim((string)($_POST['first_seen'] ?? '')),
                'last_seen' => trim((string)($_POST['last_seen'] ?? '')),
                'updated_at' => date('Y-m-d H:i:s'),
                'source' => trim((string)($_POST['source'] ?? 'manual')),
                'notes' => trim((string)($_POST['notes'] ?? '')),
            ], $title);
            $updated = false;
            foreach ($items as &$item) {
                if (strcasecmp((string)($item['title'] ?? ''), $title) === 0) {
                    if (($entry['first_seen'] ?? '') === '') {
                        $entry['first_seen'] = (string)($item['first_seen'] ?? '');
                    }
                    $item = $entry;
                    $updated = true;
                    break;
                }
            }
            unset($item);
            if (!$updated) {
                if (($entry['first_seen'] ?? '') === '') {
                    $entry['first_seen'] = date('Y-m-d H:i:s');
                }
                $items[] = $entry;
            }
            ugfx_save_top50($items);
            $message = $updated ? 'Chart entry updated.' : 'Chart entry added.';
        } else {
            $message = 'Enter a track title or artist and song name.';
        }
    }
}

$items = ugfx_top50_all();
$stats = ugfx_top50_stats();
$meta = ugfx_chart_meta();
$history = ugfx_chart_history(25);

$editTitle = trim((string)($_GET['edit'] ?? ''));
if ($editTitle !== '') {
    foreach ($items as $item) {
        if (strcasecmp((string)($item['title'] ?? ''), $editTitle) === 0) {
            $editing = $item;
            break;
        }
    }
}

$adminTitle = 'Charts';
include __DIR__ . '/includes/admin_header.php';
?>
<?php if ($message): ?><div class="ugfx-admin-alert"><?= htmlspecialchars($message) ?></div><?php endif; ?>
<div class="row g-4 mb-4">
  <div class="col-md-3"><div class="ugfx-card p-4"><div class="ugfx-micro-label">TRACKS</div><h2><?= (int)($stats['tracks'] ?? 0) ?></h2><div class="text-secondary">Auto-ranked entries</div></div></div>
  <div class="col-md-3"><div class="ugfx-card p-4"><div class="ugfx-micro-label">TOTAL PLAYS</div><h2><?= (int)($stats['total_plays'] ?? 0) ?></h2><div class="text-secondary">Captured spins</div></div></div>
  <div class="col-md-3"><div class="ugfx-card p-4"><div class="ugfx-micro-label">AUTO CAPTURES</div><h2><?= (int)($meta['recorded_count'] ?? 0) ?></h2><div class="text-secondary">Track changes logged</div></div></div>
  <div class="col-md-3"><div class="ugfx-card p-4"><div class="ugfx-micro-label">LAST SYNC</div><h2 style="font-size:1rem"><?= htmlspecialchars((string)($meta['last_recorded_at'] ?? ($meta['last_poll_at'] ?? 'Waiting'))) ?></h2><div class="text-secondary">Most recent live capture</div></div></div>
</div>

<div class="row g-4 mb-4">
  <div class="col-xl-5">
    <div class="ugfx-card p-4 h-100">
      <div class="ugfx-micro-label">LIVE CHART ENGINE</div>
      <h3>Auto-update status</h3>
      <p class="text-secondary">The chart now watches the live Icecast metadata and logs a new spin whenever the current track changes. Manual editing still works, but the board no longer depends on hand updates.</p>
      <div class="small text-secondary mb-3">
        <div><strong>Last seen title:</strong> <?= htmlspecialchars((string)($meta['last_seen_title'] ?? 'Waiting for metadata')) ?></div>
        <div><strong>Last mount:</strong> <?= htmlspecialchars((string)($meta['last_mount'] ?? '/stream')) ?></div>
        <div><strong>Last poll:</strong> <?= htmlspecialchars((string)($meta['last_poll_at'] ?? 'Not polled yet')) ?></div>
        <div><strong>Window:</strong> <?= (int)($meta['window_days'] ?? 30) ?> days</div>
      </div>
      <div class="d-flex gap-2 flex-wrap mb-4">
        <form method="post">
          <input type="hidden" name="action" value="sync_now">
          <button class="btn ugfx-btn-primary">Sync now</button>
        </form>
        <a class="btn ugfx-btn-outline" href="../charts.php" target="_blank">View public chart</a>
      </div>
      <form method="post" class="row g-3 align-items-end">
        <input type="hidden" name="action" value="rebuild_history">
        <div class="col-md-6">
          <label class="form-label">Rebuild from history</label>
          <select class="form-select" name="window_days">
            <option value="7">Last 7 days</option>
            <option value="14">Last 14 days</option>
            <option value="30" selected>Last 30 days</option>
            <option value="60">Last 60 days</option>
          </select>
        </div>
        <div class="col-md-6">
          <button class="btn ugfx-btn-outline w-100">Rebuild chart</button>
        </div>
      </form>
    </div>
  </div>

  <div class="col-xl-7">
    <div class="ugfx-card p-4 h-100">
      <div class="ugfx-micro-label">RECENT SPINS</div>
      <h3>Latest auto-detected track changes</h3>
      <div class="table-responsive mt-3">
        <table class="table ugfx-table align-middle">
          <thead><tr><th>Track</th><th>Seen</th><th>Mount</th><th>Listeners</th></tr></thead>
          <tbody>
          <?php foreach ($history as $row): ?>
            <tr>
              <td><?= htmlspecialchars((string)($row['title'] ?? 'Track')) ?></td>
              <td><?= htmlspecialchars((string)($row['seen_at'] ?? '')) ?></td>
              <td><?= htmlspecialchars((string)($row['mount'] ?? '')) ?></td>
              <td><?= (int)($row['listeners'] ?? 0) ?></td>
            </tr>
          <?php endforeach; ?>
          <?php if (!$history): ?>
            <tr><td colspan="4" class="text-center text-secondary py-4">Recent auto-captures will appear here once the live track changes.</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<div class="row g-4">
  <div class="col-xl-5">
    <div class="ugfx-card p-4 h-100">
      <div class="ugfx-micro-label">MANUAL OVERRIDE</div>
      <h3><?= $editing ? 'Edit chart entry' : 'Add chart entry' ?></h3>
      <p class="text-secondary">Use this only when you need to fix a title, merge an artist name, or seed the chart with older data. Auto-capture will continue after manual changes.</p>
      <form method="post" class="ugfx-admin-form row g-3">
        <input type="hidden" name="action" value="save">
        <div class="col-12"><input class="form-control" name="title" placeholder="Artist - Song" value="<?= htmlspecialchars((string)($editing['title'] ?? '')) ?>"></div>
        <div class="col-md-6"><input class="form-control" name="artist" placeholder="Artist" value="<?= htmlspecialchars((string)($editing['artist'] ?? '')) ?>"></div>
        <div class="col-md-6"><input class="form-control" name="song" placeholder="Song title" value="<?= htmlspecialchars((string)($editing['song'] ?? '')) ?>"></div>
        <div class="col-md-4"><input class="form-control" type="number" min="0" name="count" placeholder="Plays" value="<?= htmlspecialchars((string)($editing['count'] ?? '0')) ?>"></div>
        <div class="col-md-4"><input class="form-control" name="first_seen" placeholder="First seen" value="<?= htmlspecialchars((string)($editing['first_seen'] ?? '')) ?>"></div>
        <div class="col-md-4"><input class="form-control" name="last_seen" placeholder="Last seen" value="<?= htmlspecialchars((string)($editing['last_seen'] ?? '')) ?>"></div>
        <div class="col-md-6"><input class="form-control" name="source" placeholder="Source" value="<?= htmlspecialchars((string)($editing['source'] ?? 'manual')) ?>"></div>
        <div class="col-md-6"><input class="form-control" name="notes" placeholder="Notes" value="<?= htmlspecialchars((string)($editing['notes'] ?? '')) ?>"></div>
        <div class="col-12 d-flex gap-2 flex-wrap">
          <button class="btn ugfx-btn-primary">Save chart entry</button>
          <?php if ($editing): ?><a class="btn ugfx-btn-outline" href="charts.php">New entry</a><?php endif; ?>
        </div>
      </form>
    </div>
  </div>

  <div class="col-xl-7">
    <div class="ugfx-card p-4 h-100">
      <div class="d-flex justify-content-between gap-3 flex-wrap align-items-start">
        <div>
          <div class="ugfx-micro-label">BULK TOOLS</div>
          <h3>Import or replace chart data</h3>
          <p class="text-secondary mb-0">Paste lines as <code>Artist - Song | Plays | Last seen | Notes</code>. You can use <code>|</code>, tab, or <code>;</code> between columns.</p>
        </div>
        <form method="post" onsubmit="return confirm('Clear all chart entries?');">
          <input type="hidden" name="action" value="clear_all">
          <button class="btn btn-outline-danger btn-sm">Clear all</button>
        </form>
      </div>
      <form method="post" class="mt-3 row g-3">
        <input type="hidden" name="action" value="bulk_import">
        <div class="col-12"><textarea class="form-control" name="bulk_data" rows="8" placeholder="The Ronnettes - Be my baby | 12 | 2026-04-03 21:00:00 | imported"></textarea></div>
        <div class="col-md-4">
          <select class="form-select" name="import_mode">
            <option value="replace">Replace everything</option>
            <option value="append">Append / update existing</option>
          </select>
        </div>
        <div class="col-md-8 d-flex gap-2 flex-wrap">
          <button class="btn ugfx-btn-primary">Run import</button>
          <button type="button" class="btn ugfx-btn-outline" onclick="this.form.querySelector('textarea').value='The Ronnettes - Be my baby | 12 | <?= date('Y-m-d H:i:s') ?> | imported history';">Load example</button>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="ugfx-card p-4 mt-4">
  <div class="ugfx-admin-toolbar">
    <div>
      <div class="ugfx-micro-label">LIVE CHART LIST</div>
      <h3 class="mb-0">Top 50 manager</h3>
    </div>
    <span class="ugfx-chip"><?= count($items) ?> entries</span>
  </div>
  <div class="table-responsive mt-3">
    <table class="table ugfx-table align-middle">
      <thead><tr><th>#</th><th>Track</th><th>Plays</th><th>Last seen</th><th>Source</th><th></th></tr></thead>
      <tbody>
      <?php foreach ($items as $index => $item): ?>
        <tr>
          <td><?= $index + 1 ?></td>
          <td>
            <div class="fw-semibold"><?= htmlspecialchars((string)($item['title'] ?? 'Untitled')) ?></div>
            <?php if (!empty($item['notes'])): ?><div class="text-secondary small"><?= htmlspecialchars((string)$item['notes']) ?></div><?php endif; ?>
          </td>
          <td><?= (int)($item['count'] ?? 0) ?></td>
          <td><?= htmlspecialchars((string)($item['last_seen'] ?? '')) ?></td>
          <td><?= htmlspecialchars((string)($item['source'] ?? 'manual')) ?></td>
          <td>
            <div class="d-flex gap-2 flex-wrap justify-content-end">
              <a class="btn ugfx-btn-outline btn-sm" href="charts.php?edit=<?= urlencode((string)($item['title'] ?? '')) ?>">Edit</a>
              <form method="post" onsubmit="return confirm('Delete this chart entry?');">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="title" value="<?= htmlspecialchars((string)($item['title'] ?? '')) ?>">
                <button class="btn btn-outline-danger btn-sm">Delete</button>
              </form>
            </div>
          </td>
        </tr>
      <?php endforeach; ?>
      <?php if (!$items): ?>
        <tr><td colspan="6" class="text-center text-secondary py-4">No chart data yet. The board will start filling as live tracks change.</td></tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
