<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class BlockedTime extends Model
{
    use HasFactory;

    protected $fillable = [
        'block_date',
        'start_time',
        'end_time',
        'reason',
    ];

    protected function casts(): array
    {
        return [
            'block_date' => 'date',
        ];
    }

    /**
     * Check if this is a full day block (all-day event).
     */
    public function isAllDay(): bool
    {
        return is_null($this->start_time) && is_null($this->end_time);
    }

    /**
     * Scope to get upcoming blocked times (today and future).
     */
    public function scopeUpcoming(Builder $query): Builder
    {
        return $query->where('block_date', '>=', today());
    }

    /**
     * Scope to get past blocked times.
     */
    public function scopePast(Builder $query): Builder
    {
        return $query->where('block_date', '<', today());
    }

    /**
     * Scope to filter by a specific date.
     */
    public function scopeForDate(Builder $query, $date): Builder
    {
        return $query->where('block_date', $date);
    }

    /**
     * Check if this block covers a specific time slot.
     */
    public function blocksSlot(string $time): bool
    {
        if ($this->isAllDay()) {
            return true;
        }

        $slotTime = Carbon::parse($time);
        $start = Carbon::parse($this->start_time);
        $end = Carbon::parse($this->end_time);

        return $slotTime->gte($start) && $slotTime->lt($end);
    }
}
