<?php

namespace App\Models;

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

class HostelRoom extends Model
{
    use HasFactory;

    protected $fillable = [
        'hostel_id',
        'room_number',
        'room_type',
        'floor_number',
        'capacity',
        'monthly_fee',
        'amenities',
        'is_active',
    ];

    protected $casts = [
        'floor_number' => 'integer',
        'capacity' => 'integer',
        'monthly_fee' => 'decimal:2',
        'amenities' => 'array',
        'is_active' => 'boolean',
    ];

    // Relationships
    public function hostel()
    {
        return $this->belongsTo(Hostel::class);
    }

    public function allocations()
    {
        return $this->hasMany(HostelAllocation::class);
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeByFloor($query, $floor)
    {
        return $query->where('floor_number', $floor);
    }

    public function scopeByType($query, $type)
    {
        return $query->where('room_type', $type);
    }

    public function scopeAvailable($query)
    {
        return $query->whereRaw('capacity > (SELECT COUNT(*) FROM hostel_allocations WHERE hostel_room_id = hostel_rooms.id AND is_active = true)');
    }

    // Accessors
    public function getOccupiedBedsAttribute()
    {
        return $this->allocations()->where('is_active', true)->count();
    }

    public function getAvailableBedsAttribute()
    {
        return $this->capacity - $this->occupied_beds;
    }

    public function getIsFullAttribute()
    {
        return $this->occupied_beds >= $this->capacity;
    }
}
