<?php

use App\Models\AuditLog;
use Illuminate\Support\Facades\Auth;

if (!function_exists('audit_log')) {

    /**
     * Store audit log
     *
     * @param string $table
     * @param int|null $recordId
     * @param string $action
     * @param string|null $description
     * @param array|null $changes
     */
    function audit_log(
        string $table,
        ?int $recordId,
        string $action,
        ?string $description = null,
        ?array $changes = null
    ) {
        try {
            AuditLog::create([
                'table_name' => $table,
                'record_id'  => $recordId,
                'action'     => $action,
                'user_id'    => Auth::id(),
                'description'=> $description,
                'changes'    => $changes ? json_encode($changes) : null,
            ]);
        } catch (\Throwable $e) {
            // optional: log error silently
            \Log::error('Audit Log Failed: ' . $e->getMessage());
        }
    }
}
