<?php

namespace App\Observers;

use App\Models\Order;

class OrderObserver
{
    public function creating(Order $order): void
    {
        if ($order->order_number !== null && $order->order_number !== '') {
            return;
        }

        $date = now()->format('Ymd');
        $prefix = "PSN-{$date}-";

        $lastOrder = Order::withTrashed()
            ->where('order_number', 'like', "{$prefix}%")
            ->orderByDesc('order_number')
            ->value('order_number');

        $sequence = $lastOrder !== null
            ? ((int) substr($lastOrder, -5)) + 1
            : 1;

        $order->order_number = $prefix.str_pad((string) $sequence, 5, '0', STR_PAD_LEFT);
    }
}
