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

/* ------------------------------
   DJ SCHEDULE (JSON with TXT fallback)
------------------------------ */
$scheduleJson = __DIR__ . '/data/schedule.json';
$scheduleTxt  = __DIR__ . '/data/schedule.txt';

function smurf_load_schedule($jsonFile, $txtFile) {
    $days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];

    // 1) Prefer JSON if valid
    if (file_exists($jsonFile) && filesize($jsonFile) > 5) {
        $j = json_decode(file_get_contents($jsonFile), true);
        if (is_array($j) && !empty($j)) return $j;
    }

    // 2) Fallback import from TXT if present
    if (file_exists($txtFile) && filesize($txtFile) > 0) {
        $out = [];
        foreach ($days as $d) $out[$d] = [];
        foreach (file($txtFile, FILE_IGNORE_NEW_LINES) as $line) {
            $line = trim($line);
            if ($line === '' || str_starts_with($line, '#')) continue;

            // supported formats:
            // Day|HH:MM|DJ
            // Day|HH:MM|Show Title|DJ
            $parts = array_map('trim', explode('|', $line));
            if (count($parts) < 3) continue;

            $day = $parts[0];
            $time = $parts[1];

            if (!in_array($day, $days, true)) continue;
            if (!preg_match('/^\d{2}:\d{2}$/', $time)) continue;

            $title = '';
            $dj = '';

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

            $out[$day][] = ['time'=>$time, 'title'=>$title, 'dj'=>$dj];
        }

        // save JSON for future loads
        @file_put_contents($jsonFile, json_encode($out, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE), LOCK_EX);
        return $out;
    }

    // 3) empty schedule
    $out = [];
    foreach ($days as $d) $out[$d] = [];
    return $out;
}

$schedule = smurf_load_schedule($scheduleJson, $scheduleTxt);

$currentDay   = date('l');
$currentHour  = date('H') . ':00';

function smurf_find_dj_for_hour($schedule, $day, $hour) {
    $shows = $schedule[$day] ?? [];
    foreach ($shows as $row) {
        if (($row['time'] ?? '') === $hour) {
            $dj = trim($row['dj'] ?? '');
            return $dj !== '' ? $dj : 'Auto DJ';
        }
    }
    return 'Auto DJ';
}

$currentDJ = smurf_find_dj_for_hour($schedule, $currentDay, $currentHour);

$nextHourIndex = (int)substr($currentHour, 0, 2) + 1;
$nextHour      = str_pad($nextHourIndex % 24, 2, '0', STR_PAD_LEFT) . ':00';
$nextDJ        = smurf_find_dj_for_hour($schedule, $currentDay, $nextHour);

/* ------------------------------
   POLL (JSON, and ONLY if enabled for Home)
------------------------------ */
$pollFile  = __DIR__ . '/data/poll.json';
$votesFile = __DIR__ . '/data/poll_votes.json';

$poll = (file_exists($pollFile) ? json_decode(file_get_contents($pollFile), true) : []);
if (!is_array($poll)) $poll = [];
$pollEnabledHome = !empty($poll['show_on_home']);
$votes = (file_exists($votesFile) ? json_decode(file_get_contents($votesFile), true) : []);
if (!is_array($votes)) $votes = [];

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

/* ------------------------------
   FEATURED NEWS (ONLY show on Home if featured flag is set in admin)
------------------------------ */
$newsDir = __DIR__ . '/data/news/';
$featuredPosts = [];

if (is_dir($newsDir)) {
    foreach (glob($newsDir . '*.json') as $p) {
        $j = json_decode(@file_get_contents($p), true);
        if (!is_array($j)) continue;
        if (empty($j['published'])) continue;
        if (empty($j['featured_home'])) continue;

        $featuredPosts[] = [
            'title' => $j['title'] ?? 'News',
            'date'  => $j['date'] ?? '',
            'tag'   => $j['tag'] ?? '',
            'image' => $j['image'] ?? '',
            'content' => $j['content'] ?? '',
            'file'  => basename($p),
        ];
    }
}

// newest first by date then file
usort($featuredPosts, function($a,$b){
    $da = $a['date'] ?? '';
    $db = $b['date'] ?? '';
    if ($da === $db) return strcmp($b['file'] ?? '', $a['file'] ?? '');
    return strcmp($db, $da);
});

?>

<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 (Home shows ONLY posts marked Featured + Published in Admin) -->
    <?php if (!empty($featuredPosts)): ?>
        <div class="content-wrapper">
            <section class="content-card" style="text-align:left;">
                <h2 class="section-title">📰 Featured News</h2>

                <div class="news-list" style="display:flex;flex-direction:column;gap:12px;margin-top:10px;">
                    <?php foreach (array_slice($featuredPosts, 0, 3) as $p): ?>
                        <article class="news-item" style="padding:12px;border-radius:14px;background:rgba(0,0,0,.35);border:1px solid rgba(0,204,136,.18);">
                            <div style="display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;">
                                <strong style="font-size:1.05em;"><?= htmlspecialchars($p['title']) ?></strong>
                                <span style="opacity:.85;"><?= htmlspecialchars($p['date']) ?></span>
                            </div>
                            <?php if (!empty($p['tag'])): ?>
                                <div style="opacity:.8;margin-top:4px;">🏷 <?= htmlspecialchars($p['tag']) ?></div>
                            <?php endif; ?>
                            <?php
                              $excerpt = trim(strip_tags($p['content'] ?? ''));
                              if (strlen($excerpt) > 180) $excerpt = substr($excerpt, 0, 177) . '...';
                            ?>
                            <?php if ($excerpt !== ''): ?>
                                <p style="margin:10px 0 0;opacity:.92;"><?= htmlspecialchars($excerpt) ?></p>
                            <?php endif; ?>
                        </article>
                    <?php endforeach; ?>
                </div>

                <div style="margin-top:14px;">
                    <a href="/news.php" class="button play-btn">Read More News</a>
                </div>
            </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 ($pollEnabledHome && !empty($poll['question']) && !empty($poll['options'])): ?>
        <div class="content-wrapper">
            <section class="content-card center-text">
                <h2>📊 Station Poll</h2>
                <?= $pollMessage ?? '' ?>
                <p><strong><?= htmlspecialchars($poll['question']) ?></strong></p>

                <form method="POST">
                    <?php foreach (($poll['options'] ?? []) as $i => $opt): ?>
                        <label class="radio">
                            <input type="radio" name="vote" value="<?= (int)$i ?>" required>
                            <?= htmlspecialchars($opt) ?>
                        </label>
                    <?php endforeach; ?>

                    <button type="submit" class="button">Vote</button>
                </form>

                <div class="poll-results">
                    <?php foreach (($poll['options'] ?? []) as $i => $opt): ?>
                        <p><?= htmlspecialchars($opt) ?> — <strong><?= (int)($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'; ?>