<?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
    {
        $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
        }

        $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);
    }
}