<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class PurchaseSetting extends Model
{
    protected $fillable = [
        'prefix',
        'next_number',
        'number_length',
        'format',
        'terms',
        'notes',
    ];

    protected function casts(): array
    {
        return [
            'next_number' => 'integer',
            'number_length' => 'integer',
        ];
    }

    /**
     * Get purchase settings (singleton)
     */
    public static function getSettings(): self
    {
        return static::firstOrCreate([], [
            'prefix' => 'PO',
            'next_number' => 1,
            'number_length' => 6,
            'format' => '{prefix}-{number}',
        ]);
    }

    /**
     * Generate next purchase order number
     */
    public function generateNextNumber(): string
    {
        $number = str_pad($this->next_number, $this->number_length, '0', STR_PAD_LEFT);
        $poNumber = str_replace(['{prefix}', '{number}'], [$this->prefix, $number], $this->format);

        $this->increment('next_number');

        return $poNumber;
    }
}
