<?php
session_start();
require_once __DIR__ . '/includes/schedule_lib.php';
require_once __DIR__ . '/includes/stream_lib.php';

/* ------------------------------
   DJ SCHEDULE (ET/USA 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'];


$schedule = smurf_load_schedule_hourmap($scheduleJson, $scheduleTxt, $daysOrder);
// Top 50 auto-track from current stream metadata
@smurf_top50_touch(__DIR__ . '/data/top50.json', __DIR__ . '/data/top50_state.json');
$playerUrls = smurf_get_player_urls();
$listenNowUrl = $playerUrls['preferred'] ?? '/stream-proxy.php';


$nowUK = new DateTime('now', new DateTimeZone('America/New_York'));
$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] : [];

$settingsFile = __DIR__ . '/data/settings.json';
$settings = (file_exists($settingsFile) ? json_decode(file_get_contents($settingsFile), true) : []);
if (!is_array($settings)) $settings = [];

$currentDJ = smurf_extract_dj($todayMap[$currentHourInt] ?? '') ?: ($settings['default_dj'] ?? 'Cosmic Vibes');
$isLiveDJ = smurf_is_live_dj($currentDJ, $settings);

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

$comingAfter = [];
$afterIndex = ($currentHourInt + 2) % 24;
$comingAfter[] = smurf_extract_dj($todayMap[$afterIndex] ?? '') ?: ($settings['default_dj'] ?? 'Cosmic Vibes');

/* ------------------------------
   POLL (JSON-driven to match admin)
------------------------------ */
$pollFile  = __DIR__ . '/data/poll.json';
$votesFile = __DIR__ . '/data/poll_votes.json';

$poll = (file_exists($pollFile) ? json_decode((string)file_get_contents($pollFile), true) : []);
if (!is_array($poll)) $poll = [];
$poll = array_merge(['question' => '', 'options' => [], 'show_on_home' => 1], $poll);

$votes = (file_exists($votesFile) ? json_decode((string)file_get_contents($votesFile), true) : []);
if (!is_array($votes)) $votes = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['vote_option']) && !empty($poll['options'])) {
    $selected = trim((string)$_POST['vote_option']);
    if (in_array($selected, $poll['options'], true)) {
        $votes[$selected] = (int)($votes[$selected] ?? 0) + 1;
        file_put_contents($votesFile, json_encode($votes, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        $pollMessage = "<div class='msg success'>Thanks for voting!</div>";
    }
}

/* ------------------------------
   FEATURED NEWS (reads admin news posts)
------------------------------ */
$featuredPost = null;
$newsDir = __DIR__ . '/data/news';
if (is_dir($newsDir)) {
    $newsFiles = glob($newsDir . '/*.json');
    usort($newsFiles, function($a, $b) { return filemtime($b) <=> filemtime($a); });
    foreach ($newsFiles as $newsPath) {
        $newsItem = json_decode((string)file_get_contents($newsPath), true);
        if (!is_array($newsItem)) continue;
        if (empty($newsItem['published']) || empty($newsItem['featured_home'])) continue;
        $featuredImage = trim((string)($newsItem['image'] ?? ''));
        if ($featuredImage !== '') {
            if (preg_match('~^(https?:)?//~i', $featuredImage) || strpos($featuredImage, '/img/') === 0) {
                $featuredImage = $featuredImage;
            } else {
                $featuredImage = '/img/content/' . ltrim($featuredImage, '/');
            }
        }
        $featuredPost = [
            'title' => trim((string)($newsItem['title'] ?? 'Featured News')),
            'content' => trim((string)($newsItem['content'] ?? '')),
            'image' => $featuredImage,
        ];
        break;
    }
}

/* ------------------------------
   radiogalaxyfx COMMENTS (Homepage)
   - New posts can be disabled in /admin/comments.php
   - Only Approved comments show publicly
------------------------------ */
$commentsFile  = __DIR__ . '/data/comments.txt';
$repliesFile   = __DIR__ . '/data/comment_replies.json';
$settingsFile  = __DIR__ . '/data/settings.json';

function smurf_front_read_json($path, $default=[]) {
  if (!file_exists($path)) return $default;
  $j = json_decode((string)file_get_contents($path), true);
  return is_array($j) ? $j : $default;
}
function smurf_front_settings($path) {
  $defaults = ['comments_enabled' => true];
  $s = smurf_front_read_json($path, []);
  return array_merge($defaults, is_array($s)?$s:[]);
}
function smurf_front_parse_blocks($path) {
  if (!file_exists($path)) return [];
  $raw = trim((string)file_get_contents($path));
  if ($raw === '') return [];
  $chunks = preg_split("/\n---\s*\n/", $raw);
  $out = [];
  foreach ($chunks as $chunk) {
    $chunk = trim($chunk);
    if ($chunk === '') continue;
    $lines = preg_split("/\R/", $chunk);
    $entry = ['_raw' => $chunk];
    $contentKeys = 0;
    foreach ($lines as $line) {
      if (strpos($line, ':') === false) continue;
      [$k,$v] = explode(':', $line, 2);
      $k = trim($k); $v = trim($v);
      if ($k === '') continue;
      $entry[$k] = $v;
      if (!in_array(strtolower($k), ['approved','ip'], true) && $v !== '') $contentKeys++;
    }
    if ($contentKeys === 0) continue;
    $out[] = $entry;
  }
  return array_reverse($out); // newest first
}
function smurf_front_is_approved($item) {
  $v = $item['Approved'] ?? $item['approved'] ?? '';
  return (string)$v === '1' || strtolower((string)$v) === 'yes' || strtolower((string)$v) === 'true';
}
function smurf_front_comment_key($item) {
  $raw = str_replace(["\r\n", "\r"], "\n", trim((string)($item['_raw'] ?? '')));
  $lines = preg_split("/\n+/", $raw);
  $keep = [];
  foreach ($lines as $line) {
    if (preg_match('/^Approved\s*:/i', $line)) continue;
    $keep[] = trim($line);
  }
  return md5(implode("\n", $keep));
}

$settings = smurf_front_settings($settingsFile);
$comment_posted = false;
$comment_error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['smurf_comment_submit'])) {
  if (empty($settings['comments_enabled'])) {
    $comment_error = 'Comments are currently closed.';
  } else {
    // Honeypot spam trap
    if (!empty($_POST['website'])) {
      // silently accept but do nothing
      $comment_posted = true;
    } else {
      $name = trim((string)($_POST['name'] ?? ''));
      $comment = trim((string)($_POST['comment'] ?? ''));
      if ($name === '' || $comment === '') {
        $comment_error = 'Please enter your name and comment.';
      } else {
        // Basic rate limit (per session)
        $now = time();
        $last = (int)($_SESSION['last_comment_ts'] ?? 0);
        if ($now - $last < 30) {
          $comment_error = 'Please wait a moment before posting again.';
        } else {
          $_SESSION['last_comment_ts'] = $now;

          $block = "Name: " . str_replace(["\n","\r"], ' ', $name) . "\n";
          $block .= "Comment: " . str_replace(["\n","\r"], ' ', $comment) . "\n";
          $block .= "Time: " . date('c') . "\n";
          $block .= "IP: " . ($_SERVER['REMOTE_ADDR'] ?? '') . "\n";
          $block .= "Approved: 0\n";

          $dir = dirname($commentsFile);
          if (!is_dir($dir)) @mkdir($dir, 0755, true);

          $fp = @fopen($commentsFile, 'a');
          if ($fp) {
            if (function_exists('flock')) @flock($fp, LOCK_EX);
            fwrite($fp, rtrim($block) . "\n---\n");
            if (function_exists('flock')) @flock($fp, LOCK_UN);
            fclose($fp);
          }
          // PRG
          header("Location: " . strtok($_SERVER["REQUEST_URI"], '?') . "?comment=sent");
          exit;
        }
      }
    }
  }
}

$replies = smurf_front_read_json($repliesFile, []);
$allComments = smurf_front_parse_blocks($commentsFile);
$approvedComments = array_values(array_filter($allComments, 'smurf_front_is_approved'));
?>

<?php
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/nav.php';
?>

<main class="content-area">

    <!-- HERO -->
    <div class="content-wrapper">
        <section class="content-card hero-card center-text">
            <h1 class="hero-title">Radio Galaxy FX</h1>
            <p class="hero-tagline">Cosmic Radio • Real Community • Real Music</p>

            <a href="<?= htmlspecialchars($listenNowUrl) ?>" class="button play-btn" target="_blank" rel="noopener">
                ▶ 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">RadioSpinner</a>
                </div>
            </div>
        </section>
    </div>

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

    <!-- FEATURED NEWS (conditional) -->
    <?php if (!empty($featuredPost)): ?>
        <div class="content-wrapper">
            <section class="content-card center-text">
                <div style="display:flex;gap:18px;align-items:center;justify-content:center;flex-wrap:wrap;text-align:left;">
                    <?php if (!empty($featuredPost['image'])): ?>
                        <img src="<?= htmlspecialchars($featuredPost['image']) ?>" alt="<?= htmlspecialchars($featuredPost['title'] ?? 'Featured News') ?>" style="width:120px;height:155px;object-fit:cover;border-radius:14px;flex:0 0 auto;">
                    <?php endif; ?>
                    <div style="max-width:720px;">
                        <h2>📰 Featured News</h2>
                        <h3><?= htmlspecialchars($featuredPost['title'] ?? 'Featured News') ?></h3>
                        <p><?= nl2br(htmlspecialchars(strlen((string)($featuredPost['content'] ?? '')) > 320 ? substr((string)($featuredPost['content'] ?? ''), 0, 317) . '...' : (string)($featuredPost['content'] ?? ''))) ?></p>
                        <a href="/news.php" class="button play-btn">Read More</a>
                    </div>
                </div>
            </section>
        </div>

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

    <?php
    $promoHomeFile = __DIR__ . '/data/promo.json';
    $featuredEvent = null;
    if (file_exists($promoHomeFile)) {
        $promoHome = json_decode((string)file_get_contents($promoHomeFile), true);
        if (is_array($promoHome) && !empty($promoHome['enabled']) && !empty($promoHome['pinned'])) {
            $eventImage = trim((string)($promoHome['image'] ?? ''));
            if ($eventImage !== '') {
                if (!(preg_match('~^(https?:)?//~i', $eventImage) || strpos($eventImage, '/img/') === 0)) {
                    $eventImage = '/img/content/' . ltrim($eventImage, '/');
                }
            }
            $featuredEvent = [
                'title' => trim((string)($promoHome['title'] ?? 'Featured Event')),
                'description' => trim((string)($promoHome['description'] ?? '')),
                'image' => $eventImage,
                'url' => '/events.php',
            ];
        }
    }
    ?>

    <?php if (!empty($featuredEvent)): ?>
        <div class="content-wrapper">
            <section class="content-card center-text">
                <div style="display:flex;gap:18px;align-items:center;justify-content:center;flex-wrap:wrap;text-align:left;">
                    <?php if (!empty($featuredEvent['image'])): ?>
                        <img src="<?= htmlspecialchars($featuredEvent['image']) ?>" alt="<?= htmlspecialchars($featuredEvent['title']) ?>" style="width:120px;height:155px;object-fit:cover;border-radius:14px;flex:0 0 auto;">
                    <?php endif; ?>
                    <div style="max-width:720px;">
                        <h2>🎉 Featured Event</h2>
                        <h3><?= htmlspecialchars($featuredEvent['title']) ?></h3>
                        <p><?= nl2br(htmlspecialchars(strlen((string)$featuredEvent['description']) > 260 ? substr((string)$featuredEvent['description'], 0, 257) . '...' : (string)$featuredEvent['description'])) ?></p>
                        <a href="<?= htmlspecialchars($featuredEvent['url']) ?>" class="button play-btn">View Event</a>
                    </div>
                </div>
            </section>
        </div>

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

    <!-- 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>

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

    <!-- FIXED CLOCK SCRIPT -->

    <script>
        async function refreshNowPlaying() {
            try {
                const res = await fetch('/data/nowplaying.php?ts=' + Date.now(), { cache: 'no-store' });
                if (!res.ok) throw new Error('Failed to load now playing');
                const html = await res.text();
                const wrap = document.getElementById('nowplaying-content');
                if (wrap && html.trim() !== '') {
                    wrap.innerHTML = html;
                }
            } catch (err) {
                console.error(err);
            }
        }

        refreshNowPlaying();
        setInterval(refreshNowPlaying, 30000);
    </script>

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

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

            // ET/USA time (America/New_York)
            const ukTime = new Intl.DateTimeFormat('en-GB', {
                timeZone: 'America/New_York',
                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) ?> ET / USA)</p>
            </div>

            <div class="schedule-box">
                <h3>Next Up</h3>
                <p><strong><?= htmlspecialchars($nextDJ) ?></strong> (<?= htmlspecialchars($nextHour) ?> ET / USA)</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>

    <!-- POLL (conditional) -->
    <?php if (!empty($poll['show_on_home']) && !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 $opt): ?>
                        <label class="radio">
                            <input type="radio" name="vote_option" value="<?= htmlspecialchars($opt, ENT_QUOTES, 'UTF-8') ?>" required>
                            <?= htmlspecialchars($opt) ?>
                        </label>
                    <?php endforeach; ?>

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

                <div class="poll-results">
                    <?php foreach (($poll['options'] ?? []) as $opt): ?>
                        <p><?= htmlspecialchars($opt) ?> — <strong><?= (int)($votes[$opt] ?? 0) ?></strong> votes</p>
                    <?php endforeach; ?>
                </div>
            </section>
        </div>

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


<section class="content-card" id="comments">
  <h2 style="margin-top:0;">💬 Comments</h2>

  <?php if (!empty($_GET['comment']) && $_GET['comment'] === 'sent'): ?>
    <div class="msg success" style="margin:12px 0;">Thanks! Your comment has been sent for approval.</div>
  <?php endif; ?>

  <?php if (!empty($comment_error)): ?>
    <div class="msg error" style="margin:12px 0;"><?= htmlspecialchars($comment_error) ?></div>
  <?php endif; ?>

  <?php if (empty($settings['comments_enabled'])): ?>
    <div class="content-card" style="opacity:.9;">
      Comments are currently closed.
    </div>
  <?php else: ?>
    <div class="content-card" style="text-align:left;">
      <form method="post" autocomplete="off">
        <input type="hidden" name="smurf_comment_submit" value="1">
        <div class="request-wrapper">
          <div class="request-box">
            <div class="request-field">
              <label>Your Name</label>
              <input type="text" class="request-input" name="name" required maxlength="60">
            </div>
            <div class="request-field">
              <label>Your Comment</label>
              <textarea class="request-textarea" name="comment" required rows="4" maxlength="300"></textarea>
            </div>
          </div>
        </div>

        <!-- Honeypot -->
        <div style="position:absolute;left:-9999px;top:auto;width:1px;height:1px;overflow:hidden;">
          <label>Website</label>
          <input type="text" name="website" tabindex="-1" autocomplete="off">
        </div>

        <button type="submit" class="btn btn-accent">Submit Comment</button>
        <span style="opacity:.75;margin-left:10px;">(comments appear after approval)</span>
      </form>
    </div>
  <?php endif; ?>

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

  <?php if (empty($approvedComments)): ?>
    <p style="opacity:.85;">No approved comments yet.</p>
  <?php else: ?>
    <div class="friends-grid" style="grid-template-columns: 1fr; gap:16px;">
      <?php foreach ($approvedComments as $c): ?>
        <?php
          $ckey = smurf_front_comment_key($c);
          $reply = $replies[$ckey]['text'] ?? '';
        ?>
        <div class="content-card" style="text-align:left;">
          <div style="display:flex;justify-content:space-between;gap:10px;flex-wrap:wrap;">
            <strong><?= htmlspecialchars($c['Name'] ?? 'Anonymous') ?></strong>
            <span style="opacity:.75;font-size:.95em;"><?= htmlspecialchars($c['Time'] ?? '') ?></span>
          </div>
          <div style="margin-top:8px;opacity:.95;"><?= htmlspecialchars($c['Comment'] ?? '') ?></div>

          <?php if (!empty($reply)): ?>
            <div class="content-card" style="margin-top:12px;border-style:dashed;">
              <div style="font-weight:700;margin-bottom:6px;">Admin Reply</div>
              <?= nl2br(htmlspecialchars($reply)) ?>
            </div>
          <?php endif; ?>
        </div>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
</section>


</main>

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