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

date_default_timezone_set('America/New_York');

/* ------------------------------
   VISITOR COUNTER
------------------------------ */
$counterFile = __DIR__ . '/data/visitor_count.txt';
if (!file_exists($counterFile)) file_put_contents($counterFile, '0');
$visitorCount = (int)file_get_contents($counterFile) + 1;
file_put_contents($counterFile, $visitorCount);

/* ------------------------------
   DJ SCHEDULE
------------------------------ */
$scheduleFile = __DIR__ . '/data/schedule.txt';
$currentDay   = date('l');
$currentHour  = date('H') . ':00';

$schedule = [];
if (file_exists($scheduleFile)) {
    foreach (file($scheduleFile, FILE_IGNORE_NEW_LINES) as $line) {
        $parts = explode('|', trim($line));
        if (count($parts) === 3) {
            [$day, $hour, $dj] = $parts;
            $schedule[$day][$hour] = $dj;
        }
    }
}

$currentDJ     = $schedule[$currentDay][$currentHour] ?? 'Auto DJ';
$nextHourIndex = (int)substr($currentHour, 0, 2) + 1;
$nextHour      = str_pad($nextHourIndex % 24, 2, '0', STR_PAD_LEFT) . ':00';
$nextDJ        = $schedule[$currentDay][$nextHour] ?? 'Auto DJ';

$comingAfter = [];
$hour = str_pad(($nextHourIndex + 1) % 24, 2, '0', STR_PAD_LEFT) . ':00';
$comingAfter[] = $schedule[$currentDay][$hour] ?? 'Auto DJ';

/* ------------------------------
   POLL
------------------------------ */
$pollFile  = __DIR__ . '/data/poll.txt';
$votesFile = __DIR__ . '/data/poll_votes.txt';

$poll  = file_exists($pollFile) ? file($pollFile, FILE_IGNORE_NEW_LINES) : [];
$votes = file_exists($votesFile) ? array_map('intval', file($votesFile, FILE_IGNORE_NEW_LINES)) : [];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['vote'])) {
    $i = (int)$_POST['vote'];
    $votes[$i] = ($votes[$i] ?? 0) + 1;
    file_put_contents($votesFile, implode("\n", $votes));
    $pollMessage = "<div class='msg success'>Thanks for voting!</div>";
}

/* ------------------------------
   COMMENTS
------------------------------ */
$commentsFile = __DIR__ . '/data/comments.txt';
$bannedFile   = __DIR__ . '/data/banned_ips.txt';
$userIP       = $_SERVER['REMOTE_ADDR'];
$banned       = file_exists($bannedFile) ? file($bannedFile, FILE_IGNORE_NEW_LINES) : [];

if ($_SERVER['REQUEST_METHOD'] === 'POST'
    && !empty($_POST['comment'])
    && !empty($_POST['name'])
    && !isset($_POST['vote'])) {

    if (in_array($userIP, $banned)) {
        $commentMessage = "<div class='msg error'>Your IP is banned from posting comments.</div>";
    } else {
        $entry = implode('|', [
            uniqid(),
            trim($_POST['name']),
            trim($_POST['comment']),
            $userIP,
            date('Y-m-d H:i:s'),
            'no'
        ]) . "\n";

        file_put_contents($commentsFile, $entry, FILE_APPEND);
        $commentMessage = "<div class='msg success'>Thanks for your comment! It will appear once approved.</div>";
    }
}
?>

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

        <!-- HERO -->
        <div class="hero">
            <img src="../assets/images/logo.png" class="hero-logo" alt="Oldies and More! Radio">
            <h1 class="neon-flicker">Oldies and More! Radio</h1>
            <p class="tagline">Where the jukebox never sleeps</p>

            <a href="http://cr3.broadcasturself.com:23990/stream" class="button play radio-static">▶ Play Now</a>

            <!-- Directory/Player Links (same style as existing buttons) -->
            <div class="service-buttons">

                <a href="http://e.mytuner-radio.com/embed/your-oldies-radio-504699"
                   target="_blank"
                   rel="noopener"
                   class="neon-service-btn">
                    <img src="https://static2.mytuner.mobi/static/widgets/mytuner-radio.png" alt="">
                    Listen on MyTuner
                </a>

                <a href="http://p.onlineradiobox.com/us/youroldies/player/?played=1&cs=us.youroldies"
                   target="_blank"
                   rel="noopener"
                   class="neon-service-btn">
                    <img src="https://cdn.onlineradiobox.com/img/b/88x31.png" alt="">
                    Listen on RadioBox
                </a>

                <!-- US-RADIO.COM (link only, no widget) -->
                <a href="https://us-radio.com/oldies-and-more-radio-r29439"
                   target="_blank"
                   rel="noopener"
                   class="neon-service-btn">
                    <img src="//cdn.listenonlineradio.com/embed-player/us-logo.png" alt="">
                    Listen on US-RADIO
                </a>

                <!-- RadioSpinner (link only). Replace URL with your station page if you have it -->
                <a href="https://radiospinner.com/"
                   target="_blank"
                   rel="noopener"
                   class="neon-service-btn">
                    <img src="https://www.google.com/s2/favicons?domain=radiospinner.com&sz=64" alt="">
                    Listen on RadioSpinner
                </a>

            </div>
        </div>

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

        <!-- DUAL CLOCK -->
        <div class="content-box center-text">
            <h4 class="section-title center-text">⏰ Current Time</h4>

            <div class="clock-flex">
                <div class="clock-box">
                    <strong>Your Time:</strong><br>
                    <span id="localTime">--:--</span>
                </div>

                <div class="clock-box">
                    <strong>Station Time (EST):</strong><br>
                    <span id="estTime">--:--</span>
                </div>
            </div>
        </div>

        <script>
            function updateClocks() {
                const now = new Date();

                document.getElementById('localTime').textContent =
                    now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });

                const est = new Date().toLocaleString("en-US", { timeZone: "America/New_York" });
                const estDate = new Date(est);
                document.getElementById('estTime').textContent =
                    estDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
            }
            setInterval(updateClocks, 1000);
            updateClocks();
        </script>

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

        <!-- DJ SCHEDULE -->
        <div class="schedule">
            <div class="schedule-box radio-static">
                <h3>Now On Air</h3>
                <p><strong><?= htmlspecialchars($currentDJ) ?></strong> (<?= htmlspecialchars($currentHour) ?> EST)</p>
            </div>

            <div class="schedule-box radio-static">
                <h3>Next Up</h3>
                <p><strong><?= htmlspecialchars($nextDJ) ?></strong> (<?= htmlspecialchars($nextHour) ?> EST)</p>
            </div>

            <div class="schedule-box radio-static">
                <h3>Coming After</h3>
                <?php foreach ($comingAfter as $dj): ?>
                    <p><strong><?= htmlspecialchars($dj) ?></strong></p>
                <?php endforeach; ?>
            </div>
        </div>

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

        <!-- NOW PLAYING -->
        <div class="content-box" id="nowplaying-box">
            <h4 class="section-title center-text">
                🎶 What’s Playing Now
                <span class="live-indicator">
                    <span class="live-dot"></span>
                    <span class="live-text">LIVE</span>
                </span>
            </h4>

            <div id="nowplaying-content">
                <?php include __DIR__ . '/nowplaying.php'; ?>
            </div>
        </div>

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

        <!-- COMMENT FORM -->
        <div class="content-box">
            <h4 class="section-title">💬 Leave a Comment</h4>
            <?= $commentMessage ?? '' ?>

            <form method="POST" class="form">
                <input type="text" name="name" class="input-field" placeholder="Your name" required>
                <textarea name="comment" class="input-field" placeholder="Share your thoughts..." required></textarea>
                <button type="submit" class="button radio-static">Post Comment</button>
            </form>
        </div>

        <!-- RECENT COMMENTS -->
        <div class="content-box">
            <h4 class="section-title">🗨️ Recent Comments</h4>
            <?php
            $comments = file_exists($commentsFile) ? file($commentsFile, FILE_IGNORE_NEW_LINES) : [];
            $approved = array_filter($comments, fn($l) => explode('|', $l)[5] === 'yes');
            $recent   = array_slice(array_reverse($approved), 0, 3);

            if (!$recent) {
                echo "<p>No comments yet.</p>";
            } else {
                foreach ($recent as $line) {
                    [$id,$name,$msg,$ip,$ts] = explode('|', $line);
                    echo "<div class='comment'>";
                    echo "<strong>" . htmlspecialchars($name) . "</strong><br>";
                    echo nl2br(htmlspecialchars($msg));
                    echo "<br><small>" . date('M j, Y g:i A', strtotime($ts)) . "</small>";
                    echo "</div>";
                }
            }
            ?>
        </div>

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

        <!-- POLL -->
        <?php if ($poll): list($q_en) = explode('|', $poll[0]); ?>
            <div class="content-box">
                <h4 class="section-title">📊 Station Poll</h4>
                <?= $pollMessage ?? '' ?>
                <p><strong><?= htmlspecialchars($q_en) ?></strong></p>

                <form method="POST" class="form">
                    <?php foreach (array_slice($poll, 1) as $i => $line): list($opt_en) = explode('|', $line); ?>
                        <label class="radio">
                            <input type="radio" name="vote" value="<?= $i ?>" required>
                            <?= htmlspecialchars($opt_en) ?>
                        </label>
                    <?php endforeach; ?>

                    <button type="submit" class="button radio-static">Vote</button>
                </form>

                <div class="poll-results">
                    <?php foreach (array_slice($poll, 1) as $i => $line): list($opt_en) = explode('|', $line); ?>
                        <p><?= htmlspecialchars($opt_en) ?> — <strong><?= $votes[$i] ?? 0 ?></strong> votes</p>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>

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

        <!-- VISITOR COUNTER -->
        <div class="content-box center-text">
            <p>👀 Visitors so far: <?= (int)$visitorCount ?></p>
        </div>

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