<?php include 'includes/header.php'; ?>
<?php include 'includes/sidebar.php'; ?>

<?php
session_start();
include 'includes/header.php';
include '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) {
        [$day, $hour, $dj] = explode('|', trim($line));
        $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='alert alert-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='alert alert-danger'>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='alert alert-success'>Thanks for your comment! It will appear once approved.</div>";
    }
}
?>

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

        <!-- HERO -->
        <div class="text-center mb-5 logo-wrap">
            <img src="assets/images/logo.jpg" class="img-fluid mb-3" style="max-width: 600px;">
            <h1>Oldies and More! Radio</h1>
            <p class="lead">Where the jukebox never sleeps</p>
            <a href="http://cr3.broadcasturself.com:6660/stream" class="btn btn-primary mt-3">▶ Play Now</a>
        </div>

        <!-- DJ SCHEDULE -->
        <div class="row text-center mb-5">
            <div class="col-md-4"><div class="dj-box"><h3>Now On Air</h3><p><strong><?= $currentDJ ?></strong> (<?= $currentHour ?> EST)</p></div></div>
            <div class="col-md-4"><div class="dj-box"><h3>Next Up</h3><p><strong><?= $nextDJ ?></strong> (<?= $nextHour ?> EST)</p></div></div>
            <div class="col-md-4"><div class="dj-box"><h3>Coming After</h3><ul class="list-unstyled"><?php foreach ($comingAfter as $dj) echo "<li><strong>$dj</strong></li>"; ?></ul></div></div>
        </div>

        <!-- NOW PLAYING -->
        <div class="text-center mb-5 content-box">
            <h4>🎶 What’s Playing Now</h4>
            <?php include 'nowplaying.php'; ?>
        </div>

        <!-- COMMENT FORM -->
        <div class="mb-5 content-box">
            <h4>💬 Leave a Comment</h4>
            <?= $commentMessage ?? '' ?>
            <form method="POST">
                <input type="text" name="name" class="form-control mb-2" placeholder="Your name" required>
                <textarea name="comment" class="form-control mb-2" placeholder="Share your thoughts..." required></textarea>
                <button type="submit" class="btn btn-primary">Post Comment</button>
            </form>
        </div>

        <!-- RECENT COMMENTS -->
        <div class="content-box mb-5">
            <h5>🗨️ Recent Comments</h5>
            <?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-box'><strong>$name</strong><br>" . nl2br(htmlspecialchars($msg)) . "<br><small>" . date('M j, Y g:i A', strtotime($ts)) . "</small></div>";
            }
            ?>
        </div>

        <!-- POLL -->
        <?php if ($poll): list($q_en) = explode('|', $poll[0]); ?>
            <div class="content-box mb-5">
                <h4>📊 Station Poll</h4>
                <?= $pollMessage ?? '' ?>
                <p><strong><?= $q_en ?></strong></p>
                <ul class="list-group mt-3">
                    <?php foreach (array_slice($poll, 1) as $i => $line): list($opt_en) = explode('|', $line); ?>
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            <?= $opt_en ?>
                            <span class="badge bg-primary rounded-pill"><?= $votes[$i] ?? 0 ?> votes</span>
                        </li>
                    <?php endforeach; ?>
                </ul>
                <form method="POST" class="mt-4">
                    <?php foreach (array_slice($poll, 1) as $i => $line): list($opt_en) = explode('|', $line); ?>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="vote" value="<?= $i ?>" required>
                            <label class="form-check-label"><?= $opt_en ?></label>
                        </div>
                    <?php endforeach; ?>
                    <button type="submit" class="btn btn-success mt-3">Vote</button>
                </form>
            </div>
        <?php endif; ?>

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

    </div>
</div>

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