<?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 ComponentEnrolment extends Model implements AuditableContract
{
    use Auditable;

    protected $fillable = [
        'employee_id',
        'pay_component_id',
        'amount',
        'rate',
        'active',
        'effective_from',
        'effective_to',
    ];

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

    public function employee(): BelongsTo
    {
        return $this->belongsTo(Employee::class);
    }

    public function component(): BelongsTo
    {
        return $this->belongsTo(PayComponent::class, 'pay_component_id');
    }

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