<?php

namespace App\Helpers;

/**
 * A class for generating unique invoice numbers.
 */
class InvoiceGenerator
{
    private $invoice_no;
    private $prefix = 'INV-';
    private $start_at = 1;
    private $increment_by = 1;
    private $current_length = 5; // Initial length is 5

    /**
     * Sets the prefix for the invoice number.
     *
     * @param string $prefix The prefix for the invoice number.
     *
     * @return self
     */
    public function prefix(string $prefix): self
    {
        $this->prefix = $prefix;
        return $this;
    }

    /**
     * Sets the starting number for the invoice number sequence.
     *
     * @param int $start_at The starting number for the invoice number sequence.
     *
     * @return self
     */
    public function startAt(int $start_at): self
    {
        $this->start_at = $start_at;
        return $this;
    }

    /**
     * Generates a unique invoice number.
     *
     * @return string The generated invoice number.
     */
    public function generate(): string
    {
        $this->invoice_no = $this->prefix . $this->getNextNumber();
        return $this->invoice_no;
    }

    public function generateNumber(): string
    {
        $this->invoice_no = $this->getNextNumber();
        return $this->invoice_no;
    }

    /**
     * Generates the next invoice number.
     *
     * @return string The generated invoice number.
     */
    private function getNextNumber(): string
    {
        // Check if the current number length has reached its maximum (e.g., 5) and increase the length by 1
        if ($this->start_at >= pow(10, $this->current_length) - 1) {
            $this->current_length += 1;
        }

        $this->start_at += $this->increment_by;
        $nextNumber = str_pad($this->start_at, $this->current_length, '0', STR_PAD_LEFT);

        return $nextNumber;
    }
}
