<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;

class Area extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $table = 'areas';

    protected $fillable = [
        'code',
        'name',
        'sort_order',
        'is_active',
        'floor_label',
        'requires_scan_twice',
    ];

    protected $casts = [
        'sort_order' => 'integer',
        'is_active' => 'boolean',
        'requires_scan_twice' => 'boolean',
    ];

    public function settings(): HasOne
    {
        return $this->hasOne(AreaSetting::class, 'area_id');
    }

    public function orderAreaPresences(): HasMany
    {
        return $this->hasMany(OrderAreaPresence::class, 'area_id');
    }

    public function orderAreaScanEvents(): HasMany
    {
        return $this->hasMany(OrderAreaScanEvent::class, 'area_id');
    }

    /**
     * Usuarios con esta área asignada (C5: estación de escaneo).
     */
    public function users(): HasMany
    {
        return $this->hasMany(User::class, 'area_id');
    }

    public function impresoras(): HasMany
    {
        return $this->hasMany(Impresora::class, 'area_id');
    }

    /**
     * Áreas marcadas activas en catálogo y ordenadas para UI.
     */
    public function scopeCatalogActive($query)
    {
        return $query->where('is_active', true)->orderBy('sort_order');
    }

    /**
     * Áreas habilitadas para operación (catálogo activo + configuración encendida).
     */
    public function scopeOperational($query)
    {
        return $query->where('areas.is_active', true)
            ->whereHas('settings', function ($q): void {
                $q->where('is_enabled', true);
            })
            ->orderBy('sort_order');
    }
}
