<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use OwenIt\Auditing\Auditable;
use OwenIt\Auditing\Contracts\Auditable as AuditableContract;

/**
 * A versioned PAYE ruleset: the Consolidated Relief Allowance parameters and
 * minimum-tax rate, plus its graduated bands. Selected by code + effective date
 * so historical payroll runs reproduce their original figures.
 */
class TaxTable extends Model implements AuditableContract
{
    use Auditable;

    protected $fillable = [
        'name',
        'code',
        'effective_from',
        'effective_to',
        'cra_fixed_min',
        'cra_alt_percent',
        'cra_gross_percent',
        'min_tax_percent',
        'active',
    ];

    protected function casts(): array
    {
        return [
            'effective_from' => 'date',
            'effective_to' => 'date',
            'cra_fixed_min' => 'decimal:2',
            'cra_alt_percent' => 'decimal:4',
            'cra_gross_percent' => 'decimal:4',
            'min_tax_percent' => 'decimal:4',
            'active' => 'boolean',
        ];
    }

    public function bands(): HasMany
    {
        return $this->hasMany(TaxBand::class)->orderBy('sort');
    }

    /**
     * The active table for a ruleset whose effective window contains the date.
     * Falls back to the most recent active table for the code.
     */
    public function scopeEffectiveOn(Builder $query, string $code, string $date): Builder
    {
        return $query->where('code', $code)
            ->where('active', true)
            ->whereDate('effective_from', '<=', $date)
            ->where(function (Builder $q) use ($date) {
                $q->whereNull('effective_to')->orWhereDate('effective_to', '>', $date);
            })
            ->orderByDesc('effective_from');
    }
}
