<?php
declare(strict_types=1);

use App\I18n;
use App\Csrf;
use App\Session;

if (!function_exists('e')) {
    function e($value): string {
        if ($value === null) return '';
        return htmlspecialchars((string)$value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

if (!function_exists('t')) {
    function t(string $key, array $params = []): string {
        return I18n::t($key, $params);
    }
}

if (!function_exists('locale')) {
    function locale(): string {
        return I18n::current();
    }
}

if (!function_exists('config')) {
    function config(?string $key = null, $default = null) {
        $c = $GLOBALS['mat_config'] ?? [];
        if ($key === null) return $c;
        $parts = explode('.', $key);
        foreach ($parts as $p) {
            if (!is_array($c) || !array_key_exists($p, $c)) return $default;
            $c = $c[$p];
        }
        return $c;
    }
}

if (!function_exists('url')) {
    function url(string $path = '/'): string {
        if (preg_match('#^(https?:)?//#i', $path)) return $path;
        $base = rtrim((string)config('app.base_url', ''), '/');
        // Auto-detect base path from SCRIPT_NAME when base_url is empty
        if ($base === '') {
            $script = $_SERVER['SCRIPT_NAME'] ?? '/index.php';
            // e.g. /MysticArtTattoo/public/index.php → /MysticArtTattoo/public
            $dir = rtrim(dirname($script), '/\\');
            if ($dir !== '' && $dir !== '.' && $dir !== '/') {
                $base = $dir;
            }
        }
        return $base . '/' . ltrim($path, '/');
    }
}

if (!function_exists('asset')) {
    function asset(string $path): string {
        return url('assets/' . ltrim($path, '/'));
    }
}

if (!function_exists('redirect')) {
    function redirect(string $path): void {
        header('Location: ' . url($path));
        exit;
    }
}

if (!function_exists('csrf_token')) {
    function csrf_token(): string {
        return Csrf::token();
    }
}

if (!function_exists('csrf_field')) {
    function csrf_field(): string {
        return '<input type="hidden" name="_csrf" value="' . e(Csrf::token()) . '">';
    }
}

if (!function_exists('view')) {
    function view(string $template, array $data = []): string {
        $file = MAT_ROOT . '/src/Views/' . str_replace('.', '/', $template) . '.php';
        if (!is_file($file)) {
            throw new \RuntimeException("View not found: {$template}");
        }
        extract($data, EXTR_SKIP);
        ob_start();
        require $file;
        return (string)ob_get_clean();
    }
}

if (!function_exists('render')) {
    /**
     * Render a content template inside a layout.
     * Layout receives $content, $title, $data.
     */
    function render(string $layout, string $template, array $data = [], string $title = ''): void {
        $content = view($template, $data);
        $data['content'] = $content;
        $data['title']   = $title;
        echo view('layouts.' . $layout, $data);
    }
}

if (!function_exists('uuid')) {
    function uuid(): string {
        $b = random_bytes(16);
        $b[6] = chr(ord($b[6]) & 0x0f | 0x40);
        $b[8] = chr(ord($b[8]) & 0x3f | 0x80);
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($b), 4));
    }
}

if (!function_exists('now_iso')) {
    function now_iso(): string {
        return (new \DateTimeImmutable('now'))->format(\DateTimeInterface::ATOM);
    }
}

if (!function_exists('fmt_time')) {
    /** "09:00" → "9:00 AM"; "14:30" → "2:30 PM"; passes through everything else. */
    function fmt_time(?string $hhmm): string {
        if (!$hhmm) return '';
        if (!preg_match('/^\d{1,2}:\d{2}/', $hhmm)) return $hhmm;
        try {
            return (new \DateTimeImmutable($hhmm))->format('g:i A');
        } catch (\Throwable $e) {
            return $hhmm;
        }
    }
}

if (!function_exists('video_provider')) {
    /**
     * Classify a video url into one of:
     *   'native'  – local upload or direct .mp4/.webm (plays in <video>)
     *   'youtube' – YouTube link (plays in YouTube embed iframe)
     *   'vimeo'   – Vimeo link (plays in Vimeo embed iframe)
     *   'link'    – anything else (opens in new tab)
     *
     * Returns ['provider' => ..., 'embed' => url]
     */
    function video_provider(string $url): array {
        if ($url === '') return ['provider' => 'link', 'embed' => $url];

        if (preg_match('#(?:youtube\.com/watch\?v=|youtu\.be/|youtube\.com/embed/)([a-zA-Z0-9_-]{6,})#i', $url, $m)) {
            return ['provider' => 'youtube', 'embed' => 'https://www.youtube.com/embed/' . $m[1] . '?autoplay=1&rel=0&modestbranding=1'];
        }
        if (preg_match('#vimeo\.com/(?:video/)?(\d+)#i', $url, $m)) {
            return ['provider' => 'vimeo', 'embed' => 'https://player.vimeo.com/video/' . $m[1] . '?autoplay=1'];
        }
        if (preg_match('#\.(mp4|webm|mov|m4v)(\?|$)#i', $url) || str_starts_with($url, 'uploads/')) {
            return ['provider' => 'native', 'embed' => $url];
        }
        return ['provider' => 'link', 'embed' => $url];
    }
}

if (!function_exists('fmt_hours')) {
    /** "09:00-16:00" → "9:00 AM – 4:00 PM"; "closed" → "Closed". */
    function fmt_hours(?string $range): string {
        if (!$range) return '';
        $r = trim($range);
        if (strtolower($r) === 'closed' || $r === '') return t('common.closed');
        if (strpos($r, '-') === false) return $r;
        [$a, $b] = array_map('trim', explode('-', $r, 2));
        return fmt_time($a) . ' – ' . fmt_time($b);
    }
}

if (!function_exists('flash')) {
    function flash(?string $key = null, $value = null) {
        if ($key === null) {
            $all = $_SESSION['_flash'] ?? [];
            unset($_SESSION['_flash']);
            return $all;
        }
        if ($value === null) {
            $v = $_SESSION['_flash'][$key] ?? null;
            unset($_SESSION['_flash'][$key]);
            return $v;
        }
        $_SESSION['_flash'][$key] = $value;
    }
}

if (!function_exists('old')) {
    function old(string $key, $default = '') {
        return $_SESSION['_old'][$key] ?? $default;
    }
}

if (!function_exists('remember_old')) {
    function remember_old(array $data): void {
        $_SESSION['_old'] = $data;
    }
}

if (!function_exists('clear_old')) {
    function clear_old(): void {
        unset($_SESSION['_old']);
    }
}
