<?php
// api/logger.php — Structured JSON logger with auto-rotation (30 days)
class DmLog {
    private static function log(string $level, string $context, string $message, array $data = []): void {
        $dir = __DIR__ . '/../logs';
        if (!is_dir($dir)) return;

        // Auto-rotate: delete log files older than 30 days
        static $rotated = false;
        if (!$rotated) {
            $rotated = true;
            foreach (glob("{$dir}/app-*.log") ?: [] as $f) {
                if (filemtime($f) < strtotime('-30 days')) @unlink($f);
            }
        }

        $entry = json_encode([
            'ts'      => date('c'),
            'level'   => $level,
            'context' => $context,
            'message' => $message,
            'data'    => $data,
        ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

        $file = "{$dir}/app-" . date('Y-m-d') . '.log';
        @file_put_contents($file, $entry . "\n", FILE_APPEND | LOCK_EX);
    }

    public static function info(string $context, string $message, array $data = []): void {
        self::log('INFO', $context, $message, $data);
    }

    public static function warn(string $context, string $message, array $data = []): void {
        self::log('WARN', $context, $message, $data);
    }

    public static function error(string $context, string $message, array $data = []): void {
        self::log('ERROR', $context, $message, $data);
    }
}
