<?php include('header.php'); ?>
<?php include('menu.php'); ?>
<link rel="stylesheet" href="/css/style.css">

<?php
// ------------------------------
// Home helpers
// ------------------------------
function ah_home_format_hour($hour24) {
  $parts = explode(':', (string)$hour24);
  $hour = (int)($parts[0] ?? 0);
  $suffix = $hour >= 12 ? 'PM' : 'AM';
  $hour12 = $hour % 12;
  if ($hour12 === 0) $hour12 = 12;
  return $hour12 . ':00 ' . $suffix;
}

function ah_home_trim_text($text, $limit = 220) {
  $text = trim(preg_replace('/\s+/', ' ', strip_tags((string)$text)));
  if (mb_strlen($text) <= $limit) return $text;
  return rtrim(mb_substr($text, 0, $limit - 1)) . '…';
}

function ah_load_featured_news($baseDir) {
  $newsDir = $baseDir . '/data/news';
  $featured = null;

  if (is_dir($newsDir)) {
    $files = glob($newsDir . '/*.json') ?: [];
    usort($files, function($a, $b){ return filemtime($b) <=> filemtime($a); });
    foreach ($files as $file) {
      $post = json_decode((string)file_get_contents($file), true);
      if (!is_array($post)) continue;
      if (!empty($post['featured_home']) || !empty($post['featured']) || !empty($post['pinned'])) {
        $featured = [
          'title' => (string)($post['title'] ?? 'Featured News'),
          'body' => (string)($post['body'] ?? $post['content'] ?? ''),
          'tag' => (string)($post['tag'] ?? ''),
          'author' => (string)($post['author'] ?? ''),
          'date' => (string)($post['date'] ?? ''),
          'url' => '/news/index.php'
        ];
        break;
      }
    }
  }

  if ($featured) return $featured;

  // Legacy fallback: pinned first entry from news.txt/news_pinned.txt
  $newsFile = $baseDir . '/data/news.txt';
  $pinnedFile = $baseDir . '/data/news_pinned.txt';
  if (!file_exists($newsFile)) return null;

  $entries = explode("---
", (string)file_get_contents($newsFile));
  $pinned = file_exists($pinnedFile) ? preg_split('/\R+/', trim((string)file_get_contents($pinnedFile))) : [];
  $items = [];
  foreach ($entries as $index => $entry) {
    $lines = preg_split('/\R/', trim($entry));
    if (!$lines || trim((string)$lines[0]) === '') continue;
    $title = array_shift($lines);
    $body = trim(implode("
", $lines));
    $items[] = [
      'title' => (string)$title,
      'body' => $body,
      'pinned' => in_array((string)$index, $pinned, true),
      'url' => '/news/index.php'
    ];
  }
  usort($items, fn($a, $b) => ($b['pinned'] <=> $a['pinned']));
  return $items[0] ?? null;
}

function ah_load_featured_event($baseDir) {
  $promoFile = $baseDir . '/data/promo.json';
  if (!file_exists($promoFile)) return null;
  $promo = json_decode((string)file_get_contents($promoFile), true);
  if (!is_array($promo) || empty($promo['enabled'])) return null;

  return [
    'title' => (string)($promo['title'] ?? 'Featured Event'),
    'body' => (string)($promo['description'] ?? ''),
    'start' => (string)($promo['start'] ?? ''),
    'end' => (string)($promo['end'] ?? ''),
    'prizes' => is_array($promo['prizes'] ?? null) ? $promo['prizes'] : [],
    'url' => '/events.php'
  ];
}

// ------------------------------
// Schedule / on-air data
// ------------------------------
$scheduleFile = __DIR__ . '/data/schedule.txt';
$schedule = [];
if (file_exists($scheduleFile)) {
  $lines = file($scheduleFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  foreach ($lines as $line) {
    $parts = explode('|', trim((string)$line));
    if (count($parts) === 3) {
      [$day, $hour, $dj] = $parts;
      $schedule[$day][$hour] = $dj;
    }
  }
}

date_default_timezone_set('America/New_York');
$currentDay = date('l');
$currentHour = date('H:00');
$todaySchedule = $schedule[$currentDay] ?? [];
$hours = array_keys($todaySchedule);
sort($hours);

$nowDJ = $todaySchedule[$currentHour] ?? 'No DJ scheduled';
$nextDJ = 'No DJ scheduled';
$comingDJ = 'No DJ scheduled';
$futureHours = [];
foreach ($hours as $h) {
  if ($h > $currentHour) $futureHours[] = $h;
}
if (!empty($futureHours[0])) $nextDJ = $todaySchedule[$futureHours[0]] ?? 'No DJ scheduled';
if (!empty($futureHours[1])) $comingDJ = $todaySchedule[$futureHours[1]] ?? 'No DJ scheduled';

$featuredNews = ah_load_featured_news(__DIR__);
$featuredEvent = ah_load_featured_event(__DIR__);
$comments_file = __DIR__ . '/data/comments.json';
$comments = file_exists($comments_file) ? json_decode((string)file_get_contents($comments_file), true) : [];
if (!is_array($comments)) $comments = [];
$approvedComments = array_values(array_filter($comments, fn($c) => !empty($c['approved'])));
$approvedComments = array_slice(array_reverse($approvedComments), 0, 4);

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

$directoryLinks = [
  ['label' => 'MyTuner Radio', 'url' => '#'],
  ['label' => 'Online Radio Box', 'url' => '#'],
  ['label' => 'Radio Spinner', 'url' => '#'],
  ['label' => 'Discord', 'url' => '#'],
];
?>

<main class="main-container home-shell home-pro-shell">
  <section class="home-hero-grid">
    <div class="home-main-column">
      <section class="play-now home-card home-card-soft">
        <button class="play-button" onclick="openPlayer()">▶ Play Now</button>
        <p class="live-status">Streaming live from the hills</p>
      </section>

      <section class="home-card onair-card">
        <div class="section-heading-row">
          <h2 class="text-warning">On Air Right Now</h2>
          <p class="section-heading-sub"><?= htmlspecialchars($currentDay) ?> schedule snapshot</p>
        </div>
        <div class="onair-grid-3">
          <div class="dj-slot home-status-slot now">
            <span class="slot-label">Now</span>
            <strong><?= htmlspecialchars($nowDJ) ?></strong>
          </div>
          <div class="dj-slot home-status-slot next">
            <span class="slot-label">Next</span>
            <strong><?= htmlspecialchars($nextDJ) ?></strong>
          </div>
          <div class="dj-slot home-status-slot coming">
            <span class="slot-label">Coming Up</span>
            <strong><?= htmlspecialchars($comingDJ) ?></strong>
          </div>
        </div>
      </section>

      <section class="home-card home-card-soft">
        <div class="section-heading-row centered-title">
          <h2 class="text-warning">🎶 What’s Playing Now</h2>
        </div>
        <div class="dj-slot now home-track-slot">
          <p><strong>Track:</strong> <span id="track-text">Loading...</span></p>
        </div>
      </section>

      <?php if ($featuredNews || $featuredEvent): ?>
      <section class="home-card home-feature-wrap">
        <div class="section-heading-row">
          <h2 class="text-warning">Featured on the Mountain</h2>
          <p class="section-heading-sub">Highlighted updates from the station</p>
        </div>
        <div class="home-feature-grid">
          <?php if ($featuredNews): ?>
            <article class="feature-promo-card">
              <span class="feature-kicker">Featured News</span>
              <h3><?= htmlspecialchars($featuredNews['title']) ?></h3>
              <p><?= htmlspecialchars(ah_home_trim_text($featuredNews['body'], 220)) ?></p>
              <a class="feature-link" href="<?= htmlspecialchars($featuredNews['url']) ?>">Read full story →</a>
            </article>
          <?php endif; ?>
          <?php if ($featuredEvent): ?>
            <article class="feature-promo-card">
              <span class="feature-kicker">Featured Event</span>
              <h3><?= htmlspecialchars($featuredEvent['title']) ?></h3>
              <?php if ($featuredEvent['start'] || $featuredEvent['end']): ?>
                <p class="feature-meta">
                  <?php if ($featuredEvent['start']): ?><span>Starts: <?= htmlspecialchars($featuredEvent['start']) ?></span><?php endif; ?>
                  <?php if ($featuredEvent['end']): ?><span>Ends: <?= htmlspecialchars($featuredEvent['end']) ?></span><?php endif; ?>
                </p>
              <?php endif; ?>
              <p><?= htmlspecialchars(ah_home_trim_text($featuredEvent['body'], 220)) ?></p>
              <a class="feature-link" href="<?= htmlspecialchars($featuredEvent['url']) ?>">View event details →</a>
            </article>
          <?php endif; ?>
        </div>
      </section>
      <?php endif; ?>

      <section class="home-card home-comment-card">
        <div class="section-heading-row">
          <h2 class="text-warning">Leave a Comment</h2>
          <p class="section-heading-sub">Say hello to the station</p>
        </div>
        <form method="post" action="comments/submit_comment.php" class="home-comment-form">
          <input type="hidden" name="return_to" value="<?= htmlspecialchars($_SERVER['REQUEST_URI'] ?? '/index.php') ?>">
          <div class="comment-form-grid">
            <div class="comment-input-wrap">
              <label for="home-comment-name">Your name</label>
              <input id="home-comment-name" type="text" name="name" placeholder="Your name" required class="form-control home-form-control">
            </div>
            <div class="comment-input-wrap comment-message-wrap">
              <label for="home-comment-message">Your message</label>
              <textarea id="home-comment-message" name="message" placeholder="Your message" required class="form-control home-form-control home-form-textarea"></textarea>
            </div>
            <div class="comment-submit-wrap">
              <button type="submit" class="btn btn-dark home-comment-btn">Send</button>
            </div>
          </div>
        </form>
      </section>
    </div>

    <aside class="home-side-column">
      <?php if (!empty($approvedComments)): ?>
      <section class="home-card home-side-card">
        <div class="section-heading-row">
          <h2 class="text-warning">Recent Comments</h2>
        </div>
        <div class="home-comment-list">
          <?php foreach ($approvedComments as $comment): ?>
            <article class="mini-comment-card">
              <strong><?= htmlspecialchars($comment['name'] ?? 'Guest') ?></strong>
              <p><?= htmlspecialchars(ah_home_trim_text($comment['message'] ?? '', 140)) ?></p>
              <?php if (!empty($comment['reply'])): ?>
                <div class="mini-comment-reply"><strong>Reply:</strong> <?= htmlspecialchars(ah_home_trim_text($comment['reply'], 100)) ?></div>
              <?php endif; ?>
            </article>
          <?php endforeach; ?>
        </div>
      </section>
      <?php endif; ?>

      <?php if (!empty($poll) && !empty($poll['question']) && !empty($poll['options']) && (!array_key_exists('show_on_home', $poll) || !empty($poll['show_on_home']))): ?>
      <section class="home-card home-side-card">
        <div class="section-heading-row">
          <h2 class="text-warning">Current Poll</h2>
        </div>
        <form method="post" action="poll/submit_vote.php" class="home-poll-form">
          <input type="hidden" name="return_to" value="<?= htmlspecialchars($_SERVER['REQUEST_URI'] ?? '/index.php') ?>">
          <p class="poll-question-home"><strong><?= htmlspecialchars($poll['question']) ?></strong></p>
          <?php foreach ($poll['options'] as $opt): ?>
            <label class="home-poll-option">
              <input type="radio" name="option" value="<?= htmlspecialchars($opt) ?>" required>
              <span><?= htmlspecialchars($opt) ?></span>
            </label>
          <?php endforeach; ?>
          <button type="submit" class="btn btn-dark home-comment-btn">Vote</button>
        </form>
      </section>
      <?php endif; ?>

      <section class="home-card home-side-card">
        <div class="section-heading-row">
          <h2 class="text-warning">Find Us Around the Web</h2>
          <p class="section-heading-sub">Add your live directory links later</p>
        </div>
        <div class="directory-link-list">
          <?php foreach ($directoryLinks as $link): ?>
            <a href="<?= htmlspecialchars($link['url']) ?>" class="directory-pill" <?= $link['url'] === '#' ? '' : 'target="_blank" rel="noopener"' ?>>
              <?= htmlspecialchars($link['label']) ?>
            </a>
          <?php endforeach; ?>
        </div>
      </section>
    </aside>
  </section>
</main>

<?php include('footer.php'); ?>

<script>
  function openPlayer() {
    window.open(
      "http://cr3.broadcasturself.com:6969/stream",
      "streamPlayer",
      "width=400,height=120,resizable=no,scrollbars=no"
    );
  }

  function updateTrack() {
    fetch('/live-track.php')
      .then(response => response.text())
      .then(text => {
        document.getElementById('track-text').textContent = text;
      })
      .catch(() => {
        document.getElementById('track-text').textContent = 'Unable to load track info.';
      });
  }

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