<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Spatie\Permission\Traits\HasRoles;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

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

    // NOTA: User NO usa el trait BelongsToCompany ni el CompanyScope global.
    // Razón: necesitamos poder buscar usuarios de cualquier empresa al hacer
    // login y para que los agentes Fycls puedan ver TODOS los usuarios.
    // El aislamiento se aplica en queries explícitas mediante scopes opcionales.

    protected $fillable = [
        'company_id', 'name', 'email', 'password', 'is_active', 'is_available',
        'phone', 'extension', 'position', 'location', 'avatar', 'department_id'
    ];

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

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

    // ── Relaciones ────────────────────────────────────────────────────────────
    public function company(): BelongsTo {
        return $this->belongsTo(Company::class);
    }
    public function department(): BelongsTo {
        return $this->belongsTo(Department::class);
    }
    public function agentGroups(): BelongsToMany {
        return $this->belongsToMany(AgentGroup::class, 'agent_group_user');
    }
    public function assignedTickets(): \Illuminate\Database\Eloquent\Relations\HasMany {
        return $this->hasMany(\App\Models\Ticket::class, "assignee_id");
    }

    // ── Scopes ────────────────────────────────────────────────────────────────
    public function scopeActive($query) {
        return $query->where('is_active', true);
    }
    public function scopeAgents($query) {
        return $query->whereHas('roles', fn($q) => $q->whereIn('name', ['agente', 'jefe_soporte']));
    }
    public function scopeAvailable($query) {
        return $query->where('is_available', true)->where('is_active', true);
    }
    public function scopeOfCompany($query, int $companyId) {
        return $query->where('company_id', $companyId);
    }

    // ── Multi-tenant helpers ──────────────────────────────────────────────────

    /**
     * ¿Es miembro de la empresa operadora (Fycls)?
     * Estos usuarios pueden ver y atender tickets de TODAS las empresas.
     */
    public function isOperatorMember(): bool {
        return $this->company && $this->company->is_operator;
    }

    /**
     * ¿Tiene acceso a esta empresa específica?
     */
    public function canAccessCompany(int $companyId): bool {
        if ($this->isOperatorMember()) return true;
        return $this->company_id === $companyId;
    }

    /**
     * Empresa con la que está trabajando ahora mismo.
     */
    public function activeCompany(): ?Company {
        if ($this->isOperatorMember() && session()->has('current_company_id')) {
            return Company::find(session('current_company_id'));
        }
        return $this->company;
    }

    // ── Helpers UI ────────────────────────────────────────────────────────────
    public function getAvatarUrlAttribute(): string {
        return $this->avatar
            ? asset('storage/' . $this->avatar)
            : 'https://ui-avatars.com/api/?name=' . urlencode($this->name) . '&color=2E86AB&background=E8F4F8';
    }

    public function getActivitylogOptions(): LogOptions {
        return LogOptions::defaults()
            ->logOnly(['name', 'email', 'is_active', 'department_id', 'company_id'])
            ->logOnlyDirty()
            ->setDescriptionForEvent(fn(string $e) => match($e) {
                'created' => "Usuario {$this->name} creado",
                'updated' => "Usuario {$this->name} actualizado",
                'deleted' => "Usuario {$this->name} eliminado",
                default   => "Usuario {$this->name}: {$e}",
            });
    }
}
