<?php

namespace App\Models;

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

class Sucursal extends Model
{
    protected $table = 'sucursales';
    protected $fillable = ['nombre', 'direccion', 'telefono', 'activa'];

    protected function casts(): array
    {
        return ['activa' => 'boolean'];
    }

    // ─── Relaciones ───────────────────────────────────────────────

    public function usuarios(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'sucursal_user')->withTimestamps();
    }

    public function stocks(): HasMany
    {
        return $this->hasMany(InsumoStock::class);
    }

    public function kardex(): HasMany
    {
        return $this->hasMany(Kardex::class);
    }

    public function programaciones(): HasMany
    {
        return $this->hasMany(Programacion::class);
    }

    public function ordenesCompra(): HasMany
    {
        return $this->hasMany(OrdenCompra::class);
    }

    public function cajaSesiones(): HasMany
    {
        return $this->hasMany(CajaSesion::class);
    }

    // ─── Helpers ─────────────────────────────────────────────────

    /** Sesión de caja actualmente abierta en esta sucursal */
    public function cajaSesionAbierta(): ?CajaSesion
    {
        return $this->cajaSesiones()->where('estado', 'abierta')->first();
    }

    public function scopeActivas($query)
    {
        return $query->where('activa', true);
    }
}