<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Room extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'room_number',
        'accommodation_id',
        'is_available',
    ];

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

    /**
     * Get the accommodation category this room belongs to
     */
    public function accommodation()
    {
        return $this->belongsTo(Accommodation::class);
    }

    /**
     * Get all bookings for this room
     */
    public function bookings()
    {
        return $this->hasMany(Booking::class);
    }

    /**
     * Check if room is available for given dates
     * 
     * @param string $checkIn
     * @param string $checkOut
     * @return bool
     */
    public function isAvailableForDates($checkIn, $checkOut)
    {
        // Check if room is marked as unavailable
        if (!$this->is_available) {
            return false;
        }

        // Check for conflicting confirmed bookings
        // A booking conflicts if:
        // - booking check_in < requested check_out AND
        // - booking check_out > requested check_in
        $conflictingBookings = $this->bookings()
            ->where('status', 'confirmed')
            ->whereNotNull('check_in')
            ->whereNotNull('check_out')
            ->where(function($query) use ($checkIn, $checkOut) {
                $query->where(function($q) use ($checkIn, $checkOut) {
                    // Booking starts before requested checkout
                    $q->where('check_in', '<', $checkOut)
                      // And booking ends after requested checkin
                      ->where('check_out', '>', $checkIn);
                });
            })
            ->exists();

        return !$conflictingBookings;
    }

    /**
     * Get display name: "Room 101 – Simple"
     */
    public function getDisplayNameAttribute()
    {
        $category = $this->accommodation->room_category ?? $this->accommodation->room_name;
        return "Room {$this->room_number} – {$category}";
    }
}
