<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class RoomBed extends Model
{
    protected $table = 'room_bed';
    public $timestamps = true;
    use SoftDeletes;

    //
    const AVAILABLE = 0;
    const DEPOSIT = 1;
    const UNAVAILABLE = 2;

    protected $fillable = [
        'name',
        'hostel_id',
        'room_id',
        'status',
        'date_available',
    ];

    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at'
    ];

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

    public function hostel()
    {
        return $this->belongsTo('App\Models\Hostel');
    }

    public function contract()
    {
        return $this->belongsTo(Contract::class, 'id', 'bed_id');
    }

    public function contractValid()
    {
        return $this->belongsTo(Contract::class, 'id', 'bed_id')
            ->where('status', '<>', Contract::LIQUIDATED);
    }

    public function reserve()
    {
        return $this->belongsTo(RoomReservation::class, 'id', 'bed_id');
    }

    public function reservation()
    {
        return $this->belongsTo(RoomReservation::class, 'id', 'bed_id');
    }

    public static function boot()
    {
        parent::boot();
        static::deleted(function ($item) {
            $roomId = $item->room_id;
            $room = Room::find($roomId);
            $maxRenters = RoomBed::query()->where('room_id', $roomId)->count();
            if ($room) {
                Room::query()->where('id', $room->id)
                    ->update([
                        'max_renters' => $maxRenters
                    ]);
            }

            $reserve = RoomReservation::query()
                ->where('bed_id', $item->id)
                ->first();
            if ($reserve) {
                $reserve->delete();
            }
        });
    }
}
