<?php
/**
 * BookiFlex Core
 *
 * @package    BookiFlex
 * @subpackage Core
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */

declare(strict_types=1);

namespace BookiFlex\Core\Service\NumberGenerator;

defined( 'ABSPATH' ) || exit;

/**
 * Generates reservation numbers.
 *
 * For group reservations:
 * - The first reservation gets the base number (e.g.: RES240821-5A2B3)
 * - Subsequent ones get the number with an index (e.g.: RES240821-5A2B3/1, RES240821-5A2B3/2)
 */
class NumberGenerator
{
    private ?string $baseNumber = null;
    private int $index = 0;

    /**
     * Reset state for a new group of reservations
     */
    public function reset(): void
    {
        $this->baseNumber = null;
        $this->index = 0;
    }

    /**
     * Get the next reservation number
     */
    public function nextNumber(): string
    {
        if (!$this->baseNumber) {
            $this->baseNumber = $this->generateBaseNumber();
            return $this->baseNumber;
        }

        $this->index++;
        return $this->baseNumber . '/' . $this->index;
    }

    private function generateBaseNumber(): string
    {
        $date = new \DateTimeImmutable();
        $dateString = $date->format('ymd'); // 240821
        $randomPart = $this->generateRandomString(5);

        return 'RES' . $dateString . '-' . $randomPart;
    }

    private function generateRandomString(int $length = 3): string
    {
        $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';

        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[mt_rand(0, $charactersLength - 1)];
        }

        return $randomString;
    }
}
