<?php
/**
 * CargoHub Free Logger Class
 * 
 * Handles logging for the FREE version
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class CargoHub_Free_Logger {
    
    /**
     * Logger instance
     */
    private static $instance = null;
    
    /**
     * Log file path
     */
    private static $log_file = null;
    
    /**
     * Log levels
     */
    const LEVEL_EMERGENCY = 0;
    const LEVEL_ALERT = 1;
    const LEVEL_CRITICAL = 2;
    const LEVEL_ERROR = 3;
    const LEVEL_WARNING = 4;
    const LEVEL_NOTICE = 5;
    const LEVEL_INFO = 6;
    const LEVEL_DEBUG = 7;
    
    /**
     * Log level names
     */
    private static $level_names = array(
        0 => 'EMERGENCY',
        1 => 'ALERT',
        2 => 'CRITICAL',
        3 => 'ERROR',
        4 => 'WARNING',
        5 => 'NOTICE',
        6 => 'INFO',
        7 => 'DEBUG'
    );
    
    /**
     * Minimum log level (configurable)
     */
    private static $min_level = 3; // ERROR level for FREE version
    
    /**
     * Initialize the logger
     */
    public static function init() {
        if (self::$instance === null) {
            self::$instance = new self();
            self::setup_log_file();
            
            // Set minimum log level based on environment
            if (defined('CARGOHUB_FREE_LOG_LEVEL')) {
                switch (strtoupper(CARGOHUB_FREE_LOG_LEVEL)) {
                    case 'EMERGENCY':
                        self::$min_level = 0;
                        break;
                    case 'ALERT':
                        self::$min_level = 1;
                        break;
                    case 'CRITICAL':
                        self::$min_level = 2;
                        break;
                    case 'ERROR':
                        self::$min_level = 3;
                        break;
                    case 'WARNING':
                        self::$min_level = 4;
                        break;
                    case 'NOTICE':
                        self::$min_level = 5;
                        break;
                    case 'INFO':
                        self::$min_level = 6;
                        break;
                    case 'DEBUG':
                        self::$min_level = 7;
                        break;
                }
            }
        }
    }
    
    /**
     * Setup log file path
     */
    private static function setup_log_file() {
        $upload_dir = wp_upload_dir();
        $log_dir = $upload_dir['basedir'] . '/cargohub-free-logs';
        
        // Create logs directory if it doesn't exist
        if (!file_exists($log_dir)) {
            wp_mkdir_p($log_dir);
            
            // Create .htaccess for security
            $htaccess_content = "deny from all\n";
            file_put_contents($log_dir . '/.htaccess', $htaccess_content);
        }
        
        self::$log_file = $log_dir . '/cargohub-free-' . gmdate('Y-m-d') . '.log';
    }
    
    /**
     * Write log entry
     */
    private static function write_log($level, $message, $context = array()) {
        // Check if logging is enabled and level is sufficient
        if (!self::should_log($level)) {
            return;
        }
        
        // Initialize if not already done
        if (self::$instance === null) {
            self::init();
        }
        
        $timestamp = current_time('Y-m-d H:i:s');
        $level_name = self::$level_names[$level];
        
        // Format context data
        $context_string = '';
        if (!empty($context) && is_array($context)) {
            $context_string = ' Context: ' . wp_json_encode($context);
        }
        
        // Create log entry
        $log_entry = sprintf(
            "[%s] %s: %s%s\n",
            $timestamp,
            $level_name,
            $message,
            $context_string
        );
        
        // Write to file
        require_once ABSPATH . 'wp-admin/includes/file.php';
        global $wp_filesystem;
        if (empty($wp_filesystem)) {
            WP_Filesystem();
        }
        if (self::$log_file && $wp_filesystem) {
            $dir = dirname(self::$log_file);
            if (!$wp_filesystem->is_dir($dir)) {
                $wp_filesystem->mkdir($dir);
            }
            // Append to log file
            $existing = '';
            if ($wp_filesystem->exists(self::$log_file)) {
                $existing = $wp_filesystem->get_contents(self::$log_file);
            }
            $wp_filesystem->put_contents(self::$log_file, $existing . $log_entry, FS_CHMOD_FILE);
        }
        
        // Also log to WordPress debug.log if WP_DEBUG is enabled
        // Optionally: integrate with error_log only in development via WP_DEBUG_LOG
        // Intentionally not using error_log() in production.
    }
    
    /**
     * Check if we should log this level
     */
    private static function should_log($level) {
        return $level <= self::$min_level;
    }
    
    /**
     * Emergency log
     */
    public static function emergency($message, $context = array()) {
        self::write_log(self::LEVEL_EMERGENCY, $message, $context);
    }
    
    /**
     * Alert log
     */
    public static function alert($message, $context = array()) {
        self::write_log(self::LEVEL_ALERT, $message, $context);
    }
    
    /**
     * Critical log
     */
    public static function critical($message, $context = array()) {
        self::write_log(self::LEVEL_CRITICAL, $message, $context);
    }
    
    /**
     * Error log
     */
    public static function error($message, $context = array()) {
        self::write_log(self::LEVEL_ERROR, $message, $context);
    }
    
    /**
     * Warning log
     */
    public static function warning($message, $context = array()) {
        self::write_log(self::LEVEL_WARNING, $message, $context);
    }
    
    /**
     * Notice log
     */
    public static function notice($message, $context = array()) {
        self::write_log(self::LEVEL_NOTICE, $message, $context);
    }
    
    /**
     * Info log
     */
    public static function info($message, $context = array()) {
        self::write_log(self::LEVEL_INFO, $message, $context);
    }
    
    /**
     * Debug log
     */
    public static function debug($message, $context = array()) {
        self::write_log(self::LEVEL_DEBUG, $message, $context);
    }
    
    /**
     * Get log file path
     */
    public static function get_log_file() {
        return self::$log_file;
    }
    
    /**
     * Clean old log files (older than 30 days)
     */
    public static function cleanup_old_logs() {
        $upload_dir = wp_upload_dir();
        $log_dir = $upload_dir['basedir'] . '/cargohub-free-logs';
        
        if (!is_dir($log_dir)) {
            return;
        }
        
        $files = glob($log_dir . '/cargohub-free-*.log');
        $cutoff_time = strtotime('-30 days');
        
        require_once ABSPATH . 'wp-admin/includes/file.php';
        global $wp_filesystem;
        if (empty($wp_filesystem)) {
            WP_Filesystem();
        }
        foreach ($files as $file) {
            if (filemtime($file) < $cutoff_time && $wp_filesystem) {
                $wp_filesystem->delete($file);
            }
        }
    }
    
    /**
     * Get recent log entries
     */
    public static function get_recent_logs($lines = 100) {
        if (!self::$log_file || !file_exists(self::$log_file)) {
            return array();
        }
        
        $file_lines = file(self::$log_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        
        if (!$file_lines) {
            return array();
        }
        
        // Get last $lines entries
        return array_slice($file_lines, -$lines);
    }
}
