<?php

namespace App\Traits;

use Illuminate\Support\Facades\Auth;

trait Auditable
{
    protected static function bootAuditable()
    {
        static::created(function ($model) {
            $model->registrarAuditoria('crear');
        });

        static::updated(function ($model) {
            $model->registrarAuditoria('actualizar');
        });

        static::deleted(function ($model) {
            $model->registrarAuditoria('eliminar');
        });
    }

    protected function registrarAuditoria($accion)
    {
        if (app()->bound('db') && Auth::check()) {
            $valoresAnteriores = $accion !== 'crear' ? $this->getOriginal() : [];
            $valoresNuevos = $accion !== 'eliminar' ? $this->getAttributes() : [];

            if ($accion === 'actualizar') {
                $changes = $this->getChanges();
                if (empty($changes)) return;

                $oldDiff = [];
                $newDiff = [];
                foreach ($changes as $key => $value) {
                    if ($key === 'updated_at' || $key === 'created_at') continue;
                    $oldDiff[$key] = $valoresAnteriores[$key] ?? null;
                    $newDiff[$key] = $value;
                }
                
                // Si solo cambió el timestamp, no registrar.
                if (empty($oldDiff) && empty($newDiff)) return;

                $valoresAnteriores = $oldDiff;
                $valoresNuevos = $newDiff;
            }

            \App\Models\Auditoria::create([
                'user_id' => Auth::id(),
                'accion' => $accion,
                'modelo' => class_basename(static::class),
                'modelo_id' => $this->getKey(),
                'valores_anteriores' => empty($valoresAnteriores) ? null : $valoresAnteriores,
                'valores_nuevos' => empty($valoresNuevos) ? null : $valoresNuevos,
                'ip' => request()->ip(),
                'user_agent' => request()->userAgent(),
                'sucursal_id' => session('sucursal_id') ?? Auth::user()->sucursal_default_id,
            ]);
        }
    }
}