<?php
/**
 * VMPFence Disable Debug Mode AJAX Handler
 *
 * @package VMPFence
 * @since 2.1.0
 */

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

/**
 * Handle disable debug mode AJAX request
 */
function vmpfence_disable_debug_ajax() {
    // Verify nonce
    $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
    if (!wp_verify_nonce($nonce, 'vmpfence_scan_nonce')) {
        wp_send_json_error(['message' => 'Security check failed']);
        return;
    }
    
    // Check user capabilities
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => 'Insufficient permissions']);
        return;
    }
    
    // Get issue ID
    $issue_id = isset($_POST['issue_id']) ? intval($_POST['issue_id']) : 0;
    
    if (!$issue_id) {
        wp_send_json_error(['message' => 'Invalid issue ID']);
        return;
    }
    
    // Locate wp-config.php
    $config_file = ABSPATH . 'wp-config.php';
    
    // Check if wp-config.php exists
    if (!file_exists($config_file)) {
        wp_send_json_error(['message' => 'wp-config.php file not found']);
        return;
    }
    
    // Check if file is writable
    if (!is_writable($config_file)) {
        wp_send_json_error(['message' => 'wp-config.php is not writable. Please check file permissions.']);
        return;
    }
    
    // Read the current wp-config.php content
    $config_content = file_get_contents($config_file);
    
    if ($config_content === false) {
        wp_send_json_error(['message' => 'Failed to read wp-config.php']);
        return;
    }
    
    // Check if WP_DEBUG is set to true in the file content (not the runtime constant)
    // We need to check the file, not defined('WP_DEBUG'), because constants can't be redefined
    $debug_pattern = "/define\s*\(\s*['\"]WP_DEBUG['\"]\s*,\s*true\s*\)/i";
    if (!preg_match($debug_pattern, $config_content)) {
        wp_send_json_error(['message' => 'WP_DEBUG is not set to true in wp-config.php or not found']);
        return;
    }
    
    // Create backup of wp-config.php
    $backup_file = ABSPATH . 'wp-config-backup-' . date('Y-m-d-His') . '.php';
    if (file_put_contents($backup_file, $config_content) === false) {
        wp_send_json_error(['message' => 'Failed to create backup of wp-config.php']);
        return;
    }
    
    // Replace WP_DEBUG true with false using multiple patterns to catch different formatting
    $patterns = [
        // Pattern 1: define('WP_DEBUG', true); or define("WP_DEBUG", true);
        "/define\s*\(\s*['\"]WP_DEBUG['\"]\s*,\s*true\s*\)\s*;/i",
        // Pattern 2: Without semicolon for cases where it might be on next line
        "/define\s*\(\s*['\"]WP_DEBUG['\"]\s*,\s*true\s*\)/i",
    ];
    
    $replacement = "define('WP_DEBUG', false);";
    $modified = false;
    
    foreach ($patterns as $pattern) {
        if (preg_match($pattern, $config_content)) {
            $config_content = preg_replace($pattern, $replacement, $config_content);
            $modified = true;
            break;
        }
    }
    
    if (!$modified) {
        // Clean up backup file
        @unlink($backup_file);
        wp_send_json_error(['message' => 'Could not find WP_DEBUG definition to modify']);
        return;
    }
    
    // Write the modified content back to wp-config.php
    if (file_put_contents($config_file, $config_content) === false) {
        // Restore from backup
        file_put_contents($config_file, file_get_contents($backup_file));
        @unlink($backup_file);
        wp_send_json_error(['message' => 'Failed to write to wp-config.php. Backup restored.']);
        return;
    }
    
    // Now delete the issue from database since it's fixed
    global $wpdb;
    $issues_table = $wpdb->prefix . 'vmpfence_scan_issues';
    $scan_results_table = $wpdb->prefix . 'vmpfence_scan_results';
    
    // Get issue details before deletion
    // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    $issue = $wpdb->get_row($wpdb->prepare(
        "SELECT issue_type, scan_id FROM {$issues_table} WHERE id = %d",
        $issue_id
    ));
    // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    
    if ($issue) {
        // Get scan result info
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $scan_result = $wpdb->get_row($wpdb->prepare(
            "SELECT scan_type, issues_found FROM {$scan_results_table} WHERE id = %d",
            $issue->scan_id
        ));
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        
        // Delete the issue
        $wpdb->delete(
            $issues_table,
            ['id' => $issue_id],
            ['%d']
        );
        
        // Update issues_found count in scan_results
        if ($scan_result) {
            $new_issues_count = max(0, intval($scan_result->issues_found) - 1);
            $wpdb->update(
                $scan_results_table,
                ['issues_found' => $new_issues_count],
                ['id' => $issue->scan_id],
                ['%d'],
                ['%d']
            );
        }
    }
    
    // Get updated issue counts
    // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    $active_count = $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM {$issues_table} WHERE status = %s",
        'new'
    ));
    
    $ignored_count = $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM {$issues_table} WHERE status = %s",
        'ignored'
    ));
    // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    
    // Clean up backup file after successful modification
    @unlink($backup_file);
    
    wp_send_json_success([
        'message' => 'Debug mode has been successfully disabled',
        'active_count' => intval($active_count),
        'ignored_count' => intval($ignored_count),
        'backup_created' => basename($backup_file)
    ]);
}

// Register AJAX action (matches pattern in signature-sync-ajax.php)
add_action('wp_ajax_vmpfence_disable_debug', 'vmpfence_disable_debug_ajax');
add_action('wp_ajax_vmpfence_disable_debug', 'vmpfence_disable_debug_ajax');
