<?php
declare(strict_types=1);

namespace App\Core;

final class AuditLogger
{
    public static function log(string $action, ?int $userId, array $context = []): void
    {
        $directory = dirname(__DIR__) . '/storage/audit';
        if (! is_dir($directory)) {
            mkdir($directory, 0775, true);
        }

        $record = [
            'timestamp' => date(DATE_ATOM),
            'user_id' => $userId,
            'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1',
            'action' => $action,
            'context' => $context,
        ];

        file_put_contents(
            $directory . '/' . date('Y-m-d') . '.log',
            json_encode($record, JSON_UNESCAPED_SLASHES) . PHP_EOL,
            FILE_APPEND | LOCK_EX
        );
    }
}
