<?php

namespace App\Traits;

use App\Models\Audit;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;

trait Auditable
{
    /**
     * Boot the trait.
     *
     * @return void
     */
    public static function bootAuditable()
    {
        // Registra evento cuando se crea un modelo
        static::created(function ($model) {
            self::registerAudit('create', $model, null, $model->getAttributes());
        });

        // Registra evento cuando se actualiza un modelo
        static::updated(function ($model) {
            $oldValues = array_intersect_key($model->getOriginal(), $model->getChanges());
            $newValues = $model->getChanges();
            
            self::registerAudit('update', $model, $oldValues, $newValues);
        });

        // Registra evento cuando se elimina un modelo
        static::deleted(function ($model) {
            self::registerAudit('delete', $model, $model->getAttributes(), null);
        });
    }

    /**
     * Registra una entrada de auditoría
     *
     * @param string $action
     * @param mixed $model
     * @param array|null $oldValues
     * @param array|null $newValues
     * @return void
     */
    protected static function registerAudit($action, $model, $oldValues = null, $newValues = null)
    {
        // Si existen valores sensibles, los ocultamos
        if ($oldValues && isset($model->hidden)) {
            $oldValues = array_diff_key($oldValues, array_flip($model->hidden));
        }
        
        if ($newValues && isset($model->hidden)) {
            $newValues = array_diff_key($newValues, array_flip($model->hidden));
        }

        Audit::create([
            'user_id' => Auth::id(),
            'model' => get_class($model),
            'model_id' => $model->getKey(),
            'action' => $action,
            'old_values' => $oldValues,
            'new_values' => $newValues,
            'url' => Request::fullUrl(),
            'method' => Request::method(),
            'ip' => Request::ip(),
            'user_agent' => Request::userAgent()
        ]);
    }
} 