<?php

namespace App\Services\Courier;

use App\Models\CourierLedgerEntry;
use App\Models\CourierSettlement;

class CourierVoucherService
{
    public function nextLedgerVoucher(string $prefix): string
    {
        $lastVoucher = CourierLedgerEntry::query()
            ->where('voucher_no', 'like', $prefix . '-%')
            ->lockForUpdate()
            ->latest('id')
            ->value('voucher_no');

        return $this->next($prefix, $lastVoucher);
    }

    public function nextSettlementVoucher(): string
    {
        $lastVoucher = CourierSettlement::query()
            ->where('voucher_no', 'like', 'CST-%')
            ->lockForUpdate()
            ->latest('id')
            ->value('voucher_no');

        return $this->next('CST', $lastVoucher);
    }

    private function next(string $prefix, ?string $lastVoucher): string
    {
        $nextNumber = 1;

        if ($lastVoucher && preg_match('/(\d+)$/', $lastVoucher, $matches)) {
            $nextNumber = ((int) $matches[1]) + 1;
        }

        return $prefix . '-' . str_pad((string) $nextNumber, 6, '0', STR_PAD_LEFT);
    }
}
