<?php
if (!function_exists('ah_media_src')) {
  function ah_media_src(string $path, string $defaultDir = 'img/content'): string {
    $path = trim(str_replace('\\', '/', $path));
    if ($path === '') return '';
    if (preg_match('~^(https?:)?//~i', $path) || strpos($path, 'data:') === 0) return $path;
    $path = preg_replace('~^(\./)+~', '', $path);
    if ($path !== '' && $path[0] === '/') return $path;
    if (preg_match('~^(img|images|uploads|assets)/~i', $path)) return '/' . ltrim($path, '/');
    $defaultDir = trim(str_replace('\\', '/', $defaultDir), '/');
    return '/' . ($defaultDir !== '' ? $defaultDir . '/' : '') . ltrim($path, '/');
  }
}

if (!function_exists('ah_excerpt')) {
  function ah_excerpt(string $text, int $width, string $trimMarker = '…'): string {
    $text = trim(preg_replace('/\s+/', ' ', str_replace(["\r\n", "\r"], "\n", $text)));
    if ($text === '' || $width <= 0) return '';
    if (function_exists('mb_strimwidth')) {
      return mb_strimwidth($text, 0, $width, $trimMarker, 'UTF-8');
    }
    if (strlen($text) <= $width) return $text;
    $cut = max(0, $width - strlen($trimMarker));
    return rtrim(substr($text, 0, $cut)) . $trimMarker;
  }
}

if (!function_exists('ah_load_featured_news')) {
  function ah_load_featured_news(string $rootDir): array {
    $newsDir = rtrim($rootDir, '/') . '/data/news/';
    if (is_dir($newsDir)) {
      $files = glob($newsDir . '*.json') ?: [];
      rsort($files);
      foreach ($files as $file) {
        $row = json_decode((string)file_get_contents($file), true);
        if (!is_array($row) || empty($row['published']) || empty($row['featured_home'])) continue;
        return [
          'title' => trim((string)($row['title'] ?? 'Featured News')),
          'body' => trim((string)($row['content'] ?? '')),
          'image' => ah_media_src((string)($row['image'] ?? ''), 'img/content'),
          'author' => trim((string)($row['author'] ?? '')),
          'date' => trim((string)($row['date'] ?? '')),
          'tag' => trim((string)($row['tag'] ?? '')),
        ];
      }
    }

    $legacy = rtrim($rootDir, '/') . '/data/news.txt';
    $fallback = ['title' => 'Latest station news', 'body' => 'Fresh station updates will appear here when news is posted.', 'image' => '', 'author' => '', 'date' => '', 'tag' => ''];
    if (file_exists($legacy)) {
      $raw = trim((string)file_get_contents($legacy));
      if ($raw !== '') {
        $chunks = preg_split('/
\s*---\s*
/', $raw);
        foreach ($chunks as $chunk) {
          $chunk = trim($chunk);
          if ($chunk === '') continue;
          $lines = preg_split('/\R+/', $chunk);
          $fallback['title'] = trim(strip_tags($lines[0] ?? 'Station Update'));
          $fallback['body'] = trim(strip_tags(implode(' ', array_slice($lines, 1))));
          if ($fallback['body'] !== '' || $fallback['title'] !== '') break;
        }
      }
    }
    return $fallback;
  }
}
