<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class RoomAvailability extends Model
{
    protected $fillable = [
        'room_id',
        'booking_id',
        'start_date',
        'end_date',
        'status',
        'source',
        'message',
        'details',
        'created_by',
    ];

    protected $casts = [
        'start_date' => 'date',
        'end_date' => 'date',
        'details' => 'array',
    ];

    /*
    |-----------------------------------------
    | RELATIONSHIPS
    |-----------------------------------------
    */

    public function room()
    {
        return $this->belongsTo(Room::class);
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /*
    |-----------------------------------------
    | SCOPES (IMPORTANT FOR CONTROLLER CLEANLINESS)
    |-----------------------------------------
    */

    // Filter by room
    public function scopeForRoom(Builder $query, int $roomId): Builder
    {
        return $query->where('room_id', $roomId);
    }

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

    // Active availability types only
    public function scopeActive(Builder $query): Builder
    {
        return $query->whereIn('status', ['booked', 'blocked', 'pending']);
    }

    public function scopeBlocking(Builder $query): Builder
    {
        return $query->whereIn('status', ['booked', 'blocked', 'pending']);
    }

    // Only blocked (admin/manual)
    public function scopeBlocked(Builder $query): Builder
    {
        return $query->where('status', 'blocked');
    }

    // Only bookings (real occupancy)
    public function scopeBooked(Builder $query): Builder
    {
        return $query->where('status', 'booked');
    }

    // Date overlap check (VERY IMPORTANT for hotel systems)
    public function scopeOverlapping(Builder $query, string $start, string $end): Builder
    {
        return $query->where(function ($q) use ($start, $end) {
            $q->where('start_date', '<', $end)
                ->where('end_date', '>=', $start);
        });
    }





    /*
    |-----------------------------------------
    | BUSINESS LOGIC HELPERS
    |-----------------------------------------
    */

    // Check if this record blocks availability
    public function isBlocking(): bool
    {
        return in_array($this->status, ['booked', 'blocked']);
    }

    // Human readable source label
    public function getSourceLabel(): string
    {
        return match ($this->source) {
            'website' => 'Direct Website',
            'admin' => 'Admin Panel',
            'booking_com' => 'Booking.com',
            default => ucfirst($this->source),
        };
    }
}
