<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphToMany;

class Room extends Model
{
    protected $fillable = [
        'room_number',
        'room_category_id',
        'floor',
        'view',
        'description',

        'details',
        'policies',

        'price_override',
        'is_published',
    ];
    /**
     * Casts
     */
    protected $casts = [
        'is_published' => 'boolean',
        'price_override' => 'decimal:2',
    ];

    public function scopePublished(Builder $query): Builder
    {
        return $query->where('is_published', true);
    }

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


    /**
     * Polymorphic relation to images
     */
    public function images(): MorphToMany
    {
        return $this->morphToMany(Image::class, 'imageable')
            ->withPivot('role', 'sort_order')
            ->orderBy('imageables.sort_order')
            ->withTimestamps();
    }

    public function thumbnail()
    {
        return $this->images()->wherePivot('role', 'thumbnail')->first();
    }

    public function thumbnailImage()
    {
        return $this->morphToMany(Image::class, 'imageable')
            ->wherePivot('role', 'thumbnail')
            ->withPivot('sort_order');
    }

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



    public function mealPackages()
    {
        return $this->belongsToMany(MealPackage::class);
    }

    public function addOns()
    {
        return $this->belongsToMany(Addon::class)->with('variants');
    }

    public function roomCategory()
    {
        return $this->belongsTo(RoomCategory::class);
    }

    public function priceModifiers()
    {
        return $this->belongsToMany(PriceModifier::class, 'modifier_room', 'room_id', 'modifier_id');
    }

    public function scopeAvailableFor(Builder $query, string $startDate, string $endDate): Builder
    {
        return $query->published()
            ->whereDoesntHave('availabilities', function ($q) use ($startDate, $endDate) {
                $q->blocking()->overlapping($startDate, $endDate);
            });
    }

    public function isAvailableFor(string $checkIn, string $checkOut): bool
    {
        return !$this->availabilities()
            ->active()
            ->overlapping($checkIn, $checkOut)
            ->exists();
    }
}
