<?php
declare(strict_types=1);

namespace App\Core;

final class Logger
{
    public static function info(string $message, array $context = []): void
    {
        self::write('INFO', $message, $context);
    }

    public static function warning(string $message, array $context = []): void
    {
        self::write('WARNING', $message, $context);
    }

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

    public static function debug(string $message, array $context = []): void
    {
        self::write('DEBUG', $message, $context);
    }

    private static function write(string $level, string $message, array $context): void
    {
        $levels = ['DEBUG' => 0, 'INFO' => 1, 'WARNING' => 2, 'ERROR' => 3];
        $minLevel = $_ENV['LOG_LEVEL'] ?? 'DEBUG';
        if (($levels[$level] ?? 0) < ($levels[$minLevel] ?? 0)) {
            return;
        }

        $logDir = Autoloader::basePath() . '/storage/logs';
        if (!is_dir($logDir)) {
            @mkdir($logDir, 0775, true);
        }

        $file = $logDir . '/app_' . date('Y-m-d') . '.log';
        $employeeId = 0;

        try {
            $employee = App::getInstance()->currentEmployee();
            if ($employee) {
                $employeeId = $employee->id ?? ($employee['id'] ?? 0);
            }
        } catch (\Throwable $e) {
            // ignore
        }

        $context['_url'] = $_SERVER['REQUEST_URI'] ?? 'cli';
        $context['_method'] = $_SERVER['REQUEST_METHOD'] ?? 'CLI';
        $context['_ip'] = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';

        $contextStr = !empty($context) ? ' ' . json_encode($context, JSON_UNESCAPED_UNICODE) : '';
        $line = sprintf(
            "[%s] [%s] [employee_id:%d] %s%s\n",
            date('Y-m-d H:i:s'),
            $level,
            $employeeId,
            $message,
            $contextStr
        );

        @file_put_contents($file, $line, FILE_APPEND | LOCK_EX);
    }
}