<?php

namespace App\Models;

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

class HostelAllocation extends Model
{
    use HasFactory;

    protected $fillable = [
        'hostel_id',
        'hostel_room_id',
        'student_id',
        'bed_number',
        'allocation_date',
        'checkout_date',
        'monthly_fee',
        'remarks',
        'is_active',
    ];

    protected $casts = [
        'allocation_date' => 'date',
        'checkout_date' => 'date',
        'monthly_fee' => 'decimal:2',
        'is_active' => 'boolean',
    ];

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

    public function room()
    {
        return $this->belongsTo(HostelRoom::class, 'hostel_room_id');
    }

    public function student()
    {
        return $this->belongsTo(Student::class);
    }

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

    public function scopeForHostel($query, $hostelId)
    {
        return $query->where('hostel_id', $hostelId);
    }

    public function scopeForRoom($query, $roomId)
    {
        return $query->where('hostel_room_id', $roomId);
    }

    public function scopeForStudent($query, $studentId)
    {
        return $query->where('student_id', $studentId);
    }

    public function scopeCurrent($query)
    {
        return $query->where('allocation_date', '<=', now())
                     ->where(function($q) {
                         $q->whereNull('checkout_date')
                           ->orWhere('checkout_date', '>=', now());
                     });
    }

    // Methods
    public function checkout($date = null)
    {
        $this->checkout_date = $date ?? now();
        $this->is_active = false;
        $this->save();
    }
}
