<?php
function ugfx_path(string $relative): string { return __DIR__ . '/../' . ltrim($relative, '/'); }
function ugfx_load_json(string $relative, $fallback = []) {
  $path = ugfx_path($relative);
  if (!is_file($path)) return $fallback;
  $data = json_decode((string)file_get_contents($path), true);
  return is_array($data) ? $data : $fallback;
}
function ugfx_load_folder_records(string $relativeFolder): array {
  $folder = ugfx_path($relativeFolder);
  if (!is_dir($folder)) return [];
  $records = [];
  foreach (glob($folder.'/*.json') as $file) {
    $data = json_decode((string)file_get_contents($file), true);
    if (is_array($data)) $records[] = $data;
  }
  return $records;
}
function ugfx_settings(): array {
  static $settings = null;
  if ($settings !== null) return $settings;
  $settings = ugfx_load_json('data/settings.json', []);
  $settings += [
    'site_name' => 'Underground FX Radio',
    'station_tagline' => 'Live community radio with real radio-jockey personality, bigger studio energy, and stronger listener connection.',
    'stream_url' => 'http://radio.undergroundfxradio.com:9000/stream',
    'discord_url' => 'https://discord.gg/hA2uWMpCT8',
    'station_timezone' => 'America/New_York',
    'listen_links' => [
      ['label' => 'MyTuner', 'url' => 'https://mytuner-radio.com/radio/underground-fx-radio'],
      ['label' => 'RadioBox', 'url' => 'https://onlineradiobox.com/'],
      ['label' => 'US-RADIO', 'url' => 'https://us-radio.com/'],
      ['label' => 'RadioSpinner', 'url' => 'https://radiospinner.com/'],
    ],
  ];
  return $settings;
}
function ugfx_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;
  if (!is_file(ugfx_path($path)) && $fallbackDir !== '' && is_file(ugfx_path(trim($fallbackDir, '/') . '/' . basename($path)))) {
    $path = trim($fallbackDir, '/') . '/' . basename($path);
  }
  return $path;
}
function ugfx_djs(): array {
  $rows = ugfx_load_json('data/djs.json', []);
  return array_values(array_filter(is_array($rows)?$rows:[], fn($row)=>!isset($row['active'])||$row['active']));
}
function ugfx_should_skip_copy(array $item): bool {
  $blob = strtolower(trim((string)(($item['title'] ?? '') . ' ' . ($item['summary'] ?? '') . ' ' . ($item['body'] ?? '') . ' ' . ($item['content'] ?? ''))));
  if ($blob === '') return true;
  if (str_contains($blob, 'home time radio') || str_contains($blob, 'hometime radio') || str_contains($blob, 'smurfette')) return true;
  return false;
}
function ugfx_news(): array {
  $news = [];
  foreach (array_merge(ugfx_load_json('data/news.json', []), ugfx_load_folder_records('data/news')) as $item) {
    if (!is_array($item) || trim((string)($item['title'] ?? ''))==='') continue;
    if (ugfx_should_skip_copy($item)) continue;
    $slug = strtolower(preg_replace('/[^a-z0-9]+/i', '-', (string)$item['title']));
    $imageRaw = (string)($item['image'] ?? $item['image_path'] ?? '');
    $tagRaw = (string)($item['tag'] ?? '');
    if ($imageRaw === '' && preg_match('#\.(png|jpe?g|gif|webp)$#i', $tagRaw)) {
      $imageRaw = $tagRaw;
      $tagRaw = 'Station News';
    }
    $summary = trim((string)($item['summary'] ?? $item['body'] ?? $item['content'] ?? ''));
    $body = trim((string)($item['body'] ?? $item['content'] ?? $item['summary'] ?? ''));
    $news[$slug] = [
      'title'=>(string)$item['title'],
      'summary'=>$summary,
      'body'=>$body,
      'date'=>(string)($item['date'] ?? $item['created_at'] ?? 'On Air'),
      'tag'=>$tagRaw !== '' ? $tagRaw : 'Station News',
      'image'=>ugfx_asset_url($imageRaw !== '' ? $imageRaw : 'img/content/undergroundfx-event-poster.png', 'img/content'),
      'featured'=>!empty($item['featured']) || !empty($item['featured_home']),
    ];
  }
  usort($news, fn($a,$b)=>strcmp((string)($b['date']??''), (string)($a['date']??'')));
  return array_values($news);
}
function ugfx_events(): array {
  $events = [];
  foreach (array_merge(ugfx_load_json('data/events.json', []), ugfx_load_folder_records('data/events')) as $item) {
    if (!is_array($item) || trim((string)($item['title'] ?? ''))==='') continue;
    if (ugfx_should_skip_copy($item)) continue;
    $slug = strtolower(preg_replace('/[^a-z0-9]+/i', '-', (string)$item['title']));
    $events[$slug] = [
      'title'=>(string)$item['title'],
      'description'=>trim((string)($item['description'] ?? $item['body'] ?? $item['content'] ?? '')),
      'start'=>(string)($item['start'] ?? $item['date'] ?? 'Coming Soon'),
      'location'=>(string)($item['location'] ?? 'Underground FX Radio'),
      'image'=>ugfx_asset_url((string)($item['image'] ?? $item['image_path'] ?? 'img/content/undergroundfx-event-poster.png'), 'img/content'),
      'featured'=>!empty($item['featured']) || !empty($item['featured_home']),
    ];
  }
  usort($events, fn($a,$b)=>strcmp((string)($a['start']??''), (string)($b['start']??'')));
  return array_values($events);
}
function ugfx_schedule(): array {
  $x = ugfx_load_json('data/schedule.json', []);
  return is_array($x) ? $x : [];
}
function ugfx_friends(): array { $x=ugfx_load_json('data/friends.json', []); if(!$x) $x=ugfx_load_json('friends-data.json', []); return is_array($x)?$x:[]; }
function ugfx_fans(): array { $x=ugfx_load_json('data/fans.json', []); return is_array($x)?$x:[]; }
function ugfx_featured_news(int $count=3): array {
  $rows = array_values(array_filter(ugfx_news(), fn($n)=>!empty($n['featured'])));
  if (!$rows) $rows = ugfx_news();
  return array_slice($rows,0,$count);
}
function ugfx_featured_events(int $count=3): array {
  $rows = array_values(array_filter(ugfx_events(), fn($e)=>!empty($e['featured'])));
  if (!$rows) $rows = ugfx_events();
  return array_slice($rows,0,$count);
}
function ugfx_current_show(): array {
  $schedule = ugfx_schedule();
  $tz = new DateTimeZone(ugfx_settings()['station_timezone'] ?? 'America/New_York');
  $now = new DateTime('now',$tz);
  $days=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
  $day=$days[(int)$now->format('w')];
  $hour=(int)$now->format('G');
  $slots=$schedule[$day] ?? [];
  return ['day'=>$day,'hour'=>$hour,'current'=>$slots[$hour] ?? 'Underground FX AutoMix','next'=>$slots[($hour+1)%24] ?? 'Underground FX AutoMix'];
}
function ugfx_nowplaying_text(): string {
  foreach ([ugfx_path('data/nowplaying.txt'), ugfx_path('last-track.txt'), ugfx_path('data/nowplaying.php')] as $path) {
    if (is_file($path)) {
      $raw=trim(strip_tags((string)file_get_contents($path)));
      if ($raw!=='' && !str_contains(strtolower($raw), 'loading')) return $raw;
    }
  }
  return 'Underground FX is live on air right now.';
}
function ugfx_top_tracks(int $count=10): array { $rows=ugfx_load_json('data/top50.json', []); return array_slice(is_array($rows)?$rows:[] ,0,$count); }
?>
