<?php include 'includes/header.php'; ?>
<?php include 'includes/menu.php'; ?>
<?php
date_default_timezone_set('America/New_York');

// ✅ Visitor counter logic
$counterFile = 'data/visitor_count.txt';
if (!file_exists($counterFile)) {
  file_put_contents($counterFile, '0');
}
$visitorCount = (int)file_get_contents($counterFile);
$visitorCount++;
file_put_contents($counterFile, $visitorCount);

// ✅ DJ schedule logic
$scheduleFile = 'data/schedule.txt';
$currentDay = date('l');
$currentHour = date('H') . ':00';

$schedule = [];
if (file_exists($scheduleFile)) {
  $lines = file($scheduleFile, FILE_IGNORE_NEW_LINES);
  foreach ($lines as $line) {
    $parts = explode('|', trim($line));
    if (count($parts) === 3) {
      [$day, $hour, $dj] = $parts;
      $schedule[$day][$hour] = $dj;
    }
  }
}

$currentDJ = $schedule[$currentDay][$currentHour] ?? 'DJ BLAZE';
$nextHourIndex = (int)substr($currentHour, 0, 2) + 1;
$nextHour = str_pad($nextHourIndex % 24, 2, '0', STR_PAD_LEFT) . ':00';
$nextDJ = $schedule[$currentDay][$nextHour] ?? 'DJ BLAZE';

$comingAfter = [];
$hour = str_pad(($nextHourIndex + 1) % 24, 2, '0', STR_PAD_LEFT) . ':00';
$comingAfter[] = $schedule[$currentDay][$hour] ?? 'DJ BLAZE';

// ✅ Poll logic
$pollJsonFile = 'data/poll.json';
$votesJsonFile = 'data/poll_votes.json';
$pollFile = 'data/poll.txt';
$votesFile = 'data/poll_votes.txt';
$poll = [];
$votes = [];
$pollShowOnHome = true;
if (file_exists($pollJsonFile)) {
  $pollJson = json_decode((string)file_get_contents($pollJsonFile), true);
  if (is_array($pollJson) && !empty($pollJson['question'])) {
    $pollShowOnHome = !array_key_exists('show_on_home', $pollJson) || !empty($pollJson['show_on_home']);
    $poll[] = trim((string)$pollJson['question']) . '|';
    foreach ((array)($pollJson['options'] ?? []) as $opt) {
      $opt = trim((string)$opt);
      if ($opt !== '') $poll[] = $opt . '|';
    }
  }
  $votesJson = file_exists($votesJsonFile) ? json_decode((string)file_get_contents($votesJsonFile), true) : [];
  if (is_array($votesJson)) {
    foreach (array_slice($poll, 1) as $i => $line) {
      $opt = trim((string)explode('|', $line, 2)[0]);
      $votes[$i] = (int)($votesJson[$opt] ?? $votesJson[$i] ?? 0);
    }
  }
} elseif (file_exists($pollFile)) {
  $poll = file($pollFile, FILE_IGNORE_NEW_LINES) ?: [];
  $votes = file_exists($votesFile) ? array_map('intval', file($votesFile, FILE_IGNORE_NEW_LINES)) : [];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['vote'])) {
  $voteIndex = (int)$_POST['vote'];
  $votes[$voteIndex] = ($votes[$voteIndex] ?? 0) + 1;
  file_put_contents($votesFile, implode("\n", $votes));
  if (file_exists($pollJsonFile)) {
    $votesJson = file_exists($votesJsonFile) ? json_decode((string)@file_get_contents($votesJsonFile), true) : [];
    if (!is_array($votesJson)) $votesJson = [];
    $opt = trim((string)explode('|', (string)($poll[$voteIndex + 1] ?? ''), 2)[0]);
    if ($opt !== '') {
      $votesJson[$opt] = (int)($votesJson[$opt] ?? 0) + 1;
      file_put_contents($votesJsonFile, json_encode($votesJson, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
    }
  }
  echo "<div class='alert alert-success'>Thanks for voting!</div>";
}
?>

<div class="container mt-5">
  <!-- Hero Section -->
  <div class="text-center mb-5 logo-wrap">
    <img src="assets/images/tmr.png" alt="Thunder Mountain Radio Logo" class="img-fluid mb-3" style="max-width: 600px;">
    <h1>Thunder Mountain Radio</h1>
    <p class="lead">Where lightning strikes and music roars</p>
    <a href="/stream-proxy.php" class="btn btn-primary mt-3">▶ Play Now</a>
  </div>

  <!-- DJ Schedule -->
  <div class="row text-center mb-5">
    <div class="col-md-4">
      <div class="dj-box">
        <h3>Now On Air</h3>
        <p><strong><?= $currentDJ ?></strong> (<?= $currentHour ?> EST)</p>
      </div>
    </div>
    <div class="col-md-4">
      <div class="dj-box">
        <h3>Next Up</h3>
        <p><strong><?= $nextDJ ?></strong> (<?= $nextHour ?> EST)</p>
      </div>
    </div>
    <div class="col-md-4">
      <div class="dj-box">
        <h3>Coming After</h3>
        <ul class="list-unstyled">
          <?php foreach ($comingAfter as $dj): ?>
            <li><strong><?= $dj ?></strong></li>
          <?php endforeach; ?>
        </ul>
      </div>
    </div>
  </div>

  <!-- What's Playing Now -->
  <div class="text-center mb-5 content-box">
    <h4>🎶 What’s Playing Now</h4>
    <?php include 'nowplaying.php'; ?>
  </div>

  <!-- Comment Box -->
<div class="mb-5 content-box">
  <h4>💬 Leave a Comment</h4>
  <?php
  // Use consistent paths
  $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) : [];

  // Handle new comment submission
  if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['comment']) && !empty($_POST['name']) && !isset($_POST['vote'])) {
    if (in_array($userIP, $banned)) {
      echo "<div class='alert alert-danger'>Your IP is banned from posting comments.</div>";
    } else {
      $id        = uniqid();
      $name      = trim($_POST['name']);
      $message   = trim($_POST['comment']);
      $timestamp = date('Y-m-d H:i:s');
      $approved  = 'no'; // default until admin approves
      $entry     = "$id|$name|$message|$userIP|$timestamp|$approved\n";
      file_put_contents($commentsFile, $entry, FILE_APPEND);
      echo "<div class='alert alert-success'>Thanks for your comment! It will appear once approved.</div>";
    }
  }
  ?>
  <form method="POST">
    <input type="text" name="name" class="form-control mb-2" placeholder="Your name" required>
    <textarea name="comment" class="form-control mb-2" placeholder="Share your thoughts..." required></textarea>
    <button type="submit" class="btn btn-primary">Post Comment</button>
  </form>
</div>

<!-- Recent Comments -->
<div class="content-box mb-5">
  <h5>🗨️ Recent Comments</h5>
  <?php
  $comments = file_exists($commentsFile) ? file($commentsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : [];

  // Only show approved comments
  $approved = array_filter($comments, function($line) {
    $parts = explode('|', trim($line));
    return isset($parts[5]) && $parts[5] === 'yes';
  });

  // Show up to 3 most recent
  $recent = array_slice(array_reverse($approved), 0, 3);

  if (empty($recent)) {
    echo "<p>No comments yet.</p>";
  } else {
    foreach ($recent as $line) {
      $parts = explode('|', trim($line));
      if (count($parts) === 6) {
        list($id, $name, $message, $ip, $timestamp, $approvedFlag) = $parts;
        echo "<div class='comment-box'>";
        echo "<strong>" . htmlspecialchars($name) . "</strong><br>";
        echo nl2br(htmlspecialchars($message));
        echo "<br><small>" . date('M j, Y g:i A', strtotime($timestamp)) . "</small>";
        echo "</div>";
      }
    }
  }
  ?>
</div>


  <!-- Station Poll -->
  <?php if (!empty($poll) && $pollShowOnHome): list($q_en, $q_ru) = explode('|', $poll[0]); ?>
    <div class="content-box mb-5">
      <h4>📊 Station Poll</h4>
      <p><strong><?= htmlspecialchars($q_en) ?></strong></p>
      <ul class="list-group mt-3">
        <?php foreach (array_slice($poll, 1) as $i => $line): ?>
          <?php list($opt_en, $opt_ru) = explode('|', $line); ?>
          <li class="list-group-item d-flex justify-content-between align-items-center">
            <?= htmlspecialchars($opt_en) ?>
            <span class="badge bg-primary rounded-pill"><?= $votes[$i] ?? 0 ?> votes</span>
          </li>
        <?php endforeach; ?>
      </ul>
      <form method="POST" class="mt-4">
        <?php foreach (array_slice($poll, 1) as $i => $line): ?>
          <?php list($opt_en, $opt_ru) = explode('|', $line); ?>
          <div class="form-check">
            <input class="form-check-input" type="radio" name="vote" value="<?= $i ?>" id="vote<?= $i ?>" required>
            <label class="form-check-label" for="vote<?= $i ?>"><?= htmlspecialchars($opt_en) ?></label>
          </div>
        <?php endforeach; ?>
        <button type="submit" class="btn btn-success mt-3">Vote</button>
      </form>
    </div>
  <?php endif; ?>

  <!-- Visitor Counter -->
  <div class="text-center mb-5 content-box">
    <p>👀 Visitors so far: <?= $visitorCount ?></p>
  </div>
</div>

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