<?php
declare(strict_types=1);

class Slug
{
    /**
     * Basic slug creation (USED BY OLD APIS)
     */
    public static function make(string $text): string
    {
        $text = trim($text);
        $text = mb_strtolower($text, 'UTF-8');
        $text = preg_replace('/[^a-z0-9]+/u', '-', $text);
        return trim($text, '-');
    }

    /**
     * Generate UNIQUE slug for DB tables (NEW, SAFE)
     */
    public static function unique(
        string $text,
        string $table,
        ?int $ignoreId = null,
        string $column = 'slug'
    ): string {
        $db = Database::getInstance();

        $baseSlug = self::make($text);
        $slug = $baseSlug;
        $i = 1;

        while (true) {
            $sql = "SELECT COUNT(*) FROM {$table} WHERE {$column} = :slug";
            $params = ['slug' => $slug];

            if ($ignoreId !== null) {
                $sql .= " AND id != :id";
                $params['id'] = $ignoreId;
            }

            $stmt = $db->prepare($sql);
            $stmt->execute($params);

            if ((int)$stmt->fetchColumn() === 0) {
                break;
            }

            $slug = $baseSlug . '-' . $i;
            $i++;
        }

        return $slug;
    }
}
