<?php
class NexoraAudit {
    public static function log($action, $targetType = null, $targetId = null, $before = null, $after = null, $realm = null) {
        $record = array(
            'at' => gmdate('c'),
            'actor' => isset($_SESSION['username']) ? (string)$_SESSION['username'] : 'system',
            'realm' => $realm ?: (class_exists('NexoraRealm') ? NexoraRealm::active() : null),
            'action' => (string)$action,
            'target_type' => $targetType,
            'target_id' => $targetId === null ? null : (string)$targetId,
            'ip' => class_exists('NexoraSecurity') ? NexoraSecurity::clientIp() : ($_SERVER['REMOTE_ADDR'] ?? ''),
            'user_agent' => substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 500),
            'before' => $before,
            'after' => $after,
        );

        $line = json_encode($record, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
        if($line !== false) @file_put_contents(__PATH_LOGS__.'admin_audit.log', $line.PHP_EOL, FILE_APPEND|LOCK_EX);

        if(class_exists('NexoraRealm') && NexoraRealm::platformEnabled()) {
            try {
                $db = Connection::Database('Platform', $record['realm']);
                $db->query(
                    "INSERT INTO NEXORA_AUDIT_LOG (actor, realm, action, target_type, target_id, old_data, new_data, ip_address, user_agent, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, SYSUTCDATETIME())",
                    array($record['actor'], $record['realm'], $record['action'], $record['target_type'], $record['target_id'], self::json($before), self::json($after), $record['ip'], $record['user_agent'])
                );
            } catch(Throwable $ignored) {}
        }
    }

    private static function json($value) {
        if($value === null) return null;
        $json = json_encode($value, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
        return $json === false ? null : $json;
    }
}
