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

$requestsFile = __DIR__ . '/data/requests.txt';
$requests = file_exists($requestsFile) ? file($requestsFile, FILE_IGNORE_NEW_LINES) : [];

/* ------------------------------------------------------------
   HANDLE FORM SUBMISSION
------------------------------------------------------------ */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);
    $song = trim($_POST['song']);
    $artist = trim($_POST['artist']);
    $message = trim($_POST['message']);
    $dedication = trim($_POST['dedication']);

    if ($name && $song && $artist) {
        $entry = implode('|', [
            uniqid(),
            $name,
            $song,
            $artist,
            $message,
            $dedication,
            date('Y-m-d H:i:s'),
            'no' // not approved yet
        ]) . "\n";

        file_put_contents($requestsFile, $entry, FILE_APPEND);
        $successMessage = "<div class='msg success'>Your request has been submitted! It will appear once approved.</div>";
    } else {
        $errorMessage = "<div class='msg error'>Please fill in all required fields.</div>";
    }
}

/* ------------------------------------------------------------
   LOAD APPROVED REQUESTS
------------------------------------------------------------ */
$approved = [];
foreach ($requests as $line) {
    $parts = explode('|', $line);
    if (count($parts) === 8 && $parts[7] === 'yes') {
        $approved[] = $parts;
    }
}
$approved = array_reverse($approved);

/* ------------------------------------------------------------
   MOST REQUESTED SONGS CHART
------------------------------------------------------------ */
$counts = [];

foreach ($approved as $req) {
    list($id, $name, $song, $artist, $msg, $ded, $ts) = $req;

    $key = strtolower(trim($song)) . '|' . strtolower(trim($artist));

    if (!isset($counts[$key])) {
        $counts[$key] = [
            'song' => $song,
            'artist' => $artist,
            'count' => 0
        ];
    }

    $counts[$key]['count']++;
}

usort($counts, function($a, $b) {
    return $b['count'] - $a['count'];
});

$topRequested = array_slice($counts, 0, 10);
?>

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

        <!-- PAGE HEADER -->
        <div class="requests-banner">
            <h1 class="requests-banner-text">🎧 Song Requests</h1>
            <p class="requests-subtext">Tell us what you want to hear!</p>
        </div>

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

        <!-- REQUEST FORM -->
        <div class="content-box">
            <?= $successMessage ?? '' ?>
            <?= $errorMessage ?? '' ?>

            <h3 class="section-title center-text">Request a Song</h3>

            <form method="POST" class="form">

                <input type="text" name="name" class="input-field" placeholder="Your Name" required>

                <input type="text" name="song" class="input-field" placeholder="Song Title" required>

                <input type="text" name="artist" class="input-field" placeholder="Artist" required>

                <textarea name="message" class="input-field" placeholder="Message (optional)"></textarea>

                <input type="text" name="dedication" class="input-field" placeholder="Dedication (optional)">

                <button type="submit" class="button radio-static">Submit Request</button>
            </form>
        </div>

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

        <!-- RECENT APPROVED REQUESTS -->
        <div class="content-box">
            <h3 class="section-title center-text">📻 Recent Requests</h3>

            <?php if (!$approved): ?>
                <p class="about-text center-text">No approved requests yet.</p>
            <?php else: ?>
                <?php foreach (array_slice($approved, 0, 10) as $req): ?>
                    <?php list($id, $name, $song, $artist, $msg, $ded, $ts) = $req; ?>

                    <div class="neon-card request-card">
                        <h4><?= htmlspecialchars($song) ?> — <span><?= htmlspecialchars($artist) ?></span></h4>

                        <p class="about-text">
                            Requested by <strong><?= htmlspecialchars($name) ?></strong>
                            on <?= date('M j, Y g:i A', strtotime($ts)) ?>
                        </p>

                        <?php if ($msg): ?>
                            <p class="about-text"><em>"<?= htmlspecialchars($msg) ?>"</em></p>
                        <?php endif; ?>

                        <?php if ($ded): ?>
                            <p class="about-text dedication">💙 <?= htmlspecialchars($ded) ?></p>
                        <?php endif; ?>
                    </div>

                    <div class="vinyl-divider center-divider"></div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

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

        <!-- MOST REQUESTED SONGS -->
        <div class="content-box">
            <h3 class="section-title center-text">🔥 Most Requested Songs</h3>

            <?php if (!$topRequested): ?>
                <p class="about-text center-text">No requests yet.</p>
            <?php else: ?>

                <div class="most-requested-grid">

                    <?php foreach ($topRequested as $i => $entry): ?>
                        <div class="most-requested-card rank-<?= $i+1 ?>">

                            <div class="mr-rank"><?= $i+1 ?></div>

                            <div class="mr-info">
                                <h4><?= htmlspecialchars($entry['song']) ?></h4>
                                <p><?= htmlspecialchars($entry['artist']) ?></p>
                                <span class="mr-count"><?= $entry['count'] ?> requests</span>
                            </div>

                        </div>
                    <?php endforeach; ?>

                </div>

            <?php endif; ?>
        </div>

        <!-- BACK BUTTON -->
        <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>

