<?php

namespace lumanPlus\Core;

class Logger
{
    const LEVEL_ERROR = 'ERROR';
    const LEVEL_WARNING = 'WARNING';
    const LEVEL_INFO = 'INFO';
    const LEVEL_DEBUG = 'DEBUG';

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

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

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

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

    private static function log(string $level, string $message, array $context = []): void
    {
        $message = self::interpolate($message, $context);
        $time = date('Y-m-d H:i:s');
        $logEntry = "[$time] [$level] $message" . PHP_EOL;

        if (!is_dir(LPL_LOGS_DIR)) {
            mkdir(LPL_LOGS_DIR, 0755, true);
        }

        $logFile = LPL_LOGS_DIR . DIRECTORY_SEPARATOR . date('Y_m_d') . '.log';

        file_put_contents($logFile, $logEntry, FILE_APPEND);
    }


    private static function interpolate(string $message, array $context = []): string
    {
        foreach ($context as $key => $value) {
            if ( is_array($value) ) {
                continue;
            }

            $message = str_replace("{" . $key . "}", (string)$value, $message);
        }
        return $message;
    }
}
