<?php
session_start();
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/nav.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)) {
    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)) {
  foreach (file($friendsTxtFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [] as $line) {
    $parts = array_map('trim', explode('|', $line));
    if (count($parts) < 3) continue;
    $friends[] = ['name' => $parts[0], 'desc' => $parts[1], 'link' => $parts[2], 'image' => ''];
  }
}
?>
<main class="content-area">
  <div class="content-wrapper page-shell">
    <section class="content-card center-text">
      <div class="page-intro">
        <h1>🤝 Friends of Thunder</h1>
      </div>
      <?php if (empty($friends)): ?>
        <p>No friends listed yet.</p>
      <?php else: ?>
        <div class="row g-4">
          <?php foreach ($friends as $friend): ?>
            <div class="col-md-6">
              <div class="content-card h-100">
                <?php if (!empty($friend['image'])): ?><img src="<?= htmlspecialchars($friend['image']) ?>" alt="<?= htmlspecialchars($friend['name']) ?>" class="img-fluid mb-3 rounded" style="max-height:180px;"><?php endif; ?>
                <h3><?= htmlspecialchars($friend['name']) ?></h3>
                <p><?= nl2br(htmlspecialchars($friend['desc'])) ?></p>
                <?php if (!empty($friend['link'])): ?><a href="<?= htmlspecialchars($friend['link']) ?>" target="_blank" rel="noopener" class="button play-btn">Visit</a><?php endif; ?>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </section>
  </div>
</main>
<?php include __DIR__ . '/includes/footer.php'; ?>
