<?php

namespace App\Models;

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

class Room extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'building',
        'floor',
        'capacity',
        'type',
        'manual_status',
        'description',
        'image'
    ];

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

    /**
     * Accessor untuk mendapatkan status REAL-TIME.
     * Tidak disimpan di DB, tapi dihitung saat data diambil.
     */
    public function getCurrentStatusAttribute()
    {
        // 1. Status operasional manual selalu menjadi prioritas
        if (in_array($this->manual_status, ['maintenance', 'closed'], true)) {
            return $this->manual_status;
        }

        // 2. Cek apakah SEKARANG sedang ada booking aktif
        // Logika: Ada booking dimana start <= sekarang DAN end > sekarang
        $isOccupied = $this->bookings()
            ->whereIn('status', ['approved', 'final_approved'])
            ->where('start_time', '<=', now())
            ->where('end_time', '>', now())
            ->exists();

        if ($isOccupied) {
            return 'occupied';
        }

        // 3. Jika aman
        return 'available';
    }

    // Helper warna badge
    public function getStatusColorAttribute()
    {
        return match ($this->current_status) {
            'available' => 'bg-green-100 text-green-800 border-green-200',
            'occupied' => 'bg-red-100 text-red-800 border-red-200',
            'maintenance' => 'bg-yellow-100 text-yellow-800 border-yellow-200',
            'closed' => 'bg-gray-200 text-gray-800 border-gray-300',
            default => 'bg-gray-100 text-gray-800',
        };
    }
    
    // Helper label status
    public function getStatusLabelAttribute()
    {
        return match ($this->current_status) {
            'available' => 'Tersedia',
            'occupied' => 'Sedang Dipinjam',
            'maintenance' => 'Pemeliharaan',
            'closed' => 'Ditutup Sementara',
            default => $this->current_status,
        };
    }

    // Helper Label Tipe
    public function getTypeLabelAttribute()
    {
        return match ($this->type) {
            'office' => 'Kantor/Konseling',
            'meeting' => 'Rapat',
            'storage' => 'Gudang',
            'laboratory' => 'Laboratorium',
            default => 'Lainnya',
        };
    }
    
    // Helper Warna Tipe
    public function getTypeColorAttribute()
    {
        return match ($this->type) {
            'office' => 'bg-blue-100 text-blue-800',
            'meeting' => 'bg-purple-100 text-purple-800',
            default => 'bg-gray-100 text-gray-800',
        };
    }
}
