<?php
namespace Elementor_Pay_Addons\Shared;

class Logger
{
    /**
     * Log file path
     * @var string
     */
    private static $log_file;

    /**
     * Date format for log entries
     * @var string
     */
    private static $date_format = 'Y-m-d H:i:s';

    /**
     * Initialize the logger
     */
    private static function init()
    {
        if (self::$log_file === null) {
            $date = gmdate('Y-m-d');
            self::$log_file = EPA_ADDONS_LOG_FOLDER . "/{$date}.log";
            
            // Ensure log directory exists with proper permissions
            if (!wp_mkdir_p(EPA_ADDONS_LOG_FOLDER)) {
                error_log("Logger: Failed to create log directory");
                return false;
            }
            
            // Set directory permissions to be readable
            @chmod(EPA_ADDONS_LOG_FOLDER, 0755);
        }
        return true;
    }

    /**
     * Write log entry
     * @param string $level Log level (INFO, DEBUG, WARNING, ERROR, FATAL)
     * @param string $message Log message
     * @param array $context Additional context data
     */
    private static function writeLog($level, $message, $context = [])
    {
        // Check if logging is enabled
        $sys_settings = get_option('epa_sys_settings', []);
        if (isset($sys_settings['enable_logging']) && !$sys_settings['enable_logging']) {
            return;
        }

        if (!self::init()) {
            return;
        }

        // Get caller information
        $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
        $caller = $backtrace[2] ?? $backtrace[1] ?? [];
        $file = isset($caller['file']) ? basename($caller['file']) : 'unknown';
        $line = $caller['line'] ?? 'unknown';

        // Format timestamp
        $timestamp = gmdate(self::$date_format);

        // Format context
        $context_str = empty($context) ? '' : ' ' . json_encode($context, JSON_UNESCAPED_SLASHES);

        // Create log entry
        $log_entry = "[{$timestamp}] [{$file}:{$line}] {$level}: {$message}{$context_str}" . PHP_EOL;

        // Write to file with proper error handling
        $result = @file_put_contents(self::$log_file, $log_entry, FILE_APPEND | LOCK_EX);
        
        if ($result === false) {
            // Fallback to error_log if file write fails
            error_log("Logger: Failed to write to log file. Message: {$level}: {$message}");
        } else {
            // Set file permissions to be readable
            @chmod(self::$log_file, 0644);
        }
    }

    /**
     * Log info message
     * @param string $message
     * @param array $context
     */
    public static function info($message, $context = [])
    {
        self::writeLog('INFO', $message, $context);
    }

    /**
     * Log notice message
     * @param string $message
     * @param array $context
     */
    public static function notice($message, $context = [])
    {
        self::writeLog('NOTICE', $message, $context);
    }

    /**
     * Log debug message
     * @param string $message
     * @param array $context
     */
    public static function debug($message, $context = [])
    {
        self::writeLog('DEBUG', $message, $context);
    }

    /**
     * Log warning message
     * @param string $message
     * @param array $context
     */
    public static function warning($message, $context = [])
    {
        self::writeLog('WARNING', $message, $context);
    }

    /**
     * Log error message
     * @param string $message
     * @param array $context
     */
    public static function error($message, $context = [])
    {
        self::writeLog('ERROR', $message, $context);
    }

    /**
     * Log fatal message
     * @param string $message
     * @param array $context
     */
    public static function fatal($message, $context = [])
    {
        self::writeLog('FATAL', $message, $context);
    }

    /**
     * Set custom date format
     * @param string $format
     */
    public static function setDateFormat($format)
    {
        self::$date_format = $format;
    }

    /**
     * Get current log file path
     * @return string|null
     */
    public static function getLogFile()
    {
        self::init();
        return self::$log_file;
    }

    /**
     * Clear current log file
     * @return bool
     */
    public static function clearLog()
    {
        if (self::init() && file_exists(self::$log_file)) {
            return @unlink(self::$log_file);
        }
        return true;
    }
}