<?php
session_start();
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';

$historyFile = __DIR__ . '/playhistory.json';
$history = file_exists($historyFile)
    ? json_decode(file_get_contents($historyFile), true)
    : [];

arsort($history); // Sort by play count DESC
$top50 = array_slice($history, 0, 50, true);
?>

<div class="main-wrap">
    <div class="content-panel">

        <div class="chart-banner">
            <h1 class="chart-banner-text">🎧 Top 50 Countdown</h1>
            <p class="chart-subtext">Automatically updated from real play history!</p>
        </div>

        <div class="vinyl-divider center-divider"></div>

        <?php if (empty($top50)): ?>
            <div class="content-box center-text">
                <h3 class="section-title">No Chart Data Yet</h3>
                <p class="about-text">Tracks will appear here as they are played.</p>
            </div>
        <?php else: ?>

            <div class="chart-grid">
                <?php
                $rank = 1;
                foreach ($top50 as $track => $plays):
                    // Split "Artist - Song" format
                    $parts = explode(' - ', $track, 2);
                    $artist = $parts[0] ?? 'Unknown Artist';
                    $song   = $parts[1] ?? $track;
                ?>

                <div class="chart-card rank-<?= $rank ?>">

                    <div class="rank-badge"><?= $rank ?></div>

                    <div class="chart-info">
                        <h3><?= htmlspecialchars($song) ?></h3>
                        <p><?= htmlspecialchars($artist) ?></p>
                        <small>Plays: <?= $plays ?></small>
                    </div>

                </div>

                <?php
                $rank++;
                endforeach;
                ?>
            </div>

        <?php endif; ?>

        <div class="vinyl-divider center-divider"></div>

        <div class="content-box center-text">
            <a href="index.php" class="button radio-static">⬅ Back to Home</a>
        </div>

<?php include __DIR__ . '/includes/footer.php'; ?>
    </div>
</div>
