<?php include 'includes/header.php'; ?>
<?php include 'includes/menu.php'; ?>

<?php
$friendsJsonFile = __DIR__ . '/data/friends.json';
$friendsTxtFile  = __DIR__ . '/data/friends.txt';
$friends = [];

if (file_exists($friendsJsonFile)) {
  $json = json_decode((string)file_get_contents($friendsJsonFile), true);
  if (is_array($json) && !empty($json)) {
    foreach ($json as $row) {
      if (!is_array($row)) continue;
      $img = trim((string)($row['image'] ?? ''));
      if ($img !== '' && !preg_match('~^https?://~i', $img)) {
        $img = '/img/friends/' . ltrim($img, '/');
      }
      $friends[] = [
        'name' => trim((string)($row['name'] ?? '')),
        'desc' => trim((string)($row['description'] ?? '')),
        'link' => trim((string)($row['url'] ?? '')),
        'image' => $img,
      ];
    }
  }
}

if (empty($friends) && file_exists($friendsTxtFile)) {
  $lines = file($friendsTxtFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  foreach ($lines as $line) {
    $parts = array_map('trim', explode('|', $line));
    if (count($parts) < 5) continue;
    [$id, $name, $desc, $link, $image] = $parts;
    $img = '';
    if ($image !== '') {
      $img = preg_match('~^https?://~i', $image) ? $image : ('/img/friends/' . ltrim($image, '/'));
    }
    $friends[] = ['name' => $name, 'desc' => $desc, 'link' => $link, 'image' => $img];
  }
}
?>

<div class="container mt-5">
  <div class="content-box">
    <h2>🤝 Friends of Thunder Mountain</h2>
    <p class="mb-4">These stations and creators share our spirit — loud, proud, and built for cosmic connection.</p>

    <?php if (!empty($friends)): ?>
      <div class="row g-4">
        <?php foreach ($friends as $friend): ?>
          <div class="col-md-6">
            <div class="dj-box">
              <?php if (!empty($friend['image'])): ?>
                <img src="<?= htmlspecialchars($friend['image']) ?>" alt="<?= htmlspecialchars($friend['name']) ?>" class="img-fluid mb-2 rounded" style="max-height:150px;">
              <?php endif; ?>
              <h4><?= htmlspecialchars($friend['name']) ?></h4>
              <p><?= nl2br(htmlspecialchars($friend['desc'])) ?></p>
              <?php if (!empty($friend['link'])): ?>
                <a href="<?= htmlspecialchars($friend['link']) ?>" target="_blank" rel="noopener" class="btn btn-sm btn-info">🔗 Visit</a>
              <?php endif; ?>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    <?php else: ?>
      <p>No friends listed yet. The mountain stands alone… for now.</p>
    <?php endif; ?>
  </div>
</div>

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