<?php

namespace App\Models;

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

class Room extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'type',
        'price',
        'capacity',
        'description',
        'is_available',
        'image',
    ];

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

    public function bookings()
    {
        return $this->hasMany(Booking::class);
    }

    public function images()
    {
        return $this->hasMany(RoomImage::class);
    }

    public function amenities()
    {
        return $this->belongsToMany(Amenity::class, 'amenity_room');
    }

    public function facilities()
    {
        return $this->belongsToMany(Facility::class, 'facility_room');
    }

    /**
     * Check if room is available for the given date range
     * Checks for both confirmed and pending bookings to prevent double bookings
     */
    public function isAvailable($checkIn, $checkOut)
    {
        // Check for overlaps using simple logic:
        // Two time periods overlap if (StartA < EndB) AND (EndA > StartB)
        // We use < and > instead of <= and >= to allow check-out/check-in on same day
        return !$this->bookings()
            ->whereIn('status', ['confirmed', 'pending'])
            ->where(function ($query) use ($checkIn, $checkOut) {
                $query->where('check_in', '<', $checkOut)
                      ->where('check_out', '>', $checkIn);
            })
            ->exists();
    }

    /**
     * Get all booked date ranges for this room
     */
    public function getBookedDates()
    {
        return $this->bookings()
            ->whereIn('status', ['confirmed', 'pending'])
            ->select('check_in', 'check_out')
            ->get()
            ->map(function ($booking) {
                return [
                    'start' => $booking->check_in->format('Y-m-d'),
                    'end' => $booking->check_out->format('Y-m-d'),
                ];
            });
    }
}
