<?php include 'includes/header.php';
function ht_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;
}
$friends=[];
$dataFile=__DIR__.'/data/friends.json';
$legacyFile=__DIR__.'/friends-data.json';
if (file_exists($dataFile)) { $friends=json_decode((string)file_get_contents($dataFile), true); }
if (!is_array($friends) || !$friends) { if (file_exists($legacyFile)) { $friends=json_decode((string)file_get_contents($legacyFile), true); } }
if (!is_array($friends)) $friends=[];
?>
<style>
.friend-card{background:rgba(59,43,32,.95);border:2px solid var(--accent-color);border-radius:18px;padding:1.2rem;height:100%;box-shadow:0 10px 24px rgba(0,0,0,.26);display:flex;flex-direction:column;}
.friend-card img{width:100%;height:220px;object-fit:contain;background:rgba(0,0,0,.28);border:2px solid var(--accent-color);border-radius:14px;padding:.35rem;}
.friend-card h4{margin:1rem 0 .35rem;}
.friend-card p{color:#fff;flex:1;}
.friend-card .btn-dark{margin-top:auto;align-self:flex-start;}
</style>
<div class="container content-box mt-5">
  <div class="text-center mb-5"><h1>Our Radio Friends</h1><p class="subtext">Explore other great stations in our extended broadcast family</p></div>
  <div class="row g-4">
    <?php foreach ($friends as $station): $link=$station['url'] ?? ($station['link'] ?? '#'); $img=ht_asset_url((string)($station['image'] ?? ''),'img/friends'); ?>
      <div class="col-md-6 col-xl-4"><div class="friend-card">
        <?php if ($img): ?><img src="<?= htmlspecialchars($img, ENT_QUOTES, 'UTF-8') ?>" alt="<?= htmlspecialchars((string)($station['name'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"><?php endif; ?>
        <h4><?= htmlspecialchars((string)($station['name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></h4>
        <?php if (!empty($station['description'])): ?><p><?= nl2br(htmlspecialchars((string)$station['description'], ENT_QUOTES, 'UTF-8')) ?></p><?php else: ?><p>Visit one of our broadcast friends and check out what they are playing.</p><?php endif; ?>
        <?php if ($link && $link !== '#'): ?><a href="<?= htmlspecialchars((string)$link, ENT_QUOTES, 'UTF-8') ?>" class="btn btn-dark" target="_blank" rel="noopener">Visit Station</a><?php endif; ?>
      </div></div>
    <?php endforeach; ?>
    <?php if (empty($friends)): ?><div class="col-12"><div class="dj-box">No friends added yet.</div></div><?php endif; ?>
  </div>
</div>
<?php include 'includes/footer.php'; ?>
