<?php
/**
 * Simple logging service
 */
class Logger {
    private static $instance;
    private $logFile;
    private $logLevel;
    
    private function __construct() {
        $this->logFile = __DIR__ . '/logs/app.log';
        $this->logLevel = env('LOG_LEVEL', 'error');
        
        // Create logs directory if it doesn't exist
        $logDir = dirname($this->logFile);
        if (!is_dir($logDir)) {
            mkdir($logDir, 0755, true);
        }
    }
    
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function shouldLog($level) {
        $levels = ['debug' => 0, 'info' => 1, 'warning' => 2, 'error' => 3];
        $currentLevel = $levels[$this->logLevel] ?? 3;
        $messageLevel = $levels[$level] ?? 3;
        return $messageLevel >= $currentLevel;
    }
    
    public function log($level, $message, $context = []) {
        if (!$this->shouldLog($level)) {
            return;
        }
        
        $timestamp = date('Y-m-d H:i:s');
        $contextStr = !empty($context) ? ' | ' . json_encode($context) : '';
        $logMessage = "[$timestamp] [$level] $message$contextStr" . PHP_EOL;
        
        file_put_contents($this->logFile, $logMessage, FILE_APPEND | LOCK_EX);
    }
    
    public static function debug($message, $context = []) {
        self::getInstance()->log('debug', $message, $context);
    }
    
    public static function info($message, $context = []) {
        self::getInstance()->log('info', $message, $context);
    }
    
    public static function warning($message, $context = []) {
        self::getInstance()->log('warning', $message, $context);
    }
    
    public static function error($message, $context = []) {
        self::getInstance()->log('error', $message, $context);
    }
}
