<?php
/**
 * WAF Optimizer Controller
 * 
 * Centralized logic for WAF optimization operations
 * Handles creation of vmp-waf.php and .htaccess modification
 * 
 * @package VMPFence
 * @since 2.2.4
 */

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

class VMPFence_WAF_Optimizer {
    
    /**
     * Get server type (Apache, Nginx, LiteSpeed, etc.)
     * 
     * @return string Server type
     */
    public static function get_server_type() {
        $server_software = isset($_SERVER['SERVER_SOFTWARE']) ? strtolower($_SERVER['SERVER_SOFTWARE']) : '';
        
        if (strpos($server_software, 'apache') !== false) {
            return 'apache';
        } elseif (strpos($server_software, 'nginx') !== false) {
            return 'nginx';
        } elseif (strpos($server_software, 'litespeed') !== false) {
            return 'litespeed';
        }
        return 'unknown';
    }
    
    /**
     * Detect if WordPress is installed in a subdirectory
     * 
     * @return bool True if subdirectory installation
     */
    public static function detect_subdirectory_install() {
        $abspath = ABSPATH;
        $home_url = home_url();
        
        // Parse home URL to get path
        $parsed_url = parse_url($home_url);
        $path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
        
        // If path is not empty and not just '/', it's a subdirectory install
        $is_subdirectory = !empty($path) && $path !== '/';
        return $is_subdirectory;
    }
    
    /**
     * Check if current site is a multisite subsite
     * 
     * @return bool True if multisite subsite
     */
    public static function is_multisite_subsite() {
        if (!is_multisite()) {
            return false;
        }
        
        $is_subsite = !is_main_site();        
        return $is_subsite;
    }
    
    /**
     * Get current optimization status
     * 
     * @return array Status information
     */
    public static function get_optimization_status() {
        $waf_file_path = self::get_waf_file_path();
        $waf_file_exists = file_exists($waf_file_path);
        $htaccess_optimized = VMPFence_HTAccess_Manager::waf_optimization_exists();
        
        // Get protection level from config
        $protection_level = VMPFence_Config::get('waf_protection_level', 'basic');
        
        $status = array(
            'optimized' => $waf_file_exists && $htaccess_optimized,
            'waf_file_exists' => $waf_file_exists,
            'htaccess_optimized' => $htaccess_optimized,
            'protection_level' => $protection_level,
            'server_type' => self::get_server_type(),
            'is_subdirectory' => self::detect_subdirectory_install(),
            'is_multisite_subsite' => self::is_multisite_subsite(),
            'waf_file_path' => $waf_file_path,
        );        
        return $status;
    }
    
    /**
     * Optimize firewall - Create vmp-waf.php and modify .htaccess
     * 
     * @return array Result with success status and message
     */
    public static function optimize_firewall() {        
        // Pre-flight checks
        $server_type = self::get_server_type();
        if (!in_array($server_type, array('apache', 'litespeed'))) {
            return array(
                'success' => false,
                'message' => 'Your server (' . ucfirst($server_type) . ') does not support .htaccess. Auto-prepend optimization is not available.'
            );
        }
        
        // Check multisite subsite
        if (self::is_multisite_subsite()) {
            return array(
                'success' => false,
                'message' => 'WAF optimization can only be configured on the main site of a multisite network.'
            );
        }
        
        // Check file permissions
        if (!is_writable(ABSPATH)) {
            return array(
                'success' => false,
                'message' => 'Cannot write to WordPress root directory. Please check file permissions.'
            );
        }
        
        // Check if already optimized
        if (VMPFence_HTAccess_Manager::waf_optimization_exists()) {
            return array(
                'success' => false,
                'message' => 'WAF optimization is already active.'
            );
        }
        
        // Step 1: Generate WAF file
        $waf_result = self::generate_waf_file();
        if (!$waf_result['success']) {
            return $waf_result;
        }
        
        $waf_file_path = $waf_result['file_path'];
        
        // Step 2: Modify .htaccess
        $htaccess_result = VMPFence_HTAccess_Manager::add_waf_optimization($waf_file_path);
        
        if (is_wp_error($htaccess_result)) {
            // Rollback: Delete WAF file
            @unlink($waf_file_path);
            
            return array(
                'success' => false,
                'message' => $htaccess_result->get_error_message()
            );
        }
        
        
        // Step 3: Update protection level
        VMPFence_Config::set('waf_protection_level', 'extended');
                
        return array(
            'success' => true,
            'message' => 'WAF optimization completed successfully.',
            'waf_file_path' => $waf_file_path
        );
    }
    
    /**
     * Remove optimization - Restore .htaccess and delete vmp-waf.php
     * 
     * @return array Result with success status and message
     */
    public static function remove_optimization() {        
        $waf_file_path = self::get_waf_file_path();
        
        // Step 1: Remove .htaccess optimization
        $htaccess_result = VMPFence_HTAccess_Manager::remove_waf_optimization();
        
        if (!$htaccess_result) {
            return array(
                'success' => false,
                'message' => 'Failed to restore .htaccess. Please check file permissions.'
            );
        }
        
        // Step 2: Delete WAF file
        if (file_exists($waf_file_path)) {
            $delete_result = @unlink($waf_file_path);
        }
        
        // Step 3: Update protection level
        VMPFence_Config::set('waf_protection_level', 'basic');        
        
        return array(
            'success' => true,
            'message' => 'WAF optimization removed successfully.'
        );
    }
    
    /**
     * Generate WAF file from template
     * 
     * @return array Result with success status, message, and file path
     */
    public static function generate_waf_file() {        
        $template_path = VMPFENCE_PLUGIN_DIR . 'templates/vmp-waf-template.php';
        
        // Check if template exists
        if (!file_exists($template_path)) {
            return array(
                'success' => false,
                'message' => 'WAF template file not found.'
            );
        }
        
        // Read template
        $template_content = file_get_contents($template_path);
        if ($template_content === false) {
            return array(
                'success' => false,
                'message' => 'Failed to read WAF template file.'
            );
        }
                
        // Get dynamic values
        global $wpdb;
        $plugin_dir = VMPFENCE_PLUGIN_DIR;
        $abspath = ABSPATH;
        $table_prefix = $wpdb->prefix;
        
        // Replace placeholders
        $waf_content = str_replace(
            array('{PLUGIN_DIR}', '{ABSPATH}', '{TABLE_PREFIX}'),
            array($plugin_dir, $abspath, $table_prefix),
            $template_content
        );
        
        // Get target file path
        $waf_file_path = self::get_waf_file_path();
        
        // Write WAF file
        $write_result = file_put_contents($waf_file_path, $waf_content);
        
        if ($write_result === false) {
            return array(
                'success' => false,
                'message' => 'Failed to create WAF file. Check directory permissions.'
            );
        }
        
        return array(
            'success' => true,
            'message' => 'WAF file generated successfully.',
            'file_path' => $waf_file_path
        );
    }
    
    /**
     * Get absolute path to vmp-waf.php file
     * 
     * @return string Full path
     */
    public static function get_waf_file_path() {
        return ABSPATH . 'vmp-waf.php';
    }
}
