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

date_default_timezone_set('America/New_York');

$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);
@smurf_top50_touch(__DIR__ . '/data/top50.json', __DIR__ . '/data/top50_state.json');
$playerUrls   = smurf_get_player_urls();
$listenNowUrl = $playerUrls['preferred'] ?? 'stream-proxy.php';
$publicPrefix = '';
$dataPrefix = 'data/';

$stationNow = new DateTime('now', new DateTimeZone('America/New_York'));
$currentDay = $stationNow->format('l');
$currentHourInt = (int)$stationNow->format('H');
$todayMap = (isset($schedule[$currentDay]) && is_array($schedule[$currentDay])) ? $schedule[$currentDay] : [];
$currentDJ = smurf_extract_dj((string)($todayMap[$currentHourInt] ?? '')) ?: 'Auto DJ';
$nextHourIndex = ($currentHourInt + 1) % 24;
$nextDJ = smurf_extract_dj((string)($todayMap[$nextHourIndex] ?? '')) ?: 'Auto DJ';
$afterHour = ($currentHourInt + 2) % 24;
$comingAfter = [smurf_extract_dj((string)($todayMap[$afterHour] ?? '')) ?: 'Auto DJ'];

$settings = smurf_load_public_settings();
$isLiveDJ = smurf_is_live_dj($currentDJ, $settings);

$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 = [];
$pollMessage = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['vote_option']) && !empty($poll['options'])) {
    $selected = trim((string)$_POST['vote_option']);
    if (in_array($selected, (array)$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='alert alert-success'>Thanks for voting!</div>";
    }
}

$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 | FILE_SKIP_EMPTY_LINES) : [];
$commentMessage = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['homepage_comment_submit'])) {
    $name = trim((string)($_POST['name'] ?? ''));
    $message = trim((string)($_POST['comment'] ?? ''));
    if (empty($settings['comments_enabled'])) {
        $commentMessage = "<div class='alert alert-danger'>Comments are currently turned off.</div>";
    } elseif ($name !== '' && $message !== '') {
        if (in_array($userIP, $banned, true)) {
            $commentMessage = "<div class='alert alert-danger'>Your IP is banned from posting comments.</div>";
        } else {
            $id = uniqid();
            $timestamp = date('Y-m-d H:i:s');
            $entry = $id . '|' . str_replace(['|', "\n", "\r"], [' ', ' ', ' '], $name) . '|' . str_replace(['|', "\r"], [' ', ''], $message) . '|' . $userIP . '|' . $timestamp . '|no' . "\n";
            file_put_contents($commentsFile, $entry, FILE_APPEND | LOCK_EX);
            $commentMessage = "<div class='alert alert-success'>Thanks for your comment! It will appear once approved.</div>";
        }
    }
}

$approvedComments = [];
if (file_exists($commentsFile)) {
    $rawComments = trim((string)file_get_contents($commentsFile));
    if ($rawComments !== '') {
        if (strpos($rawComments, '---') !== false && preg_match('/(^|\n)\w+\s*:/', $rawComments)) {
            $blocks = preg_split('/\n---\s*\n/', $rawComments) ?: [];
            foreach (array_reverse($blocks) as $block) {
                $block = trim((string)$block);
                if ($block === '') continue;
                $item = [];
                foreach (preg_split('/\R/', $block) as $line) {
                    if (strpos($line, ':') === false) continue;
                    [$k, $v] = explode(':', $line, 2);
                    $item[strtolower(trim((string)$k))] = trim((string)$v);
                }
                $approved = strtolower((string)($item['approved'] ?? '0'));
                if (!in_array($approved, ['1','yes','true'], true)) continue;
                $approvedComments[] = [
                    'name' => (string)($item['name'] ?? 'Listener'),
                    'message' => (string)($item['message'] ?? ''),
                    'timestamp' => (string)($item['timestamp'] ?? ''),
                ];
                if (count($approvedComments) >= 3) break;
            }
        } else {
            $commentLines = file($commentsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
            foreach (array_reverse($commentLines) as $line) {
                $parts = explode('|', trim((string)$line));
                if (count($parts) >= 6 && strtolower((string)$parts[5]) === 'yes') {
                    $approvedComments[] = [
                        'name' => $parts[1],
                        'message' => $parts[2],
                        'timestamp' => $parts[4],
                    ];
                }
                if (count($approvedComments) >= 3) break;
            }
        }
    }
}

$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) || empty($newsItem['published']) || empty($newsItem['featured_home'])) continue;
        $featuredImage = trim((string)($newsItem['image'] ?? ''));
        if ($featuredImage !== '' && !(preg_match('~^(https?:)?//~i', $featuredImage) || strpos($featuredImage, '/img/') === 0)) {
            $featuredImage = '/img/content/' . ltrim($featuredImage, '/');
        }
        $featuredPost = [
            'title' => trim((string)($newsItem['title'] ?? 'Featured News')),
            'content' => trim((string)($newsItem['content'] ?? '')),
            'image' => $featuredImage,
        ];
        break;
    }
}

$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 !== '' && !(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',
        ];
    }
}
?>
<main class="content-area">
  <div class="content-wrapper page-shell">
    <section class="content-card hero-card center-text">
      <img src="assets/images/tmr.png" alt="Thunder Mountain Radio Logo" class="img-fluid mb-3" style="max-width:220px;">
      <h1 class="hero-title">Thunder Mountain Radio</h1>
      <p class="hero-tagline">Where lightning strikes and music roars</p>
      <a href="<?= htmlspecialchars($listenNowUrl) ?>" class="button play-btn" target="_blank" rel="noopener">▶ Listen Live</a>
    </section>
  </div>

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

  <?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']) ?>" 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']) ?></h3>
          <p><?= nl2br(htmlspecialchars(strlen((string)$featuredPost['content']) > 320 ? substr((string)$featuredPost['content'], 0, 317) . '...' : (string)$featuredPost['content'])) ?></p>
          <a href="<?= htmlspecialchars($publicPrefix) ?>news.php" class="button play-btn">Read More</a>
        </div>
      </div>
    </section>
  </div>
  <div class="smurf-divider"></div>
  <?php endif; ?>

  <?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($publicPrefix . ltrim((string)$featuredEvent['url'], '/')) ?>" class="button play-btn">View Event</a>
        </div>
      </div>
    </section>
  </div>
  <div class="smurf-divider"></div>
  <?php endif; ?>

  <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>
      <div class="row g-3" style="margin-top:18px;text-align:left;">
        <div class="col-md-12"><h3 style="margin-bottom:8px;">Current Time</h3></div>
        <div class="col-md-6">
          <div class="schedule-box h-100">
            <h4>User Time</h4>
            <p id="user-time" style="font-size:1.2rem;margin:0;">--:--:-- --</p>
          </div>
        </div>
        <div class="col-md-6">
          <div class="schedule-box h-100">
            <h4>Station Time (EST)</h4>
            <p id="station-time" style="font-size:1.2rem;margin:0;">--:--:-- --</p>
          </div>
        </div>
      </div>
    </section>
  </div>

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

  <div class="content-wrapper">
    <section class="content-card center-text">
      <h2>🎙️ On Air Right Now</h2>
      <div class="row g-3" style="text-align:left;">
        <div class="col-md-4"><div class="schedule-box h-100"><h4>Now On Air</h4><p><strong><?= htmlspecialchars($currentDJ) ?></strong></p><p><?= htmlspecialchars(str_pad((string)$currentHourInt, 2, '0', STR_PAD_LEFT)) ?>:00 EST <?= $isLiveDJ ? '• LIVE DJ' : '• Auto / Scheduled' ?></p></div></div>
        <div class="col-md-4"><div class="schedule-box h-100"><h4>Next Up</h4><p><strong><?= htmlspecialchars($nextDJ) ?></strong></p><p><?= htmlspecialchars(str_pad((string)$nextHourIndex, 2, '0', STR_PAD_LEFT)) ?>:00 EST</p></div></div>
        <div class="col-md-4"><div class="schedule-box h-100"><h4>Coming After</h4><?php foreach ($comingAfter as $dj): ?><p><strong><?= htmlspecialchars($dj) ?></strong></p><?php endforeach; ?></div></div>
      </div>
    </section>
  </div>

  <?php if (!empty($poll['question']) && !empty($poll['show_on_home'])): ?>
  <div class="smurf-divider"></div>
  <div class="content-wrapper">
    <section class="content-card center-text">
      <h2>📊 Station Poll</h2>
      <?= $pollMessage ?>
      <p><strong><?= htmlspecialchars((string)$poll['question']) ?></strong></p>
      <form method="post" style="max-width:720px;margin:0 auto;text-align:left;">
        <?php foreach ((array)$poll['options'] as $opt): ?>
          <label style="display:block;margin:10px 0;padding:12px 14px;border:1px solid rgba(102,217,255,.18);border-radius:14px;">
            <input type="radio" name="vote_option" value="<?= htmlspecialchars((string)$opt) ?>" required>
            <span style="margin-left:10px;"><?= htmlspecialchars((string)$opt) ?></span>
            <span style="float:right;opacity:.8;"><?= (int)($votes[$opt] ?? 0) ?> votes</span>
          </label>
        <?php endforeach; ?>
        <button type="submit" class="button play-btn">Vote</button>
      </form>
    </section>
  </div>
  <?php endif; ?>

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

  <div class="content-wrapper">
    <section class="content-card center-text">
      <h2>💬 Leave a Comment</h2>
      <?= $commentMessage ?>
      <form method="post" style="max-width:720px;margin:0 auto;">
        <input type="hidden" name="homepage_comment_submit" value="1">
        <input type="text" name="name" class="form-control mb-3" placeholder="Your name" required>
        <textarea name="comment" class="form-control mb-3" placeholder="Share your thoughts..." rows="4" required></textarea>
        <button type="submit" class="button play-btn">Post Comment</button>
      </form>
      <div style="margin-top:24px;text-align:left;">
        <h3>Recent Comments</h3>
        <?php if (empty($approvedComments)): ?>
          <p>No approved comments yet.</p>
        <?php else: ?>
          <?php foreach ($approvedComments as $comment): ?>
            <div class="comment-box">
              <strong><?= htmlspecialchars($comment['name']) ?></strong><br>
              <?= nl2br(htmlspecialchars($comment['message'])) ?><br>
              <small><?= htmlspecialchars(date('M j, Y g:i A', strtotime((string)$comment['timestamp']))) ?></small>
            </div>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>
    </section>
  </div>
</main>
<script>
async function refreshNowPlaying(){
  try {
    const res = await fetch(<?= json_encode($dataPrefix . 'nowplaying.php', JSON_UNESCAPED_SLASHES) ?> + '?ts=' + Date.now(), {cache:'no-store'});
    if (!res.ok) throw new Error('Failed');
    document.getElementById('nowplaying-content').innerHTML = await res.text();
  } catch (e) {}
}
function updateHomeClocks(){
  const userEl = document.getElementById('user-time');
  const stationEl = document.getElementById('station-time');
  const now = new Date();
  if (userEl) {
    userEl.textContent = now.toLocaleTimeString([], {hour:'2-digit', minute:'2-digit', second:'2-digit', hour12:true});
  }
  if (stationEl) {
    stationEl.textContent = new Intl.DateTimeFormat('en-US', {
      timeZone: 'America/New_York',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: true
    }).format(now);
  }
}
refreshNowPlaying();
updateHomeClocks();
setInterval(refreshNowPlaying, 15000);
setInterval(updateHomeClocks, 1000);
</script>
<?php include __DIR__ . '/includes/footer.php'; ?>
