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

<main class="main-container">

  <!-- Play Now Section -->
  <section class="play-now">
    <button class="play-button" onclick="openPlayer()">▶ Play Now</button>
    <p class="live-status">Streaming live from the hills</p>
  </section>

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

  <!-- On Air -->
<?php
// Load schedule
$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($line));
    if (count($parts) === 3) {
      [$day, $hour, $dj] = $parts;
      $schedule[$day][$hour] = $dj;
    }
  }
}

// Helper: format 24h to 12h
function formatHour($hour24) {
  $parts = explode(':', $hour24);
  $hour = (int)$parts[0];
  $suffix = $hour >= 12 ? 'PM' : 'AM';
  $hour12 = $hour % 12;
  if ($hour12 === 0) $hour12 = 12;
  return $hour12 . ':00 ' . $suffix;
}

// Determine current slot
date_default_timezone_set('America/New_York'); // adjust to EST or your station TZ
$currentDay = date('l'); // e.g. "Monday"
$currentHour = date('H:00'); // e.g. "08:00"

$todaySchedule = $schedule[$currentDay] ?? [];
$hours = array_keys($todaySchedule);
sort($hours);

$nowDJ = $todaySchedule[$currentHour] ?? 'No DJ scheduled';
$nextDJ = 'No DJ scheduled';
$comingDJ = 'No DJ scheduled';

// Find next slots
$found = false;
foreach ($hours as $h) {
  if ($h > $currentHour) {
    if (!$found) {
      $nextDJ = $todaySchedule[$h];
      $found = true;
    } elseif ($comingDJ === 'No DJ scheduled') {
      $comingDJ = $todaySchedule[$h];
      break;
    }
  }
}
?>

<section class="schedule-preview">
  <h2 class="text-warning">On Air</h2>
  <div class="dj-slot now">
    <strong>Now:</strong> <?= htmlspecialchars($nowDJ) ?>
  </div>
  <div class="dj-slot next">
    <strong>Next:</strong> <?= htmlspecialchars($nextDJ) ?>
  </div>
  <div class="dj-slot coming">
    <strong>Coming Up:</strong> <?= htmlspecialchars($comingDJ) ?>
  </div>
</section>


  <!-- Now Playing -->
  <section class="schedule-preview">
    <h2 class="text-warning">Now Playing</h2>
    <div class="dj-slot now">
      <p><strong>Track:</strong> <span id="track-text">Loading...</span></p>
    </div>
  </section>

  <!-- Leave a Comment -->
  <section class="schedule-preview">
    <h2 class="text-warning">Leave a Comment</h2>
    <div class="dj-slot next">
      <form method="post" action="comments/submit_comment.php">
        <input type="hidden" name="return_to" value="<?= htmlspecialchars($_SERVER['REQUEST_URI'] ?? '/index.php') ?>">
        <input type="text" name="name" placeholder="Your name" required class="form-control mb-2">
        <textarea name="message" placeholder="Your message" required class="form-control mb-2"></textarea>
        <button type="submit" class="btn btn-dark">Send</button>
      </form>
    </div>
  </section>

  <!-- Recent Comments -->
 <?php
    $comments_file = __DIR__ . '/data/comments.json'; // ✅ correct path if index.php is in root
    $comments = file_exists($comments_file) ? json_decode(file_get_contents($comments_file), true) : [];
?>
  <section class="schedule-preview">
    <h2 class="text-warning">Recent Comments</h2>
    <div class="dj-slot coming">
      <ul class="list-unstyled">
        <?php foreach ($comments as $comment): ?>
          <?php if (!empty($comment['approved'])): ?>
            <li class="mb-3">
              <strong><?= htmlspecialchars($comment['name']) ?>:</strong><br>
              <?= htmlspecialchars($comment['message']) ?><br>
              <em>(<?= $comment['timestamp'] ?>)</em>
              <?php if (!empty($comment['reply'])): ?>
                <br><strong>Reply:</strong> <?= htmlspecialchars($comment['reply']) ?>
              <?php endif; ?>
            </li>
          <?php endif; ?>
        <?php endforeach; ?>
      </ul>
    </div>
  </section>

  <!-- Poll Section -->
  <?php
    $poll_file = 'poll/poll.json';
    $poll = file_exists($poll_file) ? json_decode(file_get_contents($poll_file), true) : [];
  ?>
  <?php if (!empty($poll)): ?>
    <section class="schedule-preview">
      <h2 class="text-warning">Current Poll</h2>
      <div class="dj-slot now">
        <p><strong><?= htmlspecialchars($poll['question']) ?></strong></p>
        <form method="post" action="poll/submit_vote.php">
          <input type="hidden" name="return_to" value="<?= htmlspecialchars($_SERVER['REQUEST_URI'] ?? '/index.php') ?>">
          <?php foreach ($poll['options'] as $opt): ?>
            <div class="form-check mb-2">
              <input class="form-check-input" type="radio" name="option" value="<?= htmlspecialchars($opt) ?>" required>
              <label class="form-check-label"><?= htmlspecialchars($opt) ?></label>
            </div>
          <?php endforeach; ?>
          <button type="submit" class="btn btn-dark">Vote</button>
        </form>
      </div>
    </section>
  <?php endif; ?>

</main>

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

<script>
  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(); // initial load
  setInterval(updateTrack, 30000); // refresh every 30 seconds
</script>
