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

/* ------------------------------
   DJ SCHEDULE (UK time, JSON preferred)
   Frontend schedule page reads /data/schedule.json
------------------------------ */
$scheduleJson = __DIR__ . '/data/schedule.json';
$scheduleTxt  = __DIR__ . '/data/schedule.txt';
$daysOrder    = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];

function smurf_load_schedule_hourmap($jsonFile, $txtFile, $daysOrder) {
    // Expected JSON format: {"Monday": {"0":"Show — DJ", "13":"..."}, ...}
    if (file_exists($jsonFile) && filesize($jsonFile) > 5) {
        $j = json_decode(file_get_contents($jsonFile), true);
        if (is_array($j)) return $j;
    }

    // Fallback: legacy TXT formats
    // Day|HH:MM|DJ
    // Day|HH:MM|Show Title|DJ
    $out = [];
    foreach ($daysOrder as $d) $out[$d] = [];
    if (file_exists($txtFile) && filesize($txtFile) > 0) {
        foreach (file($txtFile, FILE_IGNORE_NEW_LINES) as $line) {
            $line = trim($line);
            if ($line === '' || str_starts_with($line, '#')) continue;
            $parts = array_map('trim', explode('|', $line));
            if (count($parts) < 3) continue;
            $day  = $parts[0];
            $time = $parts[1];
            if (!in_array($day, $daysOrder, true)) continue;
            if (!preg_match('/^\d{2}:\d{2}$/', $time)) continue;
            $hour = (int)substr($time, 0, 2);

            $title = '';
            $dj = '';
            if (count($parts) >= 4) { $title = $parts[2]; $dj = $parts[3]; }
            else { $dj = $parts[2]; }

            $val = ($title !== '' ? $title : $dj);
            if ($title !== '' && $dj !== '' && $title !== $dj) $val = $title . ' — ' . $dj;
            if ($val !== '') $out[$day][$hour] = $val;
        }
        foreach ($daysOrder as $d) {
            if (isset($out[$d]) && is_array($out[$d])) ksort($out[$d]);
        }
    }
    return $out;
}

function smurf_extract_dj($val) {
    $val = trim((string)$val);
    if ($val === '') return '';
    $parts = explode('—', $val, 2);
    if (count($parts) === 2) return trim($parts[1]);
    return $val; // if only DJ name stored
}

$schedule = smurf_load_schedule_hourmap($scheduleJson, $scheduleTxt, $daysOrder);

$nowUK = new DateTime('now', new DateTimeZone('Europe/London'));
$currentDay  = $nowUK->format('l');
$currentHourInt = (int)$nowUK->format('H');
$currentHour = str_pad((string)$currentHourInt, 2, '0', STR_PAD_LEFT) . ':00';

$todayMap = (isset($schedule[$currentDay]) && is_array($schedule[$currentDay])) ? $schedule[$currentDay] : [];

$currentDJ = smurf_extract_dj($todayMap[$currentHourInt] ?? '') ?: 'Auto DJ';

$nextHourIndex = ($currentHourInt + 1) % 24;
$nextHour      = str_pad((string)$nextHourIndex, 2, '0', STR_PAD_LEFT) . ':00';
$nextDJ        = smurf_extract_dj($todayMap[$nextHourIndex] ?? '') ?: 'Auto DJ';

$comingAfter = [];
$afterIndex = ($currentHourInt + 2) % 24;
$comingAfter[] = smurf_extract_dj($todayMap[$afterIndex] ?? '') ?: 'Auto DJ';

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

$poll  = (file_exists($pollFile) && filesize($pollFile) > 0)
    ? file($pollFile, FILE_IGNORE_NEW_LINES)
    : [];

$votes = (file_exists($votesFile) && filesize($votesFile) > 0)
    ? array_map('intval', file($votesFile, FILE_IGNORE_NEW_LINES))
    : [];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['vote']) && $poll) {
    $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>";
}

/* ------------------------------
   FEATURED NEWS
------------------------------ */
$featuredNewsFile = __DIR__ . '/data/featured_news.txt';
$featuredNews = (file_exists($featuredNewsFile) && filesize($featuredNewsFile) > 0)
    ? trim(file_get_contents($featuredNewsFile))
    : '';
?>

<main class="content-area">

    <!-- HERO -->
    <div class="content-wrapper">
        <section class="content-card hero-card center-text">
            <h1 class="hero-title">Smurfette's Country Delights</h1>
            <p class="hero-tagline">Real Country • Real Community • Real Music</p>

            <a href="http://cr3.broadcasturself.com:1982/stream" class="button play-btn" target="_blank">
                ▶ Listen Live
            </a>

            <div class="listen-anywhere center-text">
                <h2>🎧 Listen Anywhere</h2>
                <div class="listen-inline">
                    <a href="https://mytuner-radio.com" class="play-btn" target="_blank">MyRadioTuner</a>
                    <a href="https://onlineradiobox.com" class="play-btn" target="_blank">OnlineRadioBox</a>
                    <a href="https://radiospinner.com" class="play-btn" target="_blank">RadioSpiner</a>
                </div>
            </div>
        </section>
    </div>

    <div class="smurf-divider"></div>

    <!-- FEATURED NEWS (conditional) -->
    <?php if (!empty($featuredNews)): ?>
        <div class="content-wrapper">
            <section class="content-card center-text">
                <h2>📰 Featured News</h2>
                <p><?= nl2br(htmlspecialchars($featuredNews)) ?></p>
                <a href="/news.php" class="button play-btn">Read More</a>
            </section>
        </div>

        <div class="smurf-divider"></div>
    <?php endif; ?>

    <!-- CURRENT TIME -->
    <div class="content-wrapper">
        <section class="content-card center-text">
            <h2>⏰ Current Time</h2>

            <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 (UK):</strong><br>
                    <span id="ukTime">--:--</span>
                </div>
            </div>
        </section>
    </div>

    <!-- FIXED CLOCK SCRIPT -->
    <script>
        function updateClocks() {
            const now = new Date();

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

            // UK time (Europe/London)
            const ukTime = new Intl.DateTimeFormat('en-GB', {
                timeZone: 'Europe/London',
                hour: '2-digit',
                minute: '2-digit'
            }).format(now);

            document.getElementById('ukTime').textContent = ukTime;
        }

        setInterval(updateClocks, 1000);
        updateClocks();
    </script>

    <div class="smurf-divider"></div>

    <!-- DJ SCHEDULE -->
    <div class="content-wrapper">
        <section class="schedule-grid">
            <div class="schedule-box">
                <h3>Now On Air</h3>
                <p><strong><?= htmlspecialchars($currentDJ) ?></strong> (<?= htmlspecialchars($currentHour) ?> UK)</p>
            </div>

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

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

    <div class="smurf-divider"></div>

    <!-- NOW PLAYING -->
    <div class="content-wrapper">
        <section class="content-card center-text">
            <h2>🎶 What’s Playing Now</h2>
            <div id="nowplaying-content">
                <?php include __DIR__ . '/data/nowplaying.php'; ?>
            </div>
        </section>
    </div>

    <div class="smurf-divider"></div>

    <!-- POLL (conditional) -->
    <?php if (!empty($poll)):
        list($q_en) = explode('|', $poll[0]);
    ?>
        <div class="content-wrapper">
            <section class="content-card center-text">
                <h2>📊 Station Poll</h2>
                <?= $pollMessage ?? '' ?>
                <p><strong><?= htmlspecialchars($q_en) ?></strong></p>

                <form method="POST">
                    <?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">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>
            </section>
        </div>

        <div class="smurf-divider"></div>
    <?php endif; ?>

</main>

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