<?php

namespace Modules\Bms\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * A maintenance request against a hall or office (optionally an asset). Moves
 * through Submitted→Reviewed→Assigned→In Progress→Resolved→Verified with a
 * full update trail (BmsMaintenanceUpdate) and SLA aging off due_at.
 */
class BmsMaintenanceRequest extends Model
{
    protected $table = 'bms_maintenance_requests';

    protected $fillable = [
        'business_id', 'code', 'hall_id', 'location_id', 'asset_id',
        'category', 'priority', 'title', 'description', 'status',
        'reported_by', 'assigned_to', 'due_at', 'resolved_at', 'verified_at', 'photos',
    ];

    protected $casts = [
        'photos'      => 'array',
        'due_at'      => 'datetime',
        'resolved_at' => 'datetime',
        'verified_at' => 'datetime',
    ];

    /** Open = not resolved/verified/cancelled. */
    public const OPEN_STATUSES = ['submitted', 'reviewed', 'assigned', 'in_progress'];

    public function hall(): BelongsTo
    {
        return $this->belongsTo(BmsHall::class, 'hall_id');
    }

    public function asset(): BelongsTo
    {
        return $this->belongsTo(BmsAsset::class, 'asset_id');
    }

    public function updates(): HasMany
    {
        return $this->hasMany(BmsMaintenanceUpdate::class, 'request_id')->latest('id');
    }

    public function isOpen(): bool
    {
        return in_array($this->status, self::OPEN_STATUSES, true);
    }

    /** Past the SLA target and still open. */
    public function isOverdue(): bool
    {
        return $this->due_at && $this->isOpen() && $this->due_at->isPast();
    }
}
