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

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

function smurf_load_schedule_hourmap($jsonFile, $txtFile, $daysOrder) {
    // Expected JSON format: {"Monday": {"0":"Show — DJ", "13":"..."}, ...}
    if (file_exists($jsonFile) && filesize($jsonFile) > 5) {
        $j = json_decode(file_get_contents($jsonFile), true);
        if (is_array($j)) return $j;
    }

    // Fallback: legacy TXT formats
    // Day|HH:MM|DJ
    // Day|HH:MM|Show Title|DJ
    $out = [];
    foreach ($daysOrder as $d) $out[$d] = [];
    if (file_exists($txtFile) && filesize($txtFile) > 0) {
        foreach (file($txtFile, FILE_IGNORE_NEW_LINES) as $line) {
            $line = trim($line);
            if ($line === '' || str_starts_with($line, '#')) continue;
            $parts = array_map('trim', explode('|', $line));
            if (count($parts) < 3) continue;
            $day  = $parts[0];
            $time = $parts[1];
            if (!in_array($day, $daysOrder, true)) continue;
            if (!preg_match('/^\d{2}:\d{2}$/', $time)) continue;
            $hour = (int)substr($time, 0, 2);

            $title = '';
            $dj = '';
            if (count($parts) >= 4) { $title = $parts[2]; $dj = $parts[3]; }
            else { $dj = $parts[2]; }

            $val = ($title !== '' ? $title : $dj);
            if ($title !== '' && $dj !== '' && $title !== $dj) $val = $title . ' — ' . $dj;
            if ($val !== '') $out[$day][$hour] = $val;
        }
        foreach ($daysOrder as $d) {
            if (isset($out[$d]) && is_array($out[$d])) ksort($out[$d]);
        }
    }
    return $out;
}

function smurf_extract_dj($val) {
    $val = trim((string)$val);
    if ($val === '') return '';
    $parts = explode('—', $val, 2);
    if (count($parts) === 2) return trim($parts[1]);
    return $val; // if only DJ name stored
}

$schedule = smurf_load_schedule_hourmap($scheduleJson, $scheduleTxt, $daysOrder);

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

$currentDJ = smurf_extract_dj($todayMap[$currentHourInt] ?? '') ?: 'Auto DJ';

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

$comingAfter = [];
$afterIndex = ($currentHourInt + 2) % 24;
$comingAfter[] = smurf_extract_dj($todayMap[$afterIndex] ?? '') ?: 'Auto DJ';

/* ------------------------------
   POLL
------------------------------ */
$pollFile  = __DIR__ . '/data/poll.txt';
$votesFile = __DIR__ . '/data/poll_votes.txt';

$poll  = (file_exists($pollFile) && filesize($pollFile) > 0)
    ? file($pollFile, FILE_IGNORE_NEW_LINES)
    : [];

$votes = (file_exists($votesFile) && filesize($votesFile) > 0)
    ? array_map('intval', file($votesFile, FILE_IGNORE_NEW_LINES))
    : [];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['vote']) && $poll) {
    $i = (int)$_POST['vote'];
    $votes[$i] = ($votes[$i] ?? 0) + 1;
    file_put_contents($votesFile, implode("\n", $votes));
    $pollMessage = "<div class='msg success'>Thanks for voting!</div>";
}

/* ------------------------------
   FEATURED NEWS
------------------------------ */
$featuredNewsFile = __DIR__ . '/data/featured_news.txt';
$featuredNews = (file_exists($featuredNewsFile) && filesize($featuredNewsFile) > 0)
    ? trim(file_get_contents($featuredNewsFile))
    : '';
?>

<main class="content-area">

    <!-- HERO -->
    <div class="content-wrapper">
        <section class="content-card hero-card center-text">
            <h1 class="hero-title">Smurfette's Country Delights</h1>
            <p class="hero-tagline">Real Country • Real Community • Real Music</p>

            <a href="http://cr3.broadcasturself.com:1982/stream" class="button play-btn" target="_blank">
                ▶ 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">RadioSpiner</a>
                </div>
            </div>
        </section>
    </div>

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

    <!-- FEATURED NEWS (conditional) -->
    <?php if (!empty($featuredNews)): ?>
        <div class="content-wrapper">
            <section class="content-card center-text">
                <h2>📰 Featured News</h2>
                <p><?= nl2br(htmlspecialchars($featuredNews)) ?></p>
                <a href="/news.php" class="button play-btn">Read More</a>
            </section>
        </div>

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

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

    <!-- FIXED CLOCK SCRIPT -->
    <script>
        function updateClocks() {
            const now = new Date();

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

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

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

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

    <!-- POLL (conditional) -->
    <?php if (!empty($poll)):
        list($q_en) = explode('|', $poll[0]);
    ?>
        <div class="content-wrapper">
            <section class="content-card center-text">
                <h2>📊 Station Poll</h2>
                <?= $pollMessage ?? '' ?>
                <p><strong><?= htmlspecialchars($q_en) ?></strong></p>

                <form method="POST">
                    <?php foreach (array_slice($poll, 1) as $i => $line):
                        list($opt_en) = explode('|', $line); ?>
                        <label class="radio">
                            <input type="radio" name="vote" value="<?= $i ?>" required>
                            <?= htmlspecialchars($opt_en) ?>
                        </label>
                    <?php endforeach; ?>

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

                <div class="poll-results">
                    <?php foreach (array_slice($poll, 1) as $i => $line):
                        list($opt_en) = explode('|', $line); ?>
                        <p><?= htmlspecialchars($opt_en) ?> — <strong><?= $votes[$i] ?? 0 ?></strong> votes</p>
                    <?php endforeach; ?>
                </div>
            </section>
        </div>

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


<?php
/* ------------------------------
   SMURFETTES 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];
    foreach ($lines as $line) {
      if (strpos($line, ':') === false) continue;
      [$k,$v] = explode(':', $line, 2);
      $k = trim($k); $v = trim($v);
      if ($k !== '') $entry[$k] = $v;
    }
    $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) {
  return md5((string)($item['_raw'] ?? ''));
}

$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'));
?>
<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'; ?>