<?php

declare(strict_types=1);

namespace App\Shared\Support;

use App\Core\Auth;
use App\Shared\Schema\SchemaSupport;
use Throwable;

final class AuditSupport
{
    public static function log(string $action, ?string $entity = null, $entityId = null, array $meta = []): void
    {
        try {
            $pdo = db();
            if (!SchemaSupport::tableExists($pdo, 'audit_logs')) {
                return;
            }

            $uid = Auth::id();
            $ip = $_SERVER['REMOTE_ADDR'] ?? null;
            $ua = $_SERVER['HTTP_USER_AGENT'] ?? null;

            $st = $pdo->prepare("INSERT INTO audit_logs (user_id, action, entity, entity_id, meta_json, ip_address, user_agent)
                                 VALUES (?,?,?,?,?,?,?)");
            $st->execute([
                $uid,
                $action,
                $entity,
                $entityId !== null ? (string) $entityId : null,
                $meta ? json_encode($meta, JSON_UNESCAPED_UNICODE) : null,
                $ip,
                $ua ? mb_substr($ua, 0, 255) : null,
            ]);
        } catch (Throwable $e) {
            // Do not break the app on log failures.
        }
    }
}
