<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

function client_ip(): string
{
    $keys = ['HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'];

    foreach ($keys as $key) {
        if (!empty($_SERVER[$key])) {
            $value = explode(',', (string) $_SERVER[$key])[0];
            return trim($value);
        }
    }

    return '0.0.0.0';
}

function audit_log(
    string $action,
    string $module,
    ?int $recordId = null,
    mixed $oldData = null,
    mixed $newData = null,
    ?int $userId = null
): bool {
    $userId ??= isset($_SESSION['user_id']) ? (int) $_SESSION['user_id'] : null;

    try {
        db_query(
            'INSERT INTO audit_logs (user_id, action, module, record_id, old_data, new_data, ip_address, created_at)
             VALUES (:user_id, :action, :module, :record_id, :old_data, :new_data, :ip_address, NOW())',
            [
                'user_id' => $userId,
                'action' => $action,
                'module' => $module,
                'record_id' => $recordId,
                'old_data' => $oldData === null ? null : json_encode($oldData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
                'new_data' => $newData === null ? null : json_encode($newData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
                'ip_address' => client_ip(),
            ]
        );

        return true;
    } catch (Throwable) {
        return false;
    }
}
