<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class ReservationSlot extends Model
{
    protected $fillable = ['date', 'start_time', 'end_time', 'reservation_service_id', 'is_available', 'max_participants'];

    protected $casts = [
        'date' => 'date',
        'is_available' => 'boolean',
        'max_participants' => 'integer',
    ];

    public function service(): BelongsTo
    {
        return $this->belongsTo(ReservationService::class, 'reservation_service_id');
    }

    public function reservations(): HasMany
    {
        return $this->hasMany(Reservation::class);
    }

    public function confirmedReservations(): HasMany
    {
        return $this->reservations()->where('status', 'confirmed');
    }

    public function remainingPlaces(): ?int
    {
        if ($this->max_participants === null) {
            return null; // illimité
        }
        $count = $this->confirmedReservations()->count();
        return max(0, $this->max_participants - $count);
    }

    public function hasAvailablePlaces(): bool
    {
        $remaining = $this->remainingPlaces();
        return $remaining === null || $remaining > 0;
    }
}
