<?php

namespace App\Core;

class Slug
{
    public static function make(string $text): string
    {
        $text = strtolower(trim($text));
        $text = preg_replace('/[^a-z0-9]+/', '-', $text);
        return trim($text, '-');
    }

    /**
     * Buat slug unik dengan mengecek ke database via callback.
     * $exists menerima string slug dan mengembalikan bool (true kalau sudah dipakai).
     */
    public static function unique(string $text, callable $exists): string
    {
        $base = self::make($text);
        $slug = $base;
        $i = 2;

        while ($exists($slug)) {
            $slug = $base . '-' . $i;
            $i++;
        }

        return $slug;
    }
}
