<?php
/**
 * Antara — append-only security log.
 * One JSON object per line, ISO timestamp + truncated UA + IP + event + ctx.
 */

require_once __DIR__ . '/paths.php';

final class AntaraLogger
{
    public static function log(string $event, array $ctx = []): void
    {
        try {
            AntaraPaths::ensureDirs();
            $entry = [
                'ts'    => gmdate('Y-m-d\TH:i:s\Z'),
                'event' => $event,
                'ip'    => $_SERVER['REMOTE_ADDR'] ?? '',
                'ua'    => substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 180),
                'ctx'   => $ctx,
            ];
            if (PHP_SAPI !== 'cli') {
                $entry['method'] = substr((string)($_SERVER['REQUEST_METHOD'] ?? ''), 0, 12);
                $entry['uri'] = substr((string)($_SERVER['REQUEST_URI'] ?? ''), 0, 240);
            }
            $line = json_encode($entry, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . PHP_EOL;
            @file_put_contents(AntaraPaths::logFile(), $line, FILE_APPEND | LOCK_EX);
        } catch (\Throwable $e) {
            // logging must never crash the app
        }
    }

    public static function tail(int $maxLines = 200): array
    {
        $f = AntaraPaths::logFile();
        if (!is_file($f)) return [];
        $lines = @file($f, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        if (!$lines) return [];
        if (count($lines) > $maxLines) {
            $lines = array_slice($lines, -$maxLines);
        }
        $out = [];
        foreach ($lines as $l) {
            $obj = json_decode($l, true);
            if (is_array($obj)) $out[] = $obj;
        }
        return $out;
    }
}
