<?php
// admin/app_assets.php
// Central registry for public CSS/JS assets and external vendor URLs.
// Keeps asset sources in one place so pages do not hard-code CDN/local paths.

if (!function_exists('ua_asset_prefer_local')) {
  function ua_asset_prefer_local(string $localPath, string $remoteUrl): string {
    $localPath = ltrim($localPath, '/');
    if ($localPath !== '' && is_file(__DIR__ . '/' . $localPath)) {
      return $localPath;
    }
    return ua_asset_remote_allowed() ? $remoteUrl : '';
  }
}

if (!function_exists('ua_asset_remote_allowed')) {
  function ua_asset_remote_allowed(): bool {
    $flag = strtolower(trim((string)($_ENV['UA_ALLOW_REMOTE_ASSETS'] ?? '')));
    if (in_array($flag, ['1', 'true', 'yes', 'on'], true)) return true;
    if (defined('UA_ALLOW_REMOTE_ASSETS') && UA_ALLOW_REMOTE_ASSETS) return true;

    $host = strtolower((string)($_SERVER['HTTP_HOST'] ?? ''));
    $host = preg_replace('/:\d+$/', '', $host);
    if ($host === '' || $host === 'localhost' || $host === '127.0.0.1' || $host === '::1') {
      return false;
    }
    return PHP_SAPI !== 'cli';
  }
}

if (!function_exists('ua_asset_registry')) {
  function ua_asset_registry(): array {
    static $registry = null;
    if ($registry !== null) return $registry;

    $localQr = is_file(__DIR__ . '/assets/vendor/qrcode/qrcode.min.js') ? 'assets/vendor/qrcode/qrcode.min.js' : 'assets/js/qr_local.min.js';
    $registry = [
      'bootstrap_533_rtl_css' => [
        'type' => 'css',
        'href' => ua_asset_prefer_local('assets/vendor/bootstrap/5.3.3/bootstrap.rtl.min.css', 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.rtl.min.css'),
      ],
      'fontawesome_470_css' => [
        'type' => 'css',
        'href' => ua_asset_prefer_local('assets/vendor/fontawesome/4.7.0/css/font-awesome.min.css', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css'),
      ],
      'bootstrap_462_css' => [
        'type' => 'css',
        'href' => ua_asset_prefer_local('assets/vendor/bootstrap/4.6.2/bootstrap.min.css', 'https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css'),
      ],
      'bootstrap_533_bundle_js' => [
        'type' => 'js',
        'src' => ua_asset_prefer_local('assets/vendor/bootstrap/5.3.3/bootstrap.bundle.min.js', 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js'),
      ],
      'qrcode_js' => [
        'type' => 'js',
        'src' => is_file(__DIR__ . '/' . $localQr)
          ? $localQr
          : 'https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js',
      ],
    ];
    return $registry;
  }
}

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

if (!function_exists('ua_asset_url')) {
  function ua_asset_url(string $key): string {
    $entry = ua_asset_entry($key);
    if (!$entry) return '';
    return (string)($entry['href'] ?? $entry['src'] ?? '');
  }
}

if (!function_exists('ua_asset_versioned_local')) {
  function ua_asset_versioned_local(string $path): string {
    if ($path === '' || preg_match('~^https?://~i', $path)) return $path;
    $abs = __DIR__ . '/' . ltrim($path, '/');
    $v = is_file($abs) ? (int)@filemtime($abs) : 1;
    return $path . (strpos($path, '?') === false ? '?v=' : '&v=') . $v;
  }
}

if (!function_exists('ua_asset_tag_css')) {
  function ua_asset_tag_css(string $key): string {
    $href = ua_asset_url($key);
    if ($href === '') return '';
    $href = ua_asset_versioned_local($href);
    return '<link rel="stylesheet" href="' . htmlspecialchars($href, ENT_QUOTES, 'UTF-8') . '">';
  }
}

if (!function_exists('ua_asset_tag_js')) {
  function ua_asset_tag_js(string $key): string {
    $src = ua_asset_url($key);
    if ($src === '') return '';
    $src = ua_asset_versioned_local($src);
    return '<script src="' . htmlspecialchars($src, ENT_QUOTES, 'UTF-8') . '"></script>';
  }
}



if (!function_exists('ua_local_css_registry')) {
  function ua_local_css_registry(): array {
    return [
      'shell' => [
        'assets/css/ua_modern.css',
        'assets/css/ua_sidebar3.css',
        'assets/css/ua_app_shell_contract.css',
        'assets/css/ua_global_feedback.css',
        'assets/css/ua_subnav.css',
        'assets/css/ua_design_tokens.css',
        'assets/css/ua_design_system.css',
        'assets/css/ua_design_components.css',
        'assets/css/ua_number_wheel.css',
      ],
      'login' => [
        'assets/css/exanet_login.css',
      ],
    ];
  }
}

if (!function_exists('ua_local_css_list')) {
  function ua_local_css_list(string $group): array {
    $registry = ua_local_css_registry();
    return array_values(array_filter($registry[$group] ?? [], 'is_string'));
  }
}

if (!function_exists('ua_local_css_tags')) {
  function ua_local_css_tags(string $group): string {
    $tags = [];
    foreach (ua_local_css_list($group) as $path) {
      $href = ua_asset_versioned_local($path);
      $tags[] = '<link rel="stylesheet" href="' . htmlspecialchars($href, ENT_QUOTES, 'UTF-8') . '">';
    }
    return implode("\n  ", $tags);
  }
}

/* Component styles that used to be emitted by body partials.
   Register them in the document head so the canonical theme layer always follows them. */
if (!function_exists('ua_page_component_css')) {
  function ua_page_component_css(string $page): array {
    $groups = [
      'section_tabs' => [
        'automation_billing.php','automation_vouchers.php','automation_reports.php','automation_maintenance.php',
        'messages_outbox.php','messages_campaigns.php','message_log.php','messages_templates.php','device_admin_alerts.php','settings_sms.php','settings_whatsapp.php',
        'wizard_network.php','automation_comms.php','routers.php','sectors.php','subscribers_distribution.php',
        'sales.php','sales_new.php','sales_products.php','sales_history.php','sales_summary.php',
        'subscribers.php','subscribers_add.php',
      ],
      'messages' => ['messages_outbox.php','messages_campaigns.php','message_log.php','messages_templates.php','device_admin_alerts.php','settings_sms.php','settings_whatsapp.php'],
      'finance' => [
        'billing_requests_page.php','finance_cashbox.php','finance_expenses.php','finance_day_report.php','finance_partners.php',
        'finance_daily_balances.php','finance_month_report.php','finance_month_close.php','finance_reports.php','finance_payments.php',
        'invoices.php','invoices_add.php','invoices_generate_month.php','purchases_view.php','purchases_report.php','purchases_new.php',
      ],
      'agents' => ['agents.php','agents_balances.php','agents_activity.php','agents_portal_preview.php','agent_transactions.php'],
      'automation_pages' => ['automation_log.php','automation_comms.php','automation_commands.php'],
      'finance_reports' => ['finance_day_report.php','finance_month_report.php'],
      'settings_pages' => ['settings_mikrotik.php'],
      'subscriber_modal' => ['subscribers.php','subscribers_view.php'],
    ];
    $assets = [];
    if (in_array($page, $groups['section_tabs'], true)) $assets[] = 'assets/css/ua_section_tabs.css';
    if (in_array($page, $groups['messages'], true)) $assets[] = 'assets/css/messages_system.css';
    if (in_array($page, $groups['finance'], true)) $assets[] = 'assets/css/ua_finance_nav.css';
    if (in_array($page, $groups['agents'], true)) $assets[] = 'assets/css/ua_agents_module.css';
    if ($page === 'agents_portal_preview.php') $assets[] = 'assets/css/ua_agent_portal.css';
    if (in_array($page, $groups['automation_pages'], true)) $assets[] = 'assets/css/ua_automation_pages.css';
    if (in_array($page, $groups['finance_reports'], true)) $assets[] = 'assets/css/ua_finance_reports.css';
    if (in_array($page, $groups['settings_pages'], true)) $assets[] = 'assets/css/ua_settings_pages.css';
    if (in_array($page, $groups['subscriber_modal'], true)) $assets[] = 'assets/css/ua_subscribers_modal.css';
    return array_values(array_unique($assets));
  }
}


if (!function_exists('ua_asset_vendor_status')) {
  function ua_asset_vendor_status(): array {
    $status = [];
    foreach (ua_asset_registry() as $key => $entry) {
      $url = (string)($entry['href'] ?? $entry['src'] ?? '');
      $isRemote = (bool)preg_match('~^https?://~i', $url);
      $status[$key] = [
        'type' => (string)($entry['type'] ?? ''),
        'url' => $url,
        'source' => $isRemote ? 'remote_fallback' : 'local',
      ];
    }
    return $status;
  }
}

if (!function_exists('ua_asset_external_origins')) {
  function ua_asset_external_origins(string $type = ''): array {
    $origins = [];
    foreach (ua_asset_registry() as $entry) {
      if ($type !== '' && (string)($entry['type'] ?? '') !== $type) continue;
      $url = (string)($entry['href'] ?? $entry['src'] ?? '');
      if (!preg_match('~^https?://~i', $url)) continue;
      $parts = parse_url($url);
      if (!$parts || empty($parts['scheme']) || empty($parts['host'])) continue;
      $origins[] = strtolower($parts['scheme'] . '://' . $parts['host']);
    }
    return array_values(array_unique($origins));
  }
}
