<?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)) {

            // If JSON is the old list-of-objects format, migrate to hour=>string
            $looksLikeList = false;
            foreach ($days as $d) {
                if (!isset($j[$d])) continue;
                if (isset($j[$d][0]) && is_array($j[$d][0]) && isset($j[$d][0]['time'])) { $looksLikeList = true; break; }
            }

            if ($looksLikeList) {
                $fixed = [];
                foreach ($days as $d) $fixed[$d] = [];
                foreach ($days as $d) {
                    $list = (isset($j[$d]) && is_array($j[$d])) ? $j[$d] : [];
                    foreach ($list as $row) {
                        if (!is_array($row)) continue;
                        $time = trim((string)($row['time'] ?? ''));
                        if (!preg_match('/^\d{2}:\d{2}$/', $time)) continue;
                        $hour = (int)substr($time, 0, 2);

                        $title = trim((string)($row['title'] ?? ''));
                        $dj    = trim((string)($row['dj'] ?? ''));
                        $val   = ($title !== '' ? $title : $dj);
                        if ($title !== '' && $dj !== '' && $title !== $dj) $val = $title . ' — ' . $dj;
                        if ($val !== '') $fixed[$d][$hour] = $val;
                    }
                    ksort($fixed[$d]);
                }
                @file_put_contents($jsonFile, json_encode($fixed, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT), LOCK_EX);
                return $fixed;
            }

            // Ensure format is day => hour => string
            $out = [];
            foreach ($days as $d) {
                $out[$d] = [];
                $map = (isset($j[$d]) && is_array($j[$d])) ? $j[$d] : [];
                foreach ($map as $h => $val) {
                    if (!is_numeric($h)) continue;
                    $hh = (int)$h;
                    if ($hh < 0 || $hh > 23) continue;
                    $val = trim((string)$val);
                    if ($val === '') continue;
                    $out[$d][$hh] = $val;
                }
                ksort($out[$d]);
            }
            return $out;
        }
    }

    // 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];
            }

            $hour = (int)substr($time, 0, 2);
            $val = ($title !== '' ? $title : $dj);
            if ($title !== '' && $dj !== '' && $title !== $dj) $val = $title . ' — ' . $dj;
            if ($val !== '') $out[$day][$hour] = $val;
        }

        // save JSON for future loads
        foreach ($days as $d) ksort($out[$d]);
        @file_put_contents($jsonFile, json_encode($out, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT), LOCK_EX);
        return $out;
    }

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

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

$nowUK = new DateTime('now', new DateTimeZone('Europe/London'));
$currentDay   = $nowUK->format('l');
$currentHourN = (int)$nowUK->format('H');

function smurf_extract_dj($val) {
    $val = trim((string)$val);
    if ($val === '') return 'Auto DJ';
    $parts = explode('—', $val, 2);
    if (count($parts) === 2) {
        $dj = trim($parts[1]);
        return $dj !== '' ? $dj : trim($parts[0]);
    }
    return $val;
}

function smurf_find_dj_for_hour($schedule, $day, $hourN) {
    $map = (isset($schedule[$day]) && is_array($schedule[$day])) ? $schedule[$day] : [];
    if (isset($map[$hourN])) return smurf_extract_dj($map[$hourN]);
    return 'Auto DJ';
}

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

$nextHourN = ($currentHourN + 1) % 24;
$nextDJ    = smurf_find_dj_for_hour($schedule, $currentDay, $nextHourN);

// Coming after: next 3 hours (unique, non-empty)
$comingAfter = [];
for ($i=2; $i<=4; $i++) {
    $h = ($currentHourN + $i) % 24;
    $dj = smurf_find_dj_for_hour($schedule, $currentDay, $h);
    if ($dj && !in_array($dj, $comingAfter, true)) $comingAfter[] = $dj;
}

// Human readable time labels for the widget
$currentHour = str_pad((string)$currentHourN, 2, '0', STR_PAD_LEFT) . ':00';
$nextHour    = str_pad((string)$nextHourN, 2, '0', STR_PAD_LEFT) . ':00';

/* ------------------------------
   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'; ?>