<?php

namespace App\Models;

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

class Vehicle extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'type', 'plate_number', 'brand', 'model', 'year', 'color', 'fuel_type', 'capacity', 'status', 'divisi_id', 'description', 'image_path'
    ];

    // Mengikuti pola Room.php: Tambahkan appends agar terbaca di array/json
    protected $appends = ['current_status', 'status_label', 'status_color'];

    public function bookings()
    {
        return $this->hasMany(VehicleBooking::class);
    }

    public function divisi()
    {
        return $this->belongsTo(Divisi::class, 'divisi_id');
    }

    /**
     * Logika REAL-TIME identik dengan Room.php
     */
    public function getCurrentStatusAttribute()
    {
        // 1. Cek Maintenance (Gunakan kolom 'status' di tabel vehicles)
        if (in_array($this->status, ['maintenance', 'unavailable'])) {
            return 'maintenance';
        }

        // 2. Cek Occupied (Approved + Waktu Sekarang)
        $isOccupied = $this->bookings()
            ->where('status', 'approved')
            ->where('start_time', '<=', now())
            ->where('end_time', '>', now())
            ->exists();

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

        // 3. Cek Pending (Sesuai permintaan Anda)
        $isPending = $this->bookings()
            ->where('status', 'pending')
            ->exists();

        if ($isPending) {
            return 'pending';
        }

        return 'available';
    }

    public function getStatusLabelAttribute()
    {
        return match ($this->current_status) {
            'available'   => 'Tersedia',
            'occupied'    => 'Sedang Dipinjam',
            'maintenance' => 'Pemeliharaan',
            'pending'     => 'Menunggu Konfirmasi',
            default       => 'Tersedia',
        };
    }

    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',
            'pending'     => 'bg-orange-100 text-orange-800 border-orange-200',
            default       => 'bg-gray-100 text-gray-800',
        };
    }
}