<?php

namespace App\Filament\Resources\RequestQuotationResource\Pages;

use App\Filament\Resources\RequestQuotationResource;
use App\Models\RequestQuotation;
use Filament\Actions;
use Filament\Resources\Pages\CreateRecord;

class CreateRequestQuotation extends CreateRecord
{
    protected static string $resource = RequestQuotationResource::class;

    public function mount(): void
    {
        parent::mount();

        $this->form->fill([
            'rfq_number' => $this->generateRfqNumber(),
        ]);
    }

    protected function generateRfqNumber(): string
    {
        $year = now()->year;

        $lastRfq = RequestQuotation::whereYear('created_at', $year)
            ->orderBy('id', 'desc')
            ->value('rfq_number');

        if ($lastRfq) {
            $lastNumber = (int) substr($lastRfq, -3);
            $nextNumber = str_pad($lastNumber + 1, 3, '0', STR_PAD_LEFT);
        } else {
            $nextNumber = '001';
        }

        return "C.R.I-{$year}-{$nextNumber}";
    }
}
