<?php
/**
 * Rate Limiting Initialization
 *
 * Loads rate limiting components and initializes the system.
 * Simplified version with only global rate limits.
 *
 * @package VMPFence
 * @since 2.0.0
 */

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

/**
 * Initialize rate limiting system
 *
 * @since 2.0.0
 * @return void
 */
function vmpfence_init_rate_limiting() {
    // Only initialize if rate limiting is enabled
    if (!VMPFence_Config::get('rate_limiting_enabled', 0)) {
        return;
    }

    // Load required classes
    require_once VMPFENCE_PLUGIN_DIR . '/firewall/models/class-rate-limiter.php';
    require_once VMPFENCE_PLUGIN_DIR . '/firewall/models/class-visitor-classifier.php';
    require_once VMPFENCE_PLUGIN_DIR . '/firewall/controllers/class-rate-limit-controller.php';
    require_once VMPFENCE_PLUGIN_DIR . '/firewall/ajax/class-rate-limit-ajax.php';

    // Initialize AJAX handler
    if (is_admin() && defined('DOING_AJAX') && DOING_AJAX) {
        new VMPFence_Rate_Limit_Ajax();
    }
    // Schedule cleanup cron job if not already scheduled
    if (!wp_next_scheduled('vmpfence_rate_limit_cleanup')) {
        wp_schedule_event(time(), 'hourly', 'vmpfence_rate_limit_cleanup');
    }
}

/**
 * Handle rate limiting cleanup cron job
 *
 * @since 2.0.0
 * @return void
 */
function vmpfence_rate_limit_cleanup() {
    require_once VMPFENCE_PLUGIN_DIR . '/firewall/models/class-rate-limiter.php';
    
    $rate_limiter = new VMPFence_Rate_Limiter();
    $deleted_count = $rate_limiter->trim_old_data();
    
}

/**
 * Display admin notice if rate limiting has issues
 *
 * @since 2.0.0
 * @return void
 */
function vmpfence_rate_limiting_admin_notices() {
    // Only show on VMPFence admin pages
    if (!isset($_GET['page']) || $_GET['page'] !== 'vmpfence-firewall') {
        return;
    }

    // Check if rate limiting is enabled but there are configuration issues
    if (VMPFence_Config::get('rate_limiting_enabled', 0)) {
        $global_limit = VMPFence_Config::get('global_rate_limit', 'unlimited');
        $global_action = VMPFence_Config::get('global_rate_action', 'throttle');
        
        // Check if global limit is set but action is missing
        if ($global_limit !== 'unlimited' && empty($global_action)) {
            ?>
            <div class="notice notice-warning is-dismissible">
                <p>
                    <strong>VMPFence Rate Limiting:</strong> 
                    Global rate limit is configured but no action is set. 
                    Please configure the rate limit action in the firewall settings.
                </p>
            </div>
            <?php
        }

        // Check if tables exist
        global $wpdb;
        $table_name = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_TRAFFIC_RATES);
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '{$table_name}'");
        
        if (!$table_exists) {
            ?>
            <div class="notice notice-error is-dismissible">
                <p>
                    <strong>VMPFence Rate Limiting:</strong> 
                    Required database table is missing. Please deactivate and reactivate the plugin.
                </p>
            </div>
            <?php
        }
    }
}

/**
 * Unschedule rate limiting cron jobs on plugin deactivation
 *
 * @since 2.0.0
 * @return void
 */
function vmpfence_rate_limiting_deactivate() {
    wp_clear_scheduled_hook('vmpfence_rate_limit_cleanup');
}

// Hook into WordPress
add_action('plugins_loaded', 'vmpfence_init_rate_limiting', 10);
add_action('vmpfence_rate_limit_cleanup', 'vmpfence_rate_limit_cleanup');
add_action('admin_notices', 'vmpfence_rate_limiting_admin_notices');

// Hook deactivation
register_deactivation_hook(VMPFENCE_PLUGIN_FILE, 'vmpfence_rate_limiting_deactivate');

/**
 * Get rate limiting instance for Bootstrap integration
 *
 * @since 2.0.0
 * @return VMPFence_Rate_Limit_Controller|null Controller instance or null if disabled
 */
function vmpfence_get_rate_limit_controller() {
    if (!VMPFence_Config::get('rate_limiting_enabled', 0)) {
        return null;
    }

    // Load required classes if not already loaded
    require_once VMPFENCE_PLUGIN_DIR . '/firewall/models/class-rate-limiter.php';
    require_once VMPFENCE_PLUGIN_DIR . '/firewall/controllers/class-rate-limit-controller.php';

    return new VMPFence_Rate_Limit_Controller();
}