<?php

namespace Daniv04\HaciendaPackage\Services\Utils;

use Illuminate\Support\Facades\DB;
use Daniv04\HaciendaPackage\Models\ReceiptConsecutive;
use Daniv04\HaciendaPackage\Traits\ConsecutiveNumberTrait;

class ConsecutiveGeneratorService
{
    use ConsecutiveNumberTrait;
    /**
     * Genera un consecutivo único y seguro usando contador global
     * 
     * @param string $branch Sucursal (3 dígitos)
     * @param string $pos Terminal/POS (5 dígitos)
     * @param string $receiptType Tipo de comprobante (FE, TE, NC, etc.)
     * @return string Consecutivo formateado (XXX-XXXXX-XX-XXXXXXXXXX)
     */
    public function generateConsecutive(string $branch, string $pos, string $receiptType): string
    {
        $consecutiveNumber = $this->getIncrementedConsecutiveNumber();
        
        return $this->format($branch, $pos, $receiptType, $consecutiveNumber);
    }

    
    private function format(
        string $branch,
        string $pos,
        string $receiptType,
        string $consecutiveNumber
    ): string {
        return sprintf(
            '%s-%s-%s-%s',
            str_pad($branch, 3, '0', STR_PAD_LEFT),
            str_pad($pos, 5, '0', STR_PAD_LEFT),
            str_pad($receiptType, 2, '0', STR_PAD_LEFT),
            str_pad($consecutiveNumber, 10, '0', STR_PAD_LEFT)
        );
    }
}