<?php
namespace App\Core;

use App\Core\Database;

final class Audit
{
    public static function log(
        string $action,
        ?string $entityName = null,
        ?int $entityId = null,
        array $details = []
    ): void {

        try {
            $db = Database::getInstance();

            $userId = $_SESSION['user']['id'] ?? null;
            $orgId  = $_SESSION['current_org_id'] ?? null;

            $db->prepare("
                INSERT INTO audit_logs
                (user_id, action, entity_name, entity_id, details, ip_address, user_agent, org_id)
                VALUES
                (:uid, :action, :entity_name, :entity_id, :details, :ip, :ua, :org_id)
            ")->execute([
                ':uid'         => $userId,
                ':action'      => $action,
                ':entity_name' => $entityName,
                ':entity_id'   => $entityId,
                ':details'     => !empty($details) ? json_encode($details) : null,
                ':ip'          => $_SERVER['REMOTE_ADDR'] ?? null,
                ':ua'          => $_SERVER['HTTP_USER_AGENT'] ?? null,
                ':org_id'      => $orgId,
            ]);

        } catch (\Throwable $e) {
            // never break system because of audit
        }
    }
}
