<?php

namespace Modules\Inventory\Models\Traits;

use Illuminate\Support\Facades\DB;

trait GeneratePurchaseRequisitionCode
{
    protected  $purchasePrefix = 'PR-';
    protected  $counterType = 'purchase_requisition';

    public function generatePurchaseRequisitionCode(): string
    {
        return DB::transaction(function () {
            $counter = DB::table('purchase_requisition_counters')
                ->where('type', $this->counterType)
                ->lockForUpdate()
                ->first();

            if (!$counter) {
                DB::table('purchase_requisition_counters')->insert([
                    'type'    => $this->counterType,
                    'counter' => 1,
                ]);

                $number = 1;
            } else {
                $number = $counter->counter + 1;
                
                DB::table('purchase_requisition_counters')
                    ->where('type', $this->counterType)
                    ->update([
                        'counter' => $number,
                    ]);
            }

            return $this->formatCode($number);
        });
    }

    public function getPreviewReqNo(): string
    {
        $counter = DB::table('purchase_requisition_counters')
            ->where('type', $this->counterType)
            ->first();

        $number = $counter ? $counter->counter + 1 : 1;

        return $this->formatCode($number);
    }

    private function formatCode(int $number): string
    {
        return $this->purchasePrefix . str_pad($number, 6, '0', STR_PAD_LEFT);
    }
}
