<?php

declare(strict_types=1);

namespace App\Support;

use Transliterator;

/**
 * Génération de slugs (URL propres) à partir d'un texte.
 */
final class SlugService
{
    public static function make(string $text): string
    {
        $text = self::toAscii($text);
        $text = strtolower($text);
        $text = preg_replace('/[^a-z0-9]+/', '-', $text) ?? '';
        $text = trim($text, '-');

        return $text !== '' ? $text : 'galerie';
    }

    private static function toAscii(string $text): string
    {
        if (class_exists(Transliterator::class)) {
            $tr = Transliterator::create('Any-Latin; Latin-ASCII');
            if ($tr !== null) {
                $result = $tr->transliterate($text);
                if (is_string($result)) {
                    return $result;
                }
            }
        }

        $map = [
            'à' => 'a', 'á' => 'a', 'â' => 'a', 'ä' => 'a', 'ã' => 'a', 'å' => 'a',
            'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e',
            'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i',
            'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'ö' => 'o', 'õ' => 'o', 'ø' => 'o',
            'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ü' => 'u',
            'ç' => 'c', 'ñ' => 'n', 'ÿ' => 'y',
            'œ' => 'oe', 'æ' => 'ae',
        ];

        return strtr(mb_strtolower($text, 'UTF-8'), $map);
    }
}
