<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;

class Company extends Model
{
    use HasFactory, SoftDeletes, LogsActivity;

    protected $fillable = [
        'name', 'slug', 'legal_name', 'nit', 'domain',
        'logo_path', 'primary_color', 'contact_email', 'contact_phone',
        'is_active', 'is_operator', 'settings', 'order',
    ];

    protected $casts = [
        'is_active'   => 'boolean',
        'is_operator' => 'boolean',
        'settings'    => 'array',
        'order'       => 'integer',
    ];

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly(['name', 'slug', 'is_active', 'is_operator', 'primary_color'])
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs()
            ->setDescriptionForEvent(fn(string $event) => "Empresa {$this->name} {$event}");
    }

    // ── Relaciones ────────────────────────────────────────────────────────────
    public function users()       { return $this->hasMany(User::class); }
    public function tickets()     { return $this->hasMany(Ticket::class); }
    public function departments() { return $this->hasMany(Department::class); }
    public function kbArticles()  { return $this->hasMany(KbArticle::class); }
    public function assets()      { return $this->hasMany(Asset::class); }

    // ── Scopes ────────────────────────────────────────────────────────────────
    public function scopeActive($query)   { return $query->where('is_active', true); }
    public function scopeOperator($query) { return $query->where('is_operator', true); }

    // ── Helpers ───────────────────────────────────────────────────────────────
    public function logoUrl(): string
    {
        return $this->logo_path
            ? asset($this->logo_path)
            : asset('images/logo.png');
    }

    public function isOperator(): bool
    {
        return (bool) $this->is_operator;
    }

    /**
     * Empresa actualmente activa según la sesión del usuario.
     * Para usuarios normales = su empresa.
     * Para operadores = la que tienen seleccionada en el switcher.
     */
    public static function current(): ?self
    {
        if (!auth()->check()) return null;

        $user = auth()->user();

        // Si el usuario es agente del operador, puede haber elegido una empresa
        if ($user->isOperatorMember() && session()->has('current_company_id')) {
            return self::find(session('current_company_id'));
        }

        // Caso normal: la empresa del usuario
        return $user->company;
    }
}
