<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Services;

use App\Core\App;

final class NumberGeneratorService
{
    public static function subscriptionNumber(): string
    {
        return self::generateWithRetry('sa_subscriptions', 'subscription_number', 'SUB');
    }

    public static function bookingNumber(): string
    {
        return self::generateWithRetry('sa_bookings', 'booking_number', 'BK');
    }

    private static function generateWithRetry(string $table, string $column, string $prefix, int $maxAttempts = 10): string
    {
        $db = App::getInstance()->db();
        $datePrefix = $prefix . '-' . date('Ymd') . '-';

        for ($attempt = 0; $attempt < $maxAttempts; $attempt++) {
            $number = $datePrefix . str_pad((string) random_int(1, 9999), 4, '0', STR_PAD_LEFT);
            $exists = $db->selectOne(
                "SELECT id FROM `{$table}` WHERE `{$column}` = ?",
                [$number]
            );
            if (!$exists) {
                return $number;
            }
        }

        return $datePrefix . str_pad((string) random_int(10000, 99999), 5, '0', STR_PAD_LEFT);
    }
}
