<?php

declare(strict_types=1);

use App\Core\Config;

/**
 * Fonctions utilitaires globales.
 */

if (!function_exists('config')) {
    function config(string $key, mixed $default = null): mixed
    {
        return Config::get($key, $default);
    }
}

if (!function_exists('e')) {
    /** Échappement HTML systématique des sorties. */
    function e(mixed $value): string
    {
        return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

if (!function_exists('base_url')) {
    function base_url(string $path = ''): string
    {
        $base = rtrim((string) config('app.base_url', '/'), '/');
        return ($base === '' ? '' : $base) . '/' . ltrim($path, '/');
    }
}

if (!function_exists('asset')) {
    function asset(string $path): string
    {
        $rel = ltrim($path, '/');
        $url = base_url('assets/' . $rel);
        $file = BASE_PATH . '/assets/' . $rel;
        if (is_file($file)) {
            $url .= '?v=' . filemtime($file); // cache-busting : refetch dès qu'un fichier change
        }
        return $url;
    }
}

if (!function_exists('site_url')) {
    /** URL absolue (scheme + host) à partir d'un chemin. */
    function site_url(string $path = '/'): string
    {
        $https  = (($_SERVER['HTTPS'] ?? '') === 'on') || ((int) ($_SERVER['SERVER_PORT'] ?? 0) === 443);
        $scheme = $https ? 'https' : 'http';
        $host   = (string) ($_SERVER['HTTP_HOST'] ?? 'localhost');
        return $scheme . '://' . $host . base_url($path);
    }
}

if (!function_exists('current_url')) {
    function current_url(): string
    {
        $path = parse_url((string) ($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH);
        return site_url(is_string($path) ? $path : '/');
    }
}

if (!function_exists('media_url')) {
    /**
     * URL publique d'un dérivé d'image.
     * profil null => image « pleine » ; sinon sous-dossier du profil (ex. « thumb »).
     */
    function media_url(int $galleryId, string $filename, ?string $profile = null, bool $webp = false): string
    {
        if ($webp) {
            $filename = preg_replace('/\.[^.]+$/', '.webp', $filename) ?? $filename;
        }
        $sub = $profile !== null && $profile !== '' ? rawurlencode($profile) . '/' : '';
        return base_url('media/galleries/' . $galleryId . '/' . $sub . rawurlencode($filename));
    }
}
