<?php

namespace App\Models;

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

class SalaryStep extends Model implements AuditableContract
{
    use Auditable;

    protected $fillable = [
        'salary_grade_id',
        'step',
        'consolidated_amount',
        'effective_from',
        'effective_to',
    ];

    protected function casts(): array
    {
        return [
            'step' => 'integer',
            'consolidated_amount' => 'decimal:2',
            'effective_from' => 'date',
            'effective_to' => 'date',
        ];
    }

    public function grade(): BelongsTo
    {
        return $this->belongsTo(SalaryGrade::class, 'salary_grade_id');
    }

    /**
     * Scope to the row whose effective window contains the given date.
     */
    public function scopeEffectiveOn(Builder $query, string $date): Builder
    {
        return $query->whereDate('effective_from', '<=', $date)
            ->where(function (Builder $q) use ($date) {
                $q->whereNull('effective_to')->orWhereDate('effective_to', '>', $date);
            });
    }
}
