<?php

declare(strict_types=1);

namespace PpPhp\Core\Seo;

/**
 * Turn a title into a URL-safe slug for SEO-friendly URLs (platform feature A1).
 *
 *   "How do I connect to Oracle?"  →  "how-do-i-connect-to-oracle"
 *
 * Pure and deterministic. Uniqueness is NOT this class's job — the storing app
 * guarantees unique slugs (or the URL carries the numeric id as the authority,
 * so a duplicate slug still resolves). Accented characters are transliterated to
 * ASCII where the platform can; anything else becomes a hyphen boundary.
 */
final class Slugify
{
    public static function make(string $text, int $maxLen = 80): string
    {
        $text = trim($text);
        if ($text === '') {
            return '';
        }

        // Best-effort transliteration of accents/diacritics to ASCII.
        if (function_exists('iconv')) {
            $ascii = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $text);
            if (is_string($ascii) && $ascii !== '') {
                $text = $ascii;
            }
        }

        $text = strtolower($text);
        $text = preg_replace('/[^a-z0-9]+/', '-', $text) ?? '';
        $text = trim($text, '-');

        if ($maxLen > 0 && strlen($text) > $maxLen) {
            $text = rtrim(substr($text, 0, $maxLen), '-');
        }

        return $text;
    }
}
