<?php
/**
 * Logging Module
 *
 * Provides enterprise-grade logging and debugging capabilities for Mamba Cache.
 * Includes log viewing, filtering, export, and automatic cleanup.
 *
 * @package Mamba\Modules\Logs
 * @since   1.0.0
 */

namespace Mamba\Modules\Logs;

if (!defined('ABSPATH')) {
    exit;
}

use Mamba\Support\Logger;
use Mamba\Support\Paths;

/**
 * Class Module
 *
 * Main logging module that provides log viewing, filtering, export,
 * and automatic cleanup functionality for debugging cache operations.
 *
 * @since 1.0.0
 */
final class Module {
    
    public function __construct(private ?Paths $paths = null) {}
    
    public function register(): void {
        // Register the Logs tab
        add_action('mamba/admin/tab/logs', [$this, 'renderLogs'], 10, 1);
        
        // Register AJAX handlers
        add_action('wp_ajax_mamba_get_logs', [$this, 'ajaxGetLogs']);
        add_action('wp_ajax_mamba_export_logs', [$this, 'ajaxExportLogs']);
        add_action('wp_ajax_mamba_clear_logs', [$this, 'ajaxClearLogs']);
        add_action('wp_ajax_mamba_save_log_settings', [$this, 'ajaxSaveSettings']);
        
        // Schedule daily log cleanup
        if (!wp_next_scheduled('mamba_cleanup_logs')) {
            wp_schedule_event(time(), 'daily', 'mamba_cleanup_logs');
        }
        add_action('mamba_cleanup_logs', [$this, 'cleanupLogs']);
        
        // Log key cache events if logging is enabled
        if (get_option('mamba_enable_logging', 1)) {
            $this->registerCacheEventLogging();
            
            // Log initial entry on admin page load to confirm logging is working
            add_action('admin_init', function() {
                static $logged = false;
                if (!$logged && isset($_GET['page']) && sanitize_key(wp_unslash($_GET['page'])) === 'mamba-cache-for-woocommerce') {
                    $logged = true;
                    Logger::info('Mamba admin page loaded', ['tab' => sanitize_text_field(wp_unslash($_GET['tab'] ?? 'dashboard'))]);
                }
            });
        }
    }
    
    /**
     * Register hooks to log cache events
     */
    private function registerCacheEventLogging(): void {
        // Log full cache purge events (actual action name used in Invalidation.php)
        add_action('mamba_cache_purged', function() {
            Logger::info('Full cache purged', ['type' => 'all']);
        });
        
        add_action('mamba_purge_all', function() {
            Logger::info('Cache purge all triggered');
        });
        
        // Log URL-specific purges
        add_action('mamba_purge_urls', function($urls) {
            if (!empty($urls)) {
                Logger::info('URLs purged', ['urls' => $urls, 'count' => count($urls)]);
            }
        });
        
        // Log tag-based purges
        add_action('mamba_purge_tags', function($tags) {
            if (!empty($tags)) {
                Logger::info('Tags purged', ['tags' => $tags, 'count' => count($tags)]);
            }
        });
        
        // Log warmup events
        add_action('mamba_warmup_started', function($totalUrls) {
            Logger::warmup('started', ['total_urls' => $totalUrls]);
        });
        
        add_action('mamba_warmup_completed', function($stats) {
            Logger::warmup('completed', is_array($stats) ? $stats : []);
        });
        
        add_action('mamba_warmup_url', function($url, $status) {
            Logger::debug("Warmup URL: {$url}", ['status' => $status]);
        }, 10, 2);
        
        // Log cache hits/misses (debug level for high volume)
        add_action('mamba_cache_hit', function($url) {
            Logger::debug("Cache HIT: {$url}");
        });
        
        add_action('mamba_cache_miss', function($url, $reason = '') {
            Logger::debug("Cache MISS: {$url}", ['reason' => $reason]);
        }, 10, 2);
        
        // Log settings changes
        add_action('update_option_mamba_enable_page_cache', function($old, $new) {
            if ($old !== $new) {
                Logger::info('Page cache setting changed', ['from' => $old, 'to' => $new]);
            }
        }, 10, 2);
        
        // Log Store API cache clears
        add_action('mamba_store_api_cleared', function() {
            Logger::info('Store API cache cleared');
        });
        
        // Log DB optimization tasks
        add_action('mamba_db_task_completed', function($taskId, $rowsAffected) {
            Logger::info("DB task completed: {$taskId}", ['rows_affected' => $rowsAffected]);
        }, 10, 2);
        
        // Log errors
        add_action('mamba_cache_error', function($message, $context = []) {
            Logger::error($message, $context);
        }, 10, 2);
        
        // Log on plugin activation/settings save
        add_action('mamba_settings_saved', function($tab) {
            Logger::info("Settings saved: {$tab}");
        });
    }
    
    /**
     * Render the Logs tab
     */
    public function renderLogs(Paths $paths): void {
        $logger = Logger::getInstance();
        $stats = $logger->getStats();
        $files = $logger->getLogFiles();
        
        // Current settings
        $debugMode = (bool) get_option('mamba_debug_mode', 0);
        $loggingEnabled = (bool) get_option('mamba_enable_logging', 1);
        $logLevel = get_option('mamba_log_level', Logger::LEVEL_INFO);
        $retentionDays = (int) get_option('mamba_log_retention_days', 7);
        
        require __DIR__ . '/views/TabLogs.php';
    }
    
    /**
     * AJAX: Get log entries
     */
    public function ajaxGetLogs(): void {
        check_ajax_referer('mamba_logs', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Insufficient permissions']);
        }
        
        $date = sanitize_text_field(wp_unslash($_POST['date'] ?? ''));
        $level = sanitize_text_field(wp_unslash($_POST['level'] ?? ''));
        $limit = min(500, max(10, (int) wp_unslash($_POST['limit'] ?? 100)));
        $offset = max(0, (int) wp_unslash($_POST['offset'] ?? 0));
        
        $logger = Logger::getInstance();
        $result = $logger->readLogs($date, $level, $limit, $offset);
        
        wp_send_json_success($result);
    }
    
    /**
     * AJAX: Export logs
     */
    public function ajaxExportLogs(): void {
        check_ajax_referer('mamba_logs', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Insufficient permissions']);
        }
        
        $days = min(30, max(1, (int) wp_unslash($_POST['days'] ?? 3)));
        
        $logger = Logger::getInstance();
        $export = $logger->exportLogs($days);
        
        wp_send_json_success([
            'content' => $export,
            'filename' => 'mamba-logs-' . wp_date('Y-m-d-His') . '.json',
        ]);
    }
    
    /**
     * AJAX: Clear logs
     */
    public function ajaxClearLogs(): void {
        check_ajax_referer('mamba_logs', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Insufficient permissions']);
        }
        
        $logger = Logger::getInstance();
        $deleted = $logger->clearAll();
        
        Logger::info('Logs cleared manually', ['files_deleted' => $deleted]);
        
        wp_send_json_success([
            'message' => sprintf(__('%d log files deleted', 'mamba-cache-for-woocommerce'), $deleted),
            'deleted' => $deleted,
        ]);
    }
    
    /**
     * AJAX: Save log settings
     */
    public function ajaxSaveSettings(): void {
        check_ajax_referer('mamba_logs', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Insufficient permissions']);
        }
        
        $debugMode = isset($_POST['debug_mode']) && sanitize_text_field(wp_unslash($_POST['debug_mode'])) === '1';
        $loggingEnabled = isset($_POST['logging_enabled']) && sanitize_text_field(wp_unslash($_POST['logging_enabled'])) === '1';
        $logLevel = sanitize_text_field(wp_unslash($_POST['log_level'] ?? Logger::LEVEL_INFO));
        $retentionDays = min(30, max(1, (int) wp_unslash($_POST['retention_days'] ?? 7)));
        
        // Validate log level
        $validLevels = [Logger::LEVEL_ERROR, Logger::LEVEL_WARNING, Logger::LEVEL_INFO, Logger::LEVEL_DEBUG];
        if (!in_array($logLevel, $validLevels, true)) {
            $logLevel = Logger::LEVEL_INFO;
        }
        
        update_option('mamba_debug_mode', $debugMode ? 1 : 0);
        update_option('mamba_enable_logging', $loggingEnabled ? 1 : 0);
        update_option('mamba_log_level', $logLevel);
        update_option('mamba_log_retention_days', $retentionDays);
        
        Logger::info('Log settings updated', [
            'debug_mode' => $debugMode,
            'logging_enabled' => $loggingEnabled,
            'log_level' => $logLevel,
            'retention_days' => $retentionDays,
        ]);
        
        wp_send_json_success(['message' => __('Settings saved', 'mamba-cache-for-woocommerce')]);
    }
    
    /**
     * Cron: Cleanup old logs
     */
    public function cleanupLogs(): void {
        $logger = Logger::getInstance();
        $deleted = $logger->cleanup();
        
        if ($deleted > 0) {
            Logger::info('Automatic log cleanup', ['files_deleted' => $deleted]);
        }
    }
}
