<?php
namespace EasyChat\Library;

















class Logger
{
     
     
     

    







    public static function write($message, string $filename = 'main.log'): void
    {
        self::append($message, null, $filename);
    }

    


    public static function info($message, string $filename = 'main.log'): void
    {
        self::append($message, 'INFO', $filename);
    }

    


    public static function error($message, string $filename = 'main.log'): void
    {
        self::append($message, 'ERROR', $filename);
    }

    


    public static function warning($message, string $filename = 'main.log'): void
    {
        self::append($message, 'WARNING', $filename);
    }

    


    public static function debug($message, string $filename = 'main.log'): void
    {
        self::append($message, 'DEBUG', $filename);
    }

     
     
     

    



    private static function append($message, ?string $level, string $filename): void
    {
         
        $filename = preg_replace('/[^a-zA-Z0-9._\-]/', '', $filename);
        if (empty($filename)) {
            $filename = 'main.log';
        }
         
        if (substr($filename, -4) !== '.log') {
            $filename .= '.log';
        }

        $dir = self::logDir();
        if (!is_dir($dir)) {
            SafeRuntime::mkdir($dir, 0755, true);
        }

        $text      = is_string($message) ? $message : print_r($message, true);
        $timestamp = date('Y-m-d H:i:s');

        $line = ($level !== null)
            ? sprintf("[%s] [%s] %s\n", $timestamp, $level, $text)
            : sprintf("[%s] %s\n", $timestamp, $text);

        SafeRuntime::writeFile(
            rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $filename,
            $line,
            FILE_APPEND | LOCK_EX
        );
    }

    


    private static function logDir(): string
    {
        if (defined('DIR_LOGS')) {
            return DIR_LOGS;
        }
        $sep = defined('DS') ? DS : DIRECTORY_SEPARATOR;
        if (defined('SITE_PATH')) {
            return SITE_PATH . $sep . 'log';
        }
         
        return __DIR__ . $sep . '..' . $sep . 'log';
    }
}











class Log
{
     
    private $channel;

    



    public function __construct(string $channel)
    {
        $this->channel = (substr($channel, -4) === '.log') ? $channel : $channel . '.log';
    }

    




    public function write($message): void
    {
        Logger::write($message, $this->channel);
    }
}
