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

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

  <!-- Albums -->
  <div class="text-center mb-4">
    <h4>Albums</h4>
    <p class="subtext">From classic to modern — we’ve got it all</p>
  </div>
  <div class="row mb-5">
    <div class="col-md-6">
      <a href="playlist.php">
        <img src="assets/images/album1.jpg" class="img-fluid rounded" alt="Album 1 - View Playlist">
      </a>
    </div>
    <div class="col-md-6">
      <a href="playlist.php">
        <img src="assets/images/album2.jpg" class="img-fluid rounded" alt="Album 2 - View Playlist">
      </a>
    </div>
  </div>

  <?php
    // ✅ Comment settings (enabled + display count)
    $commentsFile = 'comments.txt';
    $settingsFile = 'comment-settings.json';

    $displayCount = 3;
    $commentsEnabled = true;

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

  <?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('/-{3,}\s*/', file_get_contents($commentsFile));
        $approved = array_filter($allComments, function($entry) {
          return preg_match('/Approved\s*:\s*true/i', $entry);
        });
        $recent = array_slice(array_reverse($approved), 0, $displayCount);

        foreach ($recent as $entry) {
          $lines = explode("\n", trim($entry));
          $reply = '';
          $content = [];

          foreach ($lines as $line) {
            if (str_starts_with($line, 'Reply:')) {
              $reply = substr($line, 7);
            } elseif (!str_starts_with($line, 'Approved:') && !str_starts_with($line, 'IP:') && !str_starts_with($line, 'Date:')) {
              $content[] = $line;
            }
          }

          echo "<div class='mb-3 border-bottom pb-2'>";
          echo "<p>" . nl2br(htmlspecialchars(implode("\n", $content))) . "</p>";
          if ($reply) {
            echo "<div class='reply-box border rounded p-2 mt-2'><strong>Reply:</strong> " . htmlspecialchars($reply) . "</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; ?>

  <!-- 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
        $newsFile = 'data/news.json';
        if (file_exists($newsFile)) {
          $newsList = json_decode(file_get_contents($newsFile), true);
          if (!empty($newsList)) {
            foreach ($newsList as $news) {
              echo "<div class='htr-box mb-4'>";
              echo "<h5>" . htmlspecialchars($news['title']) . "</h5>";
              echo "<p>" . nl2br(htmlspecialchars($news['body'])) . "</p>";
              echo "<small>Posted: " . date('F j, Y', strtotime($news['timestamp'])) . "</small>";
              echo "</div>";
            }
          } else {
            echo "<p>No news items available.</p>";
          }
        } else {
          echo "<p>News file not found.</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>