<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Factories\HasFactory;

use Spatie\Permission\Traits\HasRoles;
use App\Traits\Auditable;

class User extends Authenticatable
{
    use HasFactory, Notifiable, HasRoles, Auditable;

    protected $fillable = [
        'name', 'email', 'password',
        'dni', 'telefono', 'activo',
        'sucursal_default_id',
    ];

    protected $hidden = ['password', 'remember_token'];

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password'          => 'hashed',
            'activo'            => 'boolean',
        ];
    }

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

    public function sucursalDefault(): BelongsTo
    {
        return $this->belongsTo(Sucursal::class, 'sucursal_default_id');
    }

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

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

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

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

    /** Devuelve la sucursal activa en la sesión actual */
    public function sucursalActiva(): ?Sucursal
    {
        $id = session('sucursal_id');
        if (! $id) return $this->sucursalDefault;
        return $this->sucursales->find($id) ?? $this->sucursalDefault;
    }

    /** Scope: solo usuarios activos */
    public function scopeActivos($query)
    {
        return $query->where('activo', true);
    }
}