<?php

namespace App\Models;

use App\Scopes\CompanyScope;
use Illuminate\Database\Eloquent\Model;

class VoucherNumberSetting extends Model
{
    protected $table = 'voucher_number_settings';

    protected $fillable = [
        'company_id','voucher_type','prefix','suffix',
        'starting_number','current_number','padding_digits',
        'include_year','include_month','separator',
        'reset_period','number_on','allow_manual','last_reset_at',
    ];

    protected $casts = [
        'include_year'  => 'boolean',
        'include_month' => 'boolean',
        'allow_manual'  => 'boolean',
        'last_reset_at' => 'datetime',
    ];

    protected static function booted(): void
    {
        static::addGlobalScope(new CompanyScope());

        static::creating(function ($model) {
            if (auth('web')->check() && empty($model->company_id)) {
                $model->company_id = auth('web')->user()->company_id;
            }
        });
    }

    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    /**
     * Override to avoid name clash with Eloquent's Model::get() collection method.
     * Use all() instead of get() to retrieve all settings.
     */
    public static function allForCompany(int $companyId)
    {
        return static::withoutGlobalScopes()
            ->where('company_id', $companyId)
            ->get();
    }
}
