<?php

/**
 * HTML-escape output in templates.
 */
function e($string): void
{
    echo htmlspecialchars((string) $string, ENT_QUOTES, 'UTF-8');
}

/**
 * Build a web asset URL relative to the app base URL.
 */
function asset(string $path): string
{
    return \MintyPHP\Router::getBaseUrl() . ltrim($path, '/');
}

/**
 * Build an absolute filesystem path inside templates/.
 */
function templatePath(string $path): string
{
    return dirname(__DIR__, 3) . '/templates/' . ltrim($path, '/');
}

/**
 * Register the app service container for the current request.
 */
function setAppContainer(\MintyPHP\App\AppContainer $container): void
{
    $GLOBALS['minty_app_container'] = $container;

    \MintyPHP\Http\ApiAuth::configure(
        static fn (): \MintyPHP\Service\Tenant\TenantScopeService => $container->get(\MintyPHP\Service\Tenant\TenantScopeService::class),
        static fn (): \MintyPHP\Service\Auth\ApiTokenService => $container->get(\MintyPHP\Service\Auth\ApiTokenService::class),
        static fn (): \MintyPHP\Repository\Access\UserRoleRepository => $container->get(\MintyPHP\Repository\Access\UserRoleRepository::class),
        static fn (): \MintyPHP\Repository\Access\RolePermissionRepository => $container->get(\MintyPHP\Repository\Access\RolePermissionRepository::class),
        static fn (): \MintyPHP\Service\User\UserTenantContextService => $container->get(\MintyPHP\Service\User\UserTenantContextService::class),
        static fn (): \MintyPHP\Service\Access\AuthorizationService => $container->get(\MintyPHP\Service\Access\AuthorizationService::class)
    );

    \MintyPHP\Http\ApiBootstrap::configure(
        static fn (): \MintyPHP\Service\Audit\ApiAuditService => $container->get(\MintyPHP\Service\Audit\ApiAuditService::class),
        static fn (): \MintyPHP\Service\Settings\SettingsApiPolicyGateway => $container->get(\MintyPHP\Service\Settings\SettingsApiPolicyGateway::class),
        static fn (): \MintyPHP\Service\Security\RateLimiterService => $container->get(\MintyPHP\Service\Security\RateLimiterService::class),
        static fn (): \MintyPHP\Http\ApiSystemAuditReporter => $container->get(\MintyPHP\Http\ApiSystemAuditReporter::class)
    );

    \MintyPHP\Http\ApiResponse::configure(
        static fn (): \MintyPHP\Service\Audit\ApiAuditService => $container->get(\MintyPHP\Service\Audit\ApiAuditService::class),
        static fn (): \MintyPHP\Service\Access\AuthorizationService => $container->get(\MintyPHP\Service\Access\AuthorizationService::class),
        static fn (): \MintyPHP\Http\ApiSystemAuditReporter => $container->get(\MintyPHP\Http\ApiSystemAuditReporter::class)
    );

    \MintyPHP\Support\Guard::configure(
        static fn (): \MintyPHP\Service\Auth\AuthService => $container->get(\MintyPHP\Service\Auth\AuthService::class),
        static fn (): \MintyPHP\Service\Tenant\TenantService => $container->get(\MintyPHP\Service\Tenant\TenantService::class),
        static fn (): \MintyPHP\Service\Access\AuthorizationService => $container->get(\MintyPHP\Service\Access\AuthorizationService::class)
    );

    \MintyPHP\Support\Search\SearchItemMapperProvider::configure(
        static fn (): \MintyPHP\Service\User\UserAvatarService => $container->get(\MintyPHP\Service\User\UserAvatarService::class)
    );
}

/**
 * Resolve a service from the app container.
 */
function app(string $id): mixed
{
    $container = $GLOBALS['minty_app_container'] ?? null;
    if (!$container instanceof \MintyPHP\App\AppContainer) {
        throw new \RuntimeException('App container is not initialized');
    }

    return $container->get($id);
}

/**
 * Build an asset URL with filemtime cache-busting when available.
 */
function assetVersion(string $path): string
{
    $path = ltrim($path, '/');
    $file = dirname(__DIR__, 3) . '/web/' . $path;
    $url = asset($path);
    $version = @filemtime($file);
    if ($version === false) {
        return $url;
    }
    return $url . '?v=' . $version;
}

/**
 * Base URL including locale segment (e.g. /de/).
 */
function localeBase(): string
{
    $locale = \MintyPHP\I18n::$locale ?? \MintyPHP\I18n::$defaultLocale;
    $prefix = $locale !== '' ? $locale . '/' : '';
    return \MintyPHP\Router::getBaseUrl() . $prefix;
}

/**
 * Locale-aware URL for app routes.
 */
function lurl(string $path = ''): string
{
    return localeBase() . ltrim($path, '/');
}

/**
 * App title from settings with APP_NAME fallback.
 */
function appTitle(): string
{
    $default = defined('APP_NAME') ? APP_NAME : 'CoreCore';
    $title = appSetting('app_title');
    if ($title !== null) {
        return $title;
    }
    return $default;
}

/**
 * Build an absolute URL using APP_URL or request host fallback.
 */
function appUrl(string $path = ''): string
{
    if ($path !== '' && preg_match('#^https?://#i', $path)) {
        return $path;
    }
    // Prefer configured canonical URL to keep links stable.
    $base = getenv('APP_URL') ?: '';
    $base = rtrim((string) $base, '/');
    if ($base === '') {
        $scheme = 'http';
        $https = $_SERVER['HTTPS'] ?? '';
        $forwarded = $_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '';
        if ($https === 'on' || $https === '1' || $forwarded === 'https') {
            $scheme = 'https';
        }
        $host = $_SERVER['HTTP_HOST'] ?? '';
        if ($host !== '') {
            $base = $scheme . '://' . $host;
        }
    }
    if ($base === '') {
        return \MintyPHP\Router::getBaseUrl() . ltrim((string) $path, '/');
    }
    $path = ltrim((string) $path, '/');
    return $base . '/' . $path;
}

/**
 * Human-readable current user name fallback: first+last -> email.
 */
function currentUserDisplayName(): string
{
    $user = $_SESSION['user'] ?? [];
    $name = trim((string) (($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '')));
    if ($name !== '') {
        return $name;
    }
    return trim((string) ($user['email'] ?? ''));
}

/**
 * Absolute logo URL (used in e-mails and metadata).
 */
function appLogoUrlAbsolute(int $size = 128): string
{
    $url = appLogoUrl($size);
    return appUrl($url);
}

/**
 * Read one cached app setting from config/settings.php.
 */
function appSetting(string $key): ?string
{
    if (!class_exists('MintyPHP\\Service\\Settings\\SettingCacheService')) {
        return null;
    }

    return app(\MintyPHP\Service\Settings\SettingCacheService::class)->get($key);
}

/**
 * Load configured themes with a safe fallback list.
 */
function appThemes(): array
{
    if (!class_exists('MintyPHP\\Service\\Settings\\ThemeConfigGateway')) {
        return [
            'light' => 'Light',
            'dark' => 'Dark',
        ];
    }

    return app(\MintyPHP\Service\Settings\ThemeConfigGateway::class)->all();
}

/**
 * Resolve default locale only if it exists in APP_LOCALES.
 */
function appDefaultLocale(): ?string
{
    $locale = appSetting('app_locale');
    if ($locale === null) {
        return null;
    }
    $available = defined('APP_LOCALES') ? APP_LOCALES : [];
    if ($available && !in_array($locale, $available, true)) {
        return null;
    }
    return $locale;
}

/**
 * Resolve default theme from settings, then APP_THEME, then light.
 */
function appDefaultTheme(): string
{
    $themes = appThemes();
    $tenantTheme = strtolower(trim((string) ($_SESSION['current_tenant']['default_theme'] ?? '')));
    if ($tenantTheme !== '' && isset($themes[$tenantTheme])) {
        return $tenantTheme;
    }
    $setting = appSetting('app_theme');
    if ($setting !== null && isset($themes[$setting])) {
        return $setting;
    }
    $envTheme = getenv('APP_THEME') ?: 'light';
    $envTheme = strtolower(trim((string) $envTheme));
    return isset($themes[$envTheme]) ? $envTheme : 'light';
}

/**
 * Resolve effective theme with optional per-user override.
 */
function currentTheme(): string
{
    $themes = appThemes();
    $theme = appDefaultTheme();
    if (!allowUserTheme()) {
        return $theme;
    }
    $user = $_SESSION['user'] ?? [];
    $userTheme = strtolower(trim((string) ($user['theme'] ?? '')));
    if ($userTheme !== '' && isset($themes[$userTheme])) {
        return $userTheme;
    }
    return $theme;
}

/**
 * Feature flag: allow users to choose their own theme.
 */
function allowUserTheme(): bool
{
    $tenantValue = $_SESSION['current_tenant']['allow_user_theme'] ?? null;
    if ($tenantValue !== null && $tenantValue !== '') {
        $tenantValue = strtolower(trim((string) $tenantValue));
        if (in_array($tenantValue, ['1', 'true', 'yes', 'on'], true)) {
            return true;
        }
        if (in_array($tenantValue, ['0', 'false', 'no', 'off'], true)) {
            return false;
        }
    }

    $value = appSetting('app_theme_user');
    if ($value === null || $value === '') {
        return true;
    }
    return in_array(strtolower($value), ['1', 'true', 'yes', 'on'], true);
}

/**
 * Feature flag: allow public self-registration.
 */
function allowRegistration(): bool
{
    $value = appSetting('app_registration');
    if ($value === null || $value === '') {
        return true;
    }
    return in_array(strtolower($value), ['1', 'true', 'yes', 'on'], true);
}

/**
 * Feature flag: allow frontend telemetry events.
 */
function frontendTelemetryEnabled(): bool
{
    $value = appSetting('frontend_telemetry_enabled');
    if ($value === null || $value === '') {
        return false;
    }
    return in_array(strtolower(trim($value)), ['1', 'true', 'yes', 'on'], true);
}

/**
 * Frontend telemetry sample rate normalized to 0..1.
 */
function frontendTelemetrySampleRate(): float
{
    $value = appSetting('frontend_telemetry_sample_rate');
    if ($value === null || trim($value) === '') {
        return 0.2;
    }

    $rate = is_numeric($value) ? (float) $value : NAN;
    if (!is_finite($rate) || $rate < 0 || $rate > 1) {
        return 0.2;
    }

    return $rate;
}

/**
 * Allowed frontend telemetry events as canonical short keys.
 *
 * @return list<string>
 */
function frontendTelemetryAllowedEvents(): array
{
    $allowed = ['warn_once', 'ajax_error'];
    $value = appSetting('frontend_telemetry_allowed_events');
    if ($value === null || trim($value) === '') {
        return $allowed;
    }

    $items = preg_split('/[\s,]+/', strtolower(trim($value))) ?: [];
    $normalized = array_values(array_unique(array_filter(
        array_map(
            static fn ($entry): string => trim((string) $entry),
            $items
        ),
        static fn ($entry): bool => in_array($entry, $allowed, true)
    )));

    if ($normalized === []) {
        return $allowed;
    }

    sort($normalized, SORT_STRING);
    return $normalized;
}

/**
 * Resolve active primary color (tenant override -> app setting).
 */
function appPrimaryColor(): ?string
{
    // Tenant-scoped branding has precedence over global settings.
    $tenantColor = $_SESSION['current_tenant']['primary_color'] ?? null;
    if ($tenantColor !== null) {
        $tenantColor = strtolower(trim((string) $tenantColor));
        if (preg_match('/^#([0-9a-f]{3}|[0-9a-f]{6})$/i', $tenantColor)) {
            return $tenantColor;
        }
    }

    $value = appSetting('app_primary_color');
    if ($value === null) {
        return null;
    }
    $value = strtolower(trim($value));
    if (!preg_match('/^#([0-9a-f]{3}|[0-9a-f]{6})$/i', $value)) {
        return null;
    }
    return $value;
}

/**
 * Convert current hex color to CSS HSL custom properties.
 */
function appPrimaryCssVars(): string
{
    $hex = appPrimaryColor();
    if ($hex === null) {
        return '';
    }
    $hex = ltrim($hex, '#');
    if (strlen($hex) === 3) {
        $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
    }
    $r = hexdec(substr($hex, 0, 2)) / 255;
    $g = hexdec(substr($hex, 2, 2)) / 255;
    $b = hexdec(substr($hex, 4, 2)) / 255;

    // Short-circuit grayscale values to avoid unstable hue math.
    $monoThreshold = 0.000001;
    if (abs($r - $g) < $monoThreshold && abs($g - $b) < $monoThreshold) {
        $l = round($r * 100, 2) . '%';
        return "--app-primary-h-base: 0; --app-primary-s-base: 0%; --app-primary-l-base: {$l}; --app-primary-h-light: 0; --app-primary-s-light: 0%; --app-primary-l-light: {$l};";
    }

    $max = max($r, $g, $b);
    $min = min($r, $g, $b);
    $delta = $max - $min;

    if ($delta === 0.0) {
        $l = round((($max + $min) / 2) * 100, 2) . '%';
        return "--app-primary-h-base: 0; --app-primary-s-base: 0%; --app-primary-l-base: {$l}; --app-primary-h-light: 0; --app-primary-s-light: 0%; --app-primary-l-light: {$l};";
    }

    $h = 0.0;
    if ($max === $r) {
        $h = 60 * fmod((($g - $b) / $delta), 6);
    } elseif ($max === $g) {
        $h = 60 * ((($b - $r) / $delta) + 2);
    } else {
        $h = 60 * ((($r - $g) / $delta) + 4);
    }
    if ($h < 0) {
        $h += 360;
    }

    $l = ($max + $min) / 2;
    $denominator = 1 - abs(2 * $l - 1);
    if ($delta === 0.0 || $denominator === 0.0) {
        $s = 0.0;
    } else {
        $s = $delta / $denominator;
    }

    $h = round($h, 2);
    $s = round($s * 100, 2) . '%';
    $l = round($l * 100, 2) . '%';

    return "--app-primary-h-base: {$h}; --app-primary-s-base: {$s}; --app-primary-l-base: {$l}; --app-primary-h-light: {$h}; --app-primary-s-light: {$s}; --app-primary-l-light: {$l};";
}

/**
 * Resolve app logo path (custom upload with fallback asset).
 */
function appLogoUrl(?int $size = null): string
{
    if (class_exists('MintyPHP\\Service\\Branding\\BrandingLogoService')) {
        $logoService = app(\MintyPHP\Service\Branding\BrandingLogoService::class);
        if ($logoService->hasLogo()) {
            $query = $size ? '?size=' . (int) $size : '';
            return lurl('branding/logo' . $query);
        }
    }
    return asset('brand/logo.svg');
}

/**
 * Resolve logo for auth pages: tenant avatar → global logo → default SVG.
 *
 * After logout the tenant context (`$_SESSION['current_tenant']`) is preserved,
 * so the login page can show the tenant avatar instead of the generic app logo.
 */
function appAuthLogoUrl(?int $size = null): string
{
    $tenantUuid = $_SESSION['current_tenant']['uuid'] ?? '';
    if ($tenantUuid !== '' && class_exists('MintyPHP\\Service\\Tenant\\TenantAvatarService')) {
        if (app(\MintyPHP\Service\Tenant\TenantAvatarService::class)->hasAvatar($tenantUuid)) {
            $query = $size ? '&size=' . (int) $size : '';
            return lurl('auth/tenant-avatar-file?uuid=' . rawurlencode($tenantUuid) . $query);
        }
    }
    return appLogoUrl($size);
}

/**
 * Resolve favicon path (tenant favicon with global fallback).
 */
function appFaviconUrl(string $file): string
{
    $tenantUuid = $_SESSION['current_tenant']['uuid'] ?? '';
    if ($tenantUuid !== '' && class_exists('MintyPHP\\Service\\Tenant\\TenantFaviconService')) {
        if (app(\MintyPHP\Service\Tenant\TenantFaviconService::class)->hasFavicon($tenantUuid)) {
            return asset('favicon/tenants/' . $tenantUuid . '/favicon/' . ltrim($file, '/'));
        }
    }
    return asset('favicon/' . ltrim($file, '/'));
}

/**
 * Sort array items by 'description' case-insensitively.
 */
function sortByDescription(array &$items): void
{
    usort(
        $items,
        static fn ($a, $b) =>
        strcasecmp((string) ($a['description'] ?? ''), (string) ($b['description'] ?? ''))
    );
}

/**
 * Decide whether any admin panel capability is available in layout auth.
 *
 * @param array<string, mixed> $layoutAuth
 */
function layoutHasAdminPanel(array $layoutAuth): bool
{
    $capabilityKeys = array_keys(\MintyPHP\Service\Access\UiCapabilityMap::LAYOUT);
    foreach ($capabilityKeys as $key) {
        if ($key === 'can_view_address_book') {
            continue;
        }
        if (!empty($layoutAuth[$key])) {
            return true;
        }
    }

    return false;
}

/**
 * Normalize list-like input to sorted unique non-empty strings.
 *
 * @return list<string>
 */
function appNormalizeStringList(mixed $value): array
{
    $raw = is_array($value) ? $value : explode(',', (string) $value);
    $list = array_filter(array_map('trim', $raw), static fn ($item) => $item !== '');
    $list = array_values(array_unique($list));
    sort($list, SORT_STRING);
    return $list;
}

/**
 * Normalize list-like input to sorted unique positive integers.
 *
 * @return list<int>
 */
function appNormalizePositiveIntList(mixed $value): array
{
    $raw = is_array($value) ? $value : explode(',', (string) $value);
    $list = array_values(array_unique(array_map('intval', $raw)));
    $list = array_values(array_filter($list, static fn ($item) => $item > 0));
    sort($list, SORT_NUMERIC);
    return $list;
}

/**
 * Normalize address-book custom field query keys/values.
 *
 * @param array<string, mixed> $rawQuery
 * @return array<string, string|list<int>>
 */
function appNormalizeAddressBookCustomFilterQuery(array $rawQuery): array
{
    $normalized = [];
    foreach ($rawQuery as $rawKey => $rawValue) {
        $key = strtolower(trim((string) $rawKey));
        if ($key === '') {
            continue;
        }
        if (preg_match('/^cf_[a-f0-9-]{36}$/', $key)) {
            $value = trim((string) $rawValue);
            if ($value !== '') {
                $normalized[$key] = $value;
            }
            continue;
        }
        if (preg_match('/^cfm_[a-f0-9-]{36}$/', $key)) {
            $ids = appNormalizePositiveIntList($rawValue);
            if ($ids) {
                $normalized[$key] = $ids;
            }
            continue;
        }
        if (preg_match('/^cfd_[a-f0-9-]{36}_(from|to)$/', $key)) {
            $value = trim((string) $rawValue);
            $dt = \DateTimeImmutable::createFromFormat('Y-m-d', $value);
            if ($dt && $dt->format('Y-m-d') === $value) {
                $normalized[$key] = $value;
            }
        }
    }
    ksort($normalized, SORT_STRING);
    return $normalized;
}

/**
 * Build precomputed layout navigation context for templates.
 *
 * @param array<string, mixed> $layoutAuth
 * @param array<string, mixed> $session
 * @param array<string, mixed> $query
 * @return array<string, mixed>
 */
function appBuildLayoutNavContext(array $layoutAuth, array $session, array $query): array
{
    $currentTenant = is_array($session['current_tenant'] ?? null) ? $session['current_tenant'] : null;
    $availableTenants = is_array($session['available_tenants'] ?? null) ? $session['available_tenants'] : [];
    $tenantUuid = trim((string) ($currentTenant['uuid'] ?? ''));
    $tenantName = trim((string) ($currentTenant['description'] ?? ''));

    $tenantQueryParam = '';
    if (count($availableTenants) > 1 && $tenantUuid !== '') {
        $tenantQueryParam = '?tenant=' . urlencode($tenantUuid);
    }

    $tenantHasAvatar = false;
    if ($tenantUuid !== '' && class_exists(\MintyPHP\Service\Tenant\TenantAvatarService::class)) {
        $tenantHasAvatar = app(\MintyPHP\Service\Tenant\TenantAvatarService::class)->hasAvatar($tenantUuid);
    }

    $csrfKey = \MintyPHP\Session::$csrfSessionKey;
    $csrfToken = (string) ($session[$csrfKey] ?? '');

    return [
        'hasAdminPanel' => layoutHasAdminPanel($layoutAuth),
        'currentTenant' => $currentTenant,
        'availableTenants' => $availableTenants,
        'tenantQueryParam' => $tenantQueryParam,
        'tenantAvatar' => [
            'uuid' => $tenantUuid,
            'name' => $tenantName,
            'hasAvatar' => $tenantHasAvatar,
        ],
        'addressBook' => [
            'url' => lurl('address-book'),
            'activeSearch' => trim((string) ($query['search'] ?? '')),
            'activeTenants' => appNormalizeStringList($query['tenants'] ?? ''),
            'activeDepartments' => appNormalizePositiveIntList($query['departments'] ?? ''),
            'activeRoles' => appNormalizePositiveIntList($query['roles'] ?? ''),
            'activeCustomFilters' => appNormalizeAddressBookCustomFilterQuery($query),
            'peopleGroups' => is_array($session['available_departments_by_tenant'] ?? null) ? $session['available_departments_by_tenant'] : [],
            'savedFilters' => is_array($session['address_book_saved_filters'] ?? null) ? $session['address_book_saved_filters'] : [],
        ],
        'csrfKey' => $csrfKey,
        'csrfToken' => $csrfToken,
    ];
}
