<?php

namespace Modules\Inventory\Models\Traits;

use Illuminate\Support\Facades\DB;

trait GeneratesPurchaseInvoiceTrait
{
    protected  $prefix = 'PI-';
    protected  $counterType = 'purchase';

    public function generateInvoiceNo(): string
    {
        return DB::transaction(function () {

            $counter = DB::table('purchase_counters')
                ->where('type', $this->counterType)
                ->lockForUpdate()
                ->first();

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

            return $this->prefix . str_pad($number, 6, '0', STR_PAD_LEFT);
        });
    }

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

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

        return $this->prefix . str_pad($number, 6, '0', STR_PAD_LEFT);
    }
}
