<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Event extends Model
{
    protected $fillable = [
        'name',
        'description',
        'type',
        'event_date',
        'event_time',
        'capacity',
        'price_per_person',
        'status',
        'location',
    ];

    protected $casts = [
        'event_date' => 'date',
        'event_time' => 'datetime:H:i',
        'price_per_person' => 'decimal:2',
    ];

    /**
     * Get all reservations for this event.
     */
    public function reservations(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'event_reservations')
            ->withPivot('number_of_guests', 'status', 'created_at')
            ->withTimestamps();
    }

    /**
     * Get the number of confirmed reservations.
     */
    public function confirmedReservationsCount(): int
    {
        return $this->reservations()
            ->wherePivot('status', 'confirmed')
            ->sum('event_reservations.number_of_guests');
    }

    /**
     * Get the number of available spots.
     */
    public function availableSpots(): int
    {
        return $this->capacity - $this->confirmedReservationsCount();
    }

    /**
     * Check if the event is full.
     */
    public function isFull(): bool
    {
        return $this->availableSpots() <= 0;
    }
}
