<?php

namespace App\Models;

use App\Enums\RecordStatus;
use Illuminate\Database\Eloquent\Relations\Concerns\AsPivot;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class IntakeProgramme extends Model
{
    use AsPivot;

    protected $table = 'intake_programmes';

    protected $fillable = [
        'intake_id', 'programme_id', 'available_slots',
        'application_open', 'application_close', 'application_fee_override', 'status',
    ];

    protected function casts(): array
    {
        return [
            'application_open' => 'datetime',
            'application_close' => 'datetime',
            'application_fee_override' => 'decimal:2',
            'status' => RecordStatus::class,
        ];
    }

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

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

    /** Window falls back to the parent intake when not overridden. */
    public function isOpen(): bool
    {
        if ($this->status !== RecordStatus::Active) {
            return false;
        }

        $now = now();
        $opens = $this->application_open ?? $this->intake?->application_open_at;
        $closes = $this->application_close ?? $this->intake?->application_close_at;

        if ($opens && $now->lt($opens)) {
            return false;
        }

        if ($closes && $now->gt($closes)) {
            return false;
        }

        return true;
    }
}
