<?php include 'includes/header.php'; ?>
<?php date_default_timezone_set('America/New_York'); ?>
<?php
require_once __DIR__ . '/includes/content_store.php';
function ht_home_asset_url(string $path, string $fallbackDir = ''): string {
  $path = trim($path);
  if ($path === '') return '';
  if (preg_match('#^(https?:)?//#i', $path) || str_starts_with($path, 'data:')) return $path;
  $path = str_replace('\\', '/', $path);
  $path = ltrim($path, '/');
  if ($fallbackDir !== '' && strpos($path, '/') === false) $path = trim($fallbackDir, '/') . '/' . $path;
  return '/' . $path;
}
function ht_home_truncate(string $text, int $limit): string {
  $text = trim($text);
  if (mb_strlen($text) <= $limit) return $text;
  return rtrim(mb_substr($text, 0, $limit - 3)) . '...';
}
?>

<style>
  body {
    background: url('assets/images/bg-1.png') no-repeat center top;
    background-size: cover;
    background-attachment: fixed;
    background-color: #000;
  }

  .clock-box {
    background-color: rgba(0, 0, 0, 0.7);
    border: 2px solid var(--accent-color);
    border-radius: 8px;
    padding: 1em;
    color: var(--text-color);
    font-size: 1.2em;
    text-align: center;
    animation: pulse 1s infinite;
    box-shadow: 0 0 10px rgba(0, 204, 136, 0.3);
  }

  @keyframes pulse {
    0% { transform: scale(1); opacity: 1; }
    50% { transform: scale(1.05); opacity: 0.85; }
    100% { transform: scale(1); opacity: 1; }
  }

  .htr-box {
    background-color: var(--panel-color);
    color: var(--text-color);
    padding: 1.5em;
    border-radius: 10px;
    border: 2px solid var(--accent-color);
    box-shadow: 0 0 12px rgba(0, 204, 136, 0.3);
    margin-bottom: 2em;
  }

  .htr-box h4,
  .htr-box h5 {
    color: var(--accent-color);
    margin-bottom: 0.75em;
  }

  .htr-box ul.list-group li {
    background-color: var(--button-color);
    color: var(--accent-color);
    border: none;
    margin-bottom: 0.5em;
  }
</style>

<div class="container content-box mt-5">

  <!-- Hero Section -->
  <div class="text-center mb-5">
    <h1>Welcome to Home Time Radio</h1>
    <div class="my-3">
      <img src="assets/images/logohtr.png" alt="Home Time Radio Logo" class="img-fluid" style="max-width: 700px">
    </div>
    <p class="subtext">Your home for classic rewind and fresh hits</p>
    <a href="http://cr3.broadcasturself.com:65000/stream" class="btn btn-primary mt-3">▶ Play Now</a>

    <div class="mt-4 d-flex justify-content-center flex-wrap gap-3">
      <a href="https://mytuner-radio.com/radio/home-time-radio-507690" target="_blank" class="btn btn-accent d-inline-flex align-items-center gap-2">
        <img src="https://static2.mytuner.mobi/static/widgets/mytuner-radio.png" alt="Listen on MyTuner" style="height: 48px;">
        Listen on MyTuner
      </a>

      <a href="https://onlineradiobox.com/us/hometime" target="_blank" class="btn btn-accent d-inline-flex align-items-center gap-2">
        <img src="https://cdn.onlineradiobox.com/img/b/88x31.png" alt="Listen on RadioBox" style="height: 48px;">
        Listen on RadioBox
      </a>

<!-- ✅ RadioSpinner button FIXED -->
<a href="https://radiospinner.com/stations/home-time-radio-101497/"
   target="_blank"
   rel="noopener"
   class="btn btn-accent d-inline-flex align-items-center gap-2">

  <img src="/assets/images/radiospinner.png"
       style="height: 48px;">

  Listen on RadioSpinner
</a>
    </div>
  </div>

  <!-- DJ Schedule -->
  <div class="row text-center mb-4" id="djSchedule">
    <div class="col-md-4">
      <div class="dj-box">
        <h3>Now On Air</h3>
        <p><strong id="dj-now">Loading...</strong> (<span id="hour-now">--:--</span> EST)</p>
      </div>
    </div>
    <div class="col-md-4">
      <div class="dj-box">
        <h3>Next Up</h3>
        <p><strong id="dj-next">Loading...</strong> (<span id="hour-next">--:--</span> EST)</p>
      </div>
    </div>
    <div class="col-md-4">
      <div class="dj-box">
        <h3>Coming After</h3>
        <p><strong id="dj-after">Loading...</strong> (<span id="hour-after">--:--</span> EST)</p>
      </div>
    </div>
  </div>

  <!-- Dual Clock -->
  <div class="text-center mb-5">
    <h5>Current Time</h5>
    <div class="d-flex justify-content-center gap-4 flex-wrap">
      <div class="clock-box">
        <strong>User Time:</strong><br>
        <span id="localTime">--:--</span>
      </div>
      <div class="clock-box">
        <strong>Station Time (EST):</strong><br>
        <span id="estTime">--:--</span>
      </div>
    </div>
  </div>

  <!-- What's Playing Now -->
  <div class="text-center mb-5">
    <div id="liveTrackInfo">
      🎶 What’s Playing Now<br>
      <span id="track-text">Loading...</span>
    </div>
  </div>

  <!-- Classic Rewind + Discord -->
  <div class="row mb-5">
    <div class="col-md-6">
      <h4>THE HOME OF CLASSIC REWIND</h4>
      <img src="assets/images/bill.png" alt="Vinyl Records" class="img-fluid rounded">
    </div>
    <div class="col-md-6">
      <iframe src="https://discord.com/widget?id=1190186238158852106&theme=dark"
        width="100%" height="670"
        allowtransparency="true" frameborder="0"
        sandbox="allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"
        title="Discord Community Widget"></iframe>
    </div>
  </div>


  <?php
    // ✅ Comment settings (enabled + display count)
    $commentsFile = __DIR__ . '/data/comments.txt';
    $settingsFile = __DIR__ . '/data/settings.json';
    $repliesFile  = __DIR__ . '/data/comment_replies.json';

    $displayCount = 3;
    $commentsEnabled = true;
    $commentReplies = [];

    if (file_exists($settingsFile)) {
      $settings = json_decode((string)file_get_contents($settingsFile), true);
      if (is_array($settings)) {
        if (isset($settings['display_count'])) $displayCount = (int)$settings['display_count'];
        if (isset($settings['comments_enabled'])) $commentsEnabled = (bool)$settings['comments_enabled'];
      }
    }
    if (file_exists($repliesFile)) {
      $commentReplies = json_decode((string)file_get_contents($repliesFile), true);
      if (!is_array($commentReplies)) $commentReplies = [];
    }
  ?>

  <?php if ($commentsEnabled): ?>

    <!-- Comment Box -->
    <div class="mb-5">
      <h4>Leave a Comment, questions , concerns , critisims , locations NO SPAM</h4>
      <form method="POST" action="api/save-comment.php">
        <textarea name="comment" class="form-control mb-2" placeholder="Share your thoughts..." required></textarea>
        <button type="submit" class="btn btn-dark">Post Comment</button>
      </form>
    </div>

    <!-- Recent Comments -->
    <div class="bg-light p-3 rounded mb-5">
      <h5>Recent Comments Will Be Shown Once Approved</h5>
      <?php
      if (file_exists($commentsFile)) {
        $allComments = preg_split('/\n---\s*\n/', trim((string)file_get_contents($commentsFile)));
        $approved = array_filter($allComments, function($entry) {
          return preg_match('/Approved\s*:\s*(?:true|1|yes)/i', (string)$entry);
        });
        $recent = array_slice(array_reverse(array_values($approved)), 0, $displayCount);

        foreach ($recent as $entry) {
          $entry = trim((string)$entry);
          if ($entry === '') continue;
          $lines = explode("\n", $entry);
          $content = [];
          foreach ($lines as $line) {
            if (!str_starts_with($line, 'Approved:') && !str_starts_with($line, 'IP:') && !str_starts_with($line, 'Date:')) {
              $content[] = $line;
            }
          }
          $replyKey = md5($entry);
          $reply = trim((string)($commentReplies[$replyKey]['text'] ?? ''));
          echo "<div class='mb-3 border-bottom pb-2'>";
          echo "<p>" . nl2br(htmlspecialchars(implode("\n", $content), ENT_QUOTES, 'UTF-8')) . "</p>";
          if ($reply !== '') {
            echo "<div class='reply-box border rounded p-2 mt-2'><strong>Reply:</strong> " . nl2br(htmlspecialchars($reply, ENT_QUOTES, 'UTF-8')) . "</div>";
          }
          echo "</div>";
        }
      } else {
        echo "<p>No comments yet.</p>";
      }
      ?>
    </div>

  <?php else: ?>

    <div class="mb-5">
      <div class="alert alert-info text-center">
        Comments are currently disabled.
      </div>
    </div>

  <?php endif; ?>


  <?php
    $featuredPost = null;
    foreach (ht_load_news_items(__DIR__) as $newsItem) {
      if (empty($newsItem['published']) || empty($newsItem['featured_home'])) continue;
      $featuredPost = [
        'title' => trim((string)($newsItem['title'] ?? 'Featured News')),
        'content' => trim((string)($newsItem['content'] ?? '')),
        'image' => ht_asset_url((string)($newsItem['image'] ?? ''), 'img/content'),
      ];
      break;
    }

    $featuredEvent = null;
    foreach (ht_load_event_items(__DIR__) as $eventItem) {
      if (empty($eventItem['published']) || empty($eventItem['featured_home'])) continue;
      $featuredEvent = [
        'title' => trim((string)($eventItem['title'] ?? 'Featured Event')),
        'description' => trim((string)($eventItem['description'] ?? '')),
        'image' => ht_asset_url((string)($eventItem['image'] ?? ''), 'img/content'),
        'url' => '/events.php',
      ];
      break;
    }
  ?>

  <?php if (!empty($featuredPost) || !empty($featuredEvent)): ?>
  <div class="row mb-5 g-4">
    <?php if (!empty($featuredPost)): ?>
    <div class="col-md-6">
      <div class="htr-box d-flex gap-3 align-items-start flex-wrap">
        <?php if (!empty($featuredPost['image'])): ?><img src="<?= htmlspecialchars($featuredPost['image'], ENT_QUOTES, 'UTF-8') ?>" alt="<?= htmlspecialchars($featuredPost['title'], ENT_QUOTES, 'UTF-8') ?>" style="width:120px;height:155px;object-fit:cover;border-radius:14px;flex:0 0 auto;"><?php endif; ?>
        <div style="flex:1;min-width:220px;">
          <h4>📰 Featured News</h4>
          <h5><?= htmlspecialchars($featuredPost['title'], ENT_QUOTES, 'UTF-8') ?></h5>
          <p><?= nl2br(htmlspecialchars(ht_home_truncate((string)$featuredPost['content'], 320), ENT_QUOTES, 'UTF-8')) ?></p>
          <a href="/news.php" class="btn btn-dark">Read More</a>
        </div>
      </div>
    </div>
    <?php endif; ?>
    <?php if (!empty($featuredEvent)): ?>
    <div class="col-md-6">
      <div class="htr-box d-flex gap-3 align-items-start flex-wrap">
        <?php if (!empty($featuredEvent['image'])): ?><img src="<?= htmlspecialchars($featuredEvent['image'], ENT_QUOTES, 'UTF-8') ?>" alt="<?= htmlspecialchars($featuredEvent['title'], ENT_QUOTES, 'UTF-8') ?>" style="width:120px;height:155px;object-fit:cover;border-radius:14px;flex:0 0 auto;"><?php endif; ?>
        <div style="flex:1;min-width:220px;">
          <h4>🎉 Featured Event</h4>
          <h5><?= htmlspecialchars($featuredEvent['title'], ENT_QUOTES, 'UTF-8') ?></h5>
          <p><?= nl2br(htmlspecialchars(ht_home_truncate((string)$featuredEvent['description'], 260), ENT_QUOTES, 'UTF-8')) ?></p>
          <a href="<?= htmlspecialchars($featuredEvent['url'], ENT_QUOTES, 'UTF-8') ?>" class="btn btn-dark">View Event</a>
        </div>
      </div>
    </div>
    <?php endif; ?>
  </div>
  <?php endif; ?>

  <!-- Poll + News Reel Display -->
  <div class="row mb-5">
    <div class="col-md-6">
      <div class="htr-box">
        <h4>📊 Listener Poll</h4>
        <?php
        $pollFile = 'data/poll.json';
        if (file_exists($pollFile)) {
          $polls = json_decode(file_get_contents($pollFile), true);
          if (!empty($polls)) {
            foreach ($polls as $poll) {
              echo "<div class='htr-box mb-4'>";
              echo "<form method='POST' action='vote.php'>";
              echo "<h5>" . htmlspecialchars($poll['question']) . "</h5>";
              echo "<input type='hidden' name='poll_id' value='" . $poll['id'] . "'>";

              $totalVotes = array_sum($poll['votes']);
              echo "<ul class='list-group mb-2'>";
              foreach ($poll['options'] as $index => $option) {
                $votes = $poll['votes'][$index] ?? 0;
                $percent = $totalVotes > 0 ? round(($votes / $totalVotes) * 100) : 0;

                echo "<li class='list-group-item d-flex justify-content-between align-items-center'>";
                echo "<label><input type='radio' name='option' value='$index' required> " . htmlspecialchars($option) . "</label>";
                echo "<span class='badge bg-dark rounded-pill'>$votes vote" . ($votes !== 1 ? 's' : '') . " ($percent%)</span>";
                echo "</li>";
              }
              echo "</ul>";
              echo "<small>Total votes: $totalVotes</small><br>";
              echo "<button type='submit' class='btn btn-primary mt-2'>Submit Vote</button>";
              echo "</form>";
              echo "</div>";
            }
          } else {
            echo "<p>No polls available.</p>";
          }
        } else {
          echo "<p>Poll file not found.</p>";
        }
        ?>
      </div>
    </div>

    <div class="col-md-6">
      <div class="htr-box">
        <h4>📰 Station News</h4>
        <?php
        $newsList = array_values(array_filter(ht_load_news_items(__DIR__), fn($item) => !empty($item['published'])));
        if (!empty($newsList)) {
          foreach ($newsList as $news) {
            echo "<div class='htr-box mb-4'>";
            echo "<h5>" . htmlspecialchars($news['title'] ?? 'News Update') . "</h5>";
            echo "<p>" . nl2br(htmlspecialchars($news['content'] ?? '')) . "</p>";
            $posted = $news['date'] ?? '';
            if ($posted !== '') echo "<small>Posted: " . htmlspecialchars($posted) . "</small>";
            echo "</div>";
          }
        } else {
          echo "<p>No news items available.</p>";
        }
        ?>
      </div>
    </div>
  </div>

  <!-- Footer Credit Box -->
  <div class="htr-box text-center">
    <p>
      This page was developed and powered by abc computing.<br>
      If you have any questions regarding the design of this page,<br>
      please contact admin at <strong>Admin@abc-computing.com</strong>
    </p>
  </div>

</div>

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

<script>
function updateDJSchedule() {
  fetch('live-djs.php')
    .then(response => response.json())
    .then(data => {
      document.getElementById('dj-now').textContent = data.current.dj;
      document.getElementById('hour-now').textContent = data.current.hour;
      document.getElementById('dj-next').textContent = data.next.dj;
      document.getElementById('hour-next').textContent = data.next.hour;
      document.getElementById('dj-after').textContent = data.after.dj;
      document.getElementById('hour-after').textContent = data.after.hour;
    })
    .catch(() => {
      document.getElementById('dj-now').textContent = 'Error';
      document.getElementById('hour-now').textContent = '--:--';
      document.getElementById('dj-next').textContent = 'Error';
      document.getElementById('hour-next').textContent = '--:--';
      document.getElementById('dj-after').textContent = 'Error';
      document.getElementById('hour-after').textContent = '--:--';
    });
}

function updateClocks() {
  const local = new Date();

  const estFormatter = new Intl.DateTimeFormat('en-US', {
    timeZone: 'America/New_York',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: true
  });

  const localFormatter = new Intl.DateTimeFormat([], {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: true
  });

  document.getElementById('localTime').textContent = localFormatter.format(local);
  document.getElementById('estTime').textContent = estFormatter.format(local);
}

function updateTrack() {
  fetch('live-track.php')
    .then(response => response.text())
    .then(html => {
      document.getElementById('track-text').innerHTML = html;
    })
    .catch(() => {
      document.getElementById('track-text').textContent = 'Error fetching track';
    });
}

updateTrack();
updateDJSchedule();
updateClocks();

setInterval(updateTrack, 30000);
setInterval(updateDJSchedule, 60000);
setInterval(updateClocks, 1000);
</script>