<?php
// Prevent direct access
if (count(get_included_files()) === 1) {
    http_response_code(403);
    exit('Forbidden');
}

/** Genera slugs públicos limpios (para /n/{slug} y el QR). */
class Slug {
    public static function make(string $text): string {
        $map = ['á'=>'a','é'=>'e','í'=>'i','ó'=>'o','ú'=>'u','ñ'=>'n','ü'=>'u',
                'Á'=>'a','É'=>'e','Í'=>'i','Ó'=>'o','Ú'=>'u','Ñ'=>'n','Ü'=>'u'];
        $text = strtr($text, $map);
        $text = strtolower($text);
        $text = preg_replace('/[^a-z0-9]+/', '-', $text);
        $text = trim($text, '-');
        return $text !== '' ? substr($text, 0, 70) : 'negocio';
    }

    /** Slug único en la tabla tenants (excluye al propio tenant). */
    public static function uniqueFor(PDO $db, string $base, int $tenantId): string {
        $slug = self::make($base);
        $stmt = $db->prepare("SELECT id FROM tenants WHERE public_slug = :s AND id <> :t AND deleted_at IS NULL LIMIT 1");
        $stmt->execute([':s' => $slug, ':t' => $tenantId]);
        if ($stmt->fetch()) {
            $slug .= '-' . $tenantId; // garantiza unicidad
        }
        return $slug;
    }
}
