<?php
// admin/media_assets_lib.php
// Central registry for local media files used by UI pages.
// Keep one canonical media source and expose legacy duplicate candidates only if they still exist.

if (!function_exists('ua_media_registry')) {
  function ua_media_registry(): array {
    return [
      'sidebar_program_logo' => [
        'type' => 'image/png',
        'path' => 'assets/img/sidebar_program_logo.png',
      ],
    ];
  }
}

if (!function_exists('ua_media_entry')) {
  function ua_media_entry(string $key): ?array {
    $registry = ua_media_registry();
    return $registry[$key] ?? null;
  }
}

if (!function_exists('ua_media_abs_path')) {
  function ua_media_abs_path(string $path): string {
    return __DIR__ . '/' . ltrim($path, '/');
  }
}

if (!function_exists('ua_media_path')) {
  function ua_media_path(string $key, string $fallback = ''): string {
    $entry = ua_media_entry($key);
    $path = (string)($entry['path'] ?? '');
    if ($path !== '' && is_file(ua_media_abs_path($path))) return $path;
    return $fallback;
  }
}

if (!function_exists('ua_media_url')) {
  function ua_media_url(string $key, string $fallback = '', bool $version = true): string {
    $path = ua_media_path($key, $fallback);
    if ($path === '' || preg_match('~^https?://~i', $path)) return $path;
    if (!$version) return $path;
    $abs = ua_media_abs_path($path);
    $v = is_file($abs) ? (int)@filemtime($abs) : 1;
    return $path . (strpos($path, '?') === false ? '?v=' : '&v=') . $v;
  }
}

if (!function_exists('ua_media_type')) {
  function ua_media_type(string $key, string $fallback = ''): string {
    $entry = ua_media_entry($key);
    $type = (string)($entry['type'] ?? '');
    return $type !== '' ? $type : $fallback;
  }
}

if (!function_exists('ua_media_cleanup_candidates')) {
  function ua_media_cleanup_candidates(): array {
    return [];
  }
}

if (!function_exists('ua_media_existing_cleanup_candidates')) {
  function ua_media_existing_cleanup_candidates(): array {
    $out = [];
    foreach (ua_media_cleanup_candidates() as $path) {
      if (is_file(ua_media_abs_path($path))) $out[] = $path;
    }
    return $out;
  }
}
