<?php
/**
 * Name: Quick Debug Toggle
 * Description: Quickly enable or disable WordPress debugging mode from admin panel without editing wp-config.php file for instant troubleshooting and error logging control
 * Category: Utilities
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Add Useful Functionality",
 *     "description": "Extend WordPress with helpful tools that make site management easier."
 *   },
 *   {
 *     "title": "Save Time",
 *     "description": "Automate or simplify tasks that would otherwise require manual work or additional tools."
 *   }
 * ]
 * Added: 2025-10-11
 * Tags: debug, development, errors, logging, troubleshooting
 * WhereToFind: {
 *   "location": "Debug Log File",
 *   "url": "",
 *   "instructions": "When enabled, errors are logged to wp-content/debug.log. Use for troubleshooting PHP errors and warnings during development.",
 *   "newTab": false
 * }
 */

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

class SwitchboardQuickDebugToggle {
    
    public function __construct() {
        add_action('wp_ajax_switchboard_toggle_debug', [$this, 'ajax_toggle_debug']);
    }

    /**
     * Register data locations for this module
     */
    public function register_data_locations() {
        return [
            'options' => [
                // This module modifies wp-config.php, not database options
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => []
        ];
    }
    
    public function get_debug_status() {
        // Check wp-config.php directly to see what's actually defined
        $wp_config = ABSPATH . 'wp-config.php';
        $config_content = file_exists($wp_config) ? file_get_contents($wp_config) : '';
        
        $explicitly_set = [
            'WP_DEBUG' => preg_match("/define\s*\(\s*['\"]WP_DEBUG['\"]\s*,\s*true\s*\)/i", $config_content),
            'WP_DEBUG_LOG' => preg_match("/define\s*\(\s*['\"]WP_DEBUG_LOG['\"]\s*,\s*true\s*\)/i", $config_content),
            'WP_DEBUG_DISPLAY' => preg_match("/define\s*\(\s*['\"]WP_DEBUG_DISPLAY['\"]\s*,\s*(true|false)\s*\)/i", $config_content)
        ];
        
        // For WP_DEBUG_DISPLAY, check if it's explicitly set to false
        $display_explicitly_false = preg_match("/define\s*\(\s*['\"]WP_DEBUG_DISPLAY['\"]\s*,\s*false\s*\)/i", $config_content);
        
        // WP_DEBUG_DISPLAY defaults to WP_DEBUG value if not explicitly set
        $debug_display_value = defined('WP_DEBUG_DISPLAY') ? WP_DEBUG_DISPLAY : (defined('WP_DEBUG') && WP_DEBUG);
        
        // But if explicitly set to false in config, show as disabled
        if ($display_explicitly_false) {
            $debug_display_value = false;
        }
        
        return [
            'WP_DEBUG' => defined('WP_DEBUG') && WP_DEBUG,
            'WP_DEBUG_LOG' => defined('WP_DEBUG_LOG') && WP_DEBUG_LOG,
            'WP_DEBUG_DISPLAY' => $debug_display_value,
            'explicitly_set' => $explicitly_set
        ];
    }
    
    public function render_settings() {
        $status = $this->get_debug_status();
        $log_file = WP_CONTENT_DIR . '/debug.log';
        $log_exists = file_exists($log_file);
        $log_size = $log_exists ? size_format(filesize($log_file)) : '0 B';
        
        ?>
        <input type="hidden" name="module" value="quick-debug-toggle">
        
        <?php 
        $explicitly_set = isset($status['explicitly_set']) ? $status['explicitly_set'] : [];
        unset($status['explicitly_set']);
        
        $constant_descriptions = [
            'WP_DEBUG' => 'Master switch for debug mode',
            'WP_DEBUG_LOG' => 'Log errors to wp-content/debug.log',
            'WP_DEBUG_DISPLAY' => 'Display errors on screen (not recommended for production)'
        ];
        ?>
        
        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading"><?php esc_html_e('Quick Debug Toggle', 'wpswitchboard'); ?></h3>
            <p class="sb-sp-description"><?php esc_html_e('Quickly enable or disable WordPress debug mode. Toggle debug constants individually or use automatic mode to modify wp-config.php directly.', 'wpswitchboard'); ?></p>
        </div>

        <?php if ($log_exists): ?>
        <div class="sb-sp-card sb-sp-p-4" style="margin-bottom: 24px;">
            <div class="sb-sp-flex sb-sp-items-center sb-sp-justify-between sb-sp-mb-3">
                <div>
                    <h4 class="sb-sp-heading-sm"><?php esc_html_e('Debug Log', 'wpswitchboard'); ?></h4>
                    <p class="sb-sp-description" style="margin: 0;"><?php
                    // translators: %s is the debug log file size (e.g., "2.5 MB")
                    printf(esc_html__('Current log size: %s', 'wpswitchboard'), '<code>' . esc_html($log_size) . '</code>'); ?></p>
                </div>
                <div class="sb-sp-button-group" style="gap: 8px;">
                    <a href="<?php echo esc_url(content_url('debug.log')); ?>" target="_blank" class="button button-secondary button-small">
                        <span class="dashicons dashicons-visibility" style="margin-top: 3px;"></span> <?php esc_html_e('View Log', 'wpswitchboard'); ?>
                    </a>
                    <button type="button" id="clear-log-btn" class="button button-small">
                        <span class="dashicons dashicons-trash" style="margin-top: 3px;"></span> <?php esc_html_e('Clear Log', 'wpswitchboard'); ?>
                    </button>
                </div>
            </div>
        </div>
        <?php endif; ?>
                    
        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('Current Debug Status', 'wpswitchboard'); ?></h4>
            <p class="sb-sp-description"><?php esc_html_e('Current status of WordPress debug constants', 'wpswitchboard'); ?></p>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <?php 
            $can_modify = $this->can_modify_wp_config();
            foreach ($status as $constant => $enabled):
                $is_explicit = isset($explicitly_set[$constant]) && $explicitly_set[$constant];
            ?>
            <div class="sb-sp-card sb-sp-p-4" style="margin-bottom: 12px;">
                <div class="sb-sp-flex sb-sp-items-center sb-sp-justify-between">
                    <div style="flex: 1;">
                        <div class="sb-sp-text-semibold" style="margin-bottom: 4px;">
                            <code style="background: #f3f4f6; padding: 2px 6px; border-radius: 4px; font-size: 13px;"><?php echo esc_html($constant); ?></code>
                            <?php if (!$is_explicit && $enabled): ?>
                                <span class="sb-sp-text-xs" style="color: #64748b;"> (inherited from WP_DEBUG)</span>
                            <?php endif; ?>
                        </div>
                        <div class="sb-sp-text-sm" style="color: #64748b;">
                            <?php echo esc_html($constant_descriptions[$constant]); ?>
                        </div>
                    </div>
                    <div class="sb-sp-flex sb-sp-items-center sb-sp-gap-2">
                        <span class="sb-sp-badge" style="background: <?php echo $enabled ? '#dcfce7' : '#f3f4f6'; ?>; color: <?php echo $enabled ? '#166534' : '#64748b'; ?>; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 500;">
                            <?php echo $enabled ? 'ON' : 'OFF'; ?>
                        </span>
                        <?php if ($can_modify): ?>
                            <button type="button"
                                    class="button button-small toggle-constant-btn"
                                    data-constant="<?php echo esc_attr($constant); ?>"
                                    data-action="<?php echo $enabled ? 'disable' : 'enable'; ?>"
                                    style="<?php echo $enabled ? 'background: #fee2e2; color: #991b1b; border-color: #fee2e2;' : 'background: #dbeafe; color: #1e40af; border-color: #dbeafe;'; ?>">
                                <?php echo $enabled ? 'Disable' : 'Enable'; ?>
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        
        <?php if (!$can_modify): ?>
        <div class="sb-sp-info-box sb-sp-info-box-tip" style="margin-bottom: 24px;">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('Cannot Modify Constants', 'wpswitchboard'); ?></h4>
            <p class="sb-sp-description" style="margin: 0;"><?php esc_html_e('wp-config.php is not writable. You can still view the current status above, but automatic toggling is disabled.', 'wpswitchboard'); ?></p>
        </div>
        <?php endif; ?>
        
        <?php 
        $can_modify = $this->can_modify_wp_config();
        $is_debug_enabled = $status['WP_DEBUG'];
        ?>
        
        <div class="sb-sp-divider" style="margin: 24px 0;"></div>

        <!-- Option 1: Automatic (Risky) -->
        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('Option 1: Automatic Toggle', 'wpswitchboard'); ?></h4>
            <p class="sb-sp-description"><?php esc_html_e('Automatically modify wp-config.php to enable/disable debug mode. Use with caution!', 'wpswitchboard'); ?></p>
            
            <?php if ($can_modify): ?>
                <div class="sb-sp-info-box sb-sp-info-box-tip" style="margin-bottom: 16px;">
                    <h4 class="sb-sp-heading-sm"><?php esc_html_e('Warning', 'wpswitchboard'); ?></h4>
                    <ul class="sb-sp-list">
                        <li class="sb-sp-list-item"><?php esc_html_e('This will directly modify your wp-config.php file', 'wpswitchboard'); ?></li>
                        <li class="sb-sp-list-item"><?php esc_html_e('A backup will be created automatically', 'wpswitchboard'); ?></li>
                        <li class="sb-sp-list-item"><?php esc_html_e('Could break your site if something goes wrong', 'wpswitchboard'); ?></li>
                        <li class="sb-sp-list-item"><?php esc_html_e('Only use on development/staging sites', 'wpswitchboard'); ?></li>
                        <li class="sb-sp-list-item"><?php esc_html_e('Make sure you have FTP/SSH access as backup', 'wpswitchboard'); ?></li>
                    </ul>
                </div>

                <div class="sb-sp-button-group" style="justify-content: flex-start;">
                    <?php if ($is_debug_enabled): ?>
                        <button type="button" id="disable-debug-btn" class="button button-small" style="background: #dc2626; color: white; border-color: #dc2626;">
                            <span class="dashicons dashicons-dismiss" style="margin-top: 3px;"></span> <?php esc_html_e('Disable Debug Mode', 'wpswitchboard'); ?>
                        </button>
                    <?php else: ?>
                        <button type="button" id="enable-debug-btn" class="button button-primary button-small">
                            <span class="dashicons dashicons-yes-alt" style="margin-top: 3px;"></span> <?php esc_html_e('Enable Debug Mode', 'wpswitchboard'); ?>
                        </button>
                    <?php endif; ?>
                </div>

                <div id="auto-result" style="display: none; margin-top: 16px;"></div>
            <?php else: ?>
                <div class="sb-sp-info-box sb-sp-info-box-info">
                    <h4 class="sb-sp-heading-sm"><?php esc_html_e('Cannot Modify wp-config.php', 'wpswitchboard'); ?></h4>
                    <p class="sb-sp-description" style="margin: 0;"><?php esc_html_e('File is not writable or doesn\'t exist. File permissions need to be changed to use this option.', 'wpswitchboard'); ?></p>
                </div>
            <?php endif; ?>
        </div>
        
        <div class="sb-sp-divider" style="margin: 24px 0;"></div>

        <!-- Option 2: Manual (Safe) -->
        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('Option 2: Manual Instructions (Recommended)', 'wpswitchboard'); ?></h4>
            <p class="sb-sp-description"><?php esc_html_e('Safely add debug constants to wp-config.php manually. Recommended for production sites.', 'wpswitchboard'); ?></p>
            
            <p class="sb-sp-description" style="margin-bottom: 12px;"><?php esc_html_e('Add these lines to your wp-config.php file before', 'wpswitchboard'); ?> <code>/* That's all, stop editing! */</code>:</p>

            <div class="sb-sp-card sb-sp-p-4" style="position: relative;">
                <button type="button" id="copy-code-btn" class="button button-small button-secondary" style="position: absolute; top: 12px; right: 12px;">
                    <span class="dashicons dashicons-admin-page" style="margin-top: 3px;"></span> <?php esc_html_e('Copy', 'wpswitchboard'); ?>
                </button>
                <div id="debug-code" style="font-family: 'Courier New', monospace; font-size: 13px; color: #111827; white-space: pre-wrap; word-break: break-all; padding-right: 100px;">
// Enable debugging
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
@ini_set('display_errors', 0);
                </div>
            </div>

            <p class="sb-sp-description" style="margin-top: 12px; margin-bottom: 0;"><strong><?php esc_html_e('To disable:', 'wpswitchboard'); ?></strong> <?php esc_html_e('Simply remove or comment out these lines.', 'wpswitchboard'); ?></p>
        </div>
        
        <script>
        jQuery(document).ready(function($) {
            // Clear log
            $('#clear-log-btn').on('click', function() {
                if (!confirm('Are you sure you want to clear the debug log?')) {
                    return;
                }

                const $btn = $(this);
                $btn.prop('disabled', true).html('<span class="dashicons dashicons-update" style="animation: spin 1s linear infinite; margin-top: 3px;"></span> Clearing...');

                $.post(ajaxurl, {
                    action: 'switchboard_toggle_debug',
                    operation: 'clear_log',
                    nonce: '<?php echo esc_attr(wp_create_nonce('debug_toggle')); ?>'
                }, function(response) {
                    if (response.success) {
                        // Update the UI to show 0 B without page reload
                        $btn.closest('div').find('code').text('0 B');
                        $btn.html('<span class="dashicons dashicons-yes-alt" style="margin-top: 3px;"></span> Cleared').prop('disabled', false);
                        setTimeout(function() {
                            $btn.html('<span class="dashicons dashicons-trash" style="margin-top: 3px;"></span> Clear Log');
                        }, 2000);
                    } else {
                        alert('Error: ' + response.data);
                        $btn.prop('disabled', false).html('<span class="dashicons dashicons-trash" style="margin-top: 3px;"></span> Clear Log');
                    }
                });
            });
            
            // Enable debug (risky)
            $('#enable-debug-btn').on('click', function() {
                if (!confirm('WARNING: This will modify your wp-config.php file.\n\nA backup will be created, but this could break your site.\n\nAre you sure you want to continue?')) {
                    return;
                }

                const $btn = $(this);
                $btn.prop('disabled', true).html('<span class="dashicons dashicons-update" style="animation: spin 1s linear infinite; margin-top: 3px;"></span> Enabling...');

                $.post(ajaxurl, {
                    action: 'switchboard_toggle_debug',
                    operation: 'enable_debug',
                    nonce: '<?php echo esc_attr(wp_create_nonce('debug_toggle')); ?>'
                }, function(response) {
                    if (response.success) {
                        $('#auto-result').html('<div class="sb-sp-info-box sb-sp-info-box-success"><h4 class="sb-sp-heading-sm">Success!</h4><p class="sb-sp-description" style="margin: 0;">Debug mode enabled. Backup saved at: <code>' + response.data.backup + '</code></p></div>').show();

                        // Update all constant badges to ON without page reload
                        $('.toggle-constant-btn').each(function() {
                            const $constBtn = $(this);
                            const $badge = $constBtn.prev('span');
                            $badge.css({background: '#00a32a', color: 'white'}).text('ON');
                            $constBtn.text('Disable').data('action', 'disable');
                        });

                        // Update the main button
                        $btn.remove();
                        $btn.closest('div').prepend('<button type="button" id="disable-debug-btn" class="button button-small" style="background: #dc2626; color: white; border-color: #dc2626;"><span class="dashicons dashicons-dismiss" style="margin-top: 3px;"></span> Disable Debug Mode</button>');
                    } else {
                        $('#auto-result').html('<div class="sb-sp-alert sb-sp-alert-error"><p><strong>Error:</strong> ' + response.data + '</p></div>').show();
                        $btn.prop('disabled', false).html('<span class="dashicons dashicons-yes-alt" style="margin-top: 3px;"></span> Enable Debug Mode');
                    }
                });
            });
            
            // Disable debug (risky) - Use event delegation since button is dynamically created
            $(document).on('click', '#disable-debug-btn', function() {
                if (!confirm('This will modify your wp-config.php file to disable debug mode.\n\nContinue?')) {
                    return;
                }

                const $btn = $(this);
                $btn.prop('disabled', true).html('<span class="dashicons dashicons-update" style="animation: spin 1s linear infinite; margin-top: 3px;"></span> Disabling...');

                $.post(ajaxurl, {
                    action: 'switchboard_toggle_debug',
                    operation: 'disable_debug',
                    nonce: '<?php echo esc_attr(wp_create_nonce('debug_toggle')); ?>'
                }, function(response) {
                    if (response.success) {
                        $('#auto-result').html('<div class="sb-sp-info-box sb-sp-info-box-success"><h4 class="sb-sp-heading-sm">Success!</h4><p class="sb-sp-description" style="margin: 0;">Debug mode disabled.</p></div>').show();

                        // Update all constant badges to OFF without page reload
                        $('.toggle-constant-btn').each(function() {
                            const $constBtn = $(this);
                            const $badge = $constBtn.prev('span');
                            $badge.css({background: '#dcdcde', color: '#646970'}).text('OFF');
                            $constBtn.text('Enable').data('action', 'enable');
                        });

                        // Update the main button
                        $btn.remove();
                        $btn.closest('div').prepend('<button type="button" id="enable-debug-btn" class="button button-primary button-small"><span class="dashicons dashicons-yes-alt" style="margin-top: 3px;"></span> Enable Debug Mode</button>');
                    } else {
                        $('#auto-result').html('<div class="sb-sp-alert sb-sp-alert-error"><p><strong>Error:</strong> ' + response.data + '</p></div>').show();
                        $btn.prop('disabled', false).html('<span class="dashicons dashicons-dismiss" style="margin-top: 3px;"></span> Disable Debug Mode');
                    }
                });
            });
            
            // Toggle individual constant
            $(document).on('click', '.toggle-constant-btn', function() {
                const btn = $(this);
                const constant = btn.data('constant');
                const action = btn.data('action');
                const actionText = action === 'enable' ? 'enable' : 'disable';

                if (!confirm('This will modify wp-config.php to ' + actionText + ' ' + constant + '.\n\nContinue?')) {
                    return;
                }

                btn.prop('disabled', true).text('Working...');

                $.post(ajaxurl, {
                    action: 'switchboard_toggle_debug',
                    operation: 'toggle_constant',
                    constant: constant,
                    action_type: action,
                    nonce: '<?php echo esc_attr(wp_create_nonce('debug_toggle')); ?>'
                }, function(response) {
                    if (response.success) {
                        // Update the badge and button without page reload
                        const $badge = btn.prev('span');
                        if (action === 'enable') {
                            $badge.css({background: '#00a32a', color: 'white'}).text('ON');
                            btn.text('Disable').data('action', 'disable');
                        } else {
                            $badge.css({background: '#dcdcde', color: '#646970'}).text('OFF');
                            btn.text('Enable').data('action', 'enable');
                        }
                        btn.prop('disabled', false);
                    } else {
                        alert('Error: ' + response.data);
                        btn.prop('disabled', false).text(action === 'enable' ? 'Enable' : 'Disable');
                    }
                });
            });
            
            // Copy code
            $('#copy-code-btn').on('click', function() {
                const code = `// Enable debugging
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
@ini_set('display_errors', 0);`;
                
                navigator.clipboard.writeText(code).then(function() {
                    $('#copy-code-btn').text('Copied!');
                    setTimeout(function() {
                        $('#copy-code-btn').text('Copy');
                    }, 2000);
                });
            });
        });
        </script>
        <?php
    }
    
    private function can_modify_wp_config() {
        $wp_config = ABSPATH . 'wp-config.php';
        return file_exists($wp_config) && is_writable($wp_config); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
    }
    
    private function toggle_constant($constant, $enable) {
        $wp_config = ABSPATH . 'wp-config.php';
        
        if (!$this->can_modify_wp_config()) {
            return ['success' => false, 'message' => 'wp-config.php is not writable'];
        }
        
        // Backup first
        $backup = $wp_config . '.backup-' . time();
        if (!copy($wp_config, $backup)) {
            return ['success' => false, 'message' => 'Could not create backup'];
        }
        
        $content = file_get_contents($wp_config);
        
        // Remove existing definition of this constant
        $patterns = [
            "/define\s*\(\s*['\"]" . $constant . "['\"]\s*,\s*(true|false)\s*\)\s*;?\s*/i",
        ];
        
        foreach ($patterns as $pattern) {
            $content = preg_replace($pattern, '', $content);
        }
        
        if ($enable) {
            // Add the constant before "That's all"
            $new_line = "define('" . $constant . "', true);\n";
            
            $content = str_replace(
                "/* That's all, stop editing!",
                $new_line . "/* That's all, stop editing!",
                $content
            );
        } else {
            // When disabling, explicitly set to false (important for WP_DEBUG_DISPLAY)
            $new_line = "define('" . $constant . "', false);\n";
            
            $content = str_replace(
                "/* That's all, stop editing!",
                $new_line . "/* That's all, stop editing!",
                $content
            );
        }
        
        // Clean up multiple blank lines
        $content = preg_replace("/\n{3,}/", "\n\n", $content);
        
        if (file_put_contents($wp_config, $content) === false) {
            copy($backup, $wp_config);
            return ['success' => false, 'message' => 'Could not write to wp-config.php'];
        }
        
        return ['success' => true, 'message' => $constant . ' ' . ($enable ? 'enabled' : 'disabled'), 'backup' => $backup];
    }
    
    private function modify_wp_config($enable = true) {
        $wp_config = ABSPATH . 'wp-config.php';
        
        if (!$this->can_modify_wp_config()) {
            return ['success' => false, 'message' => 'wp-config.php is not writable'];
        }
        
        // Backup first
        $backup = $wp_config . '.backup-' . time();
        if (!copy($wp_config, $backup)) {
            return ['success' => false, 'message' => 'Could not create backup'];
        }
        
        $content = file_get_contents($wp_config);
        
        $marker_start = '// BEGIN Switchboard Debug Mode';
        $marker_end = '// END Switchboard Debug Mode';
        
        // Remove existing Switchboard debug config (with markers)
        $pattern = '/' . preg_quote($marker_start, '/') . '.*?' . preg_quote($marker_end, '/') . '\s*/s';
        $content = preg_replace($pattern, '', $content);
        
        // Also try to remove common manual debug configurations
        if (!$enable) {
            // Remove common debug define patterns (be careful to only remove debug-related ones)
            $debug_patterns = [
                "/define\s*\(\s*['\"]WP_DEBUG['\"]\s*,\s*true\s*\)\s*;?\s*/i",
                "/define\s*\(\s*['\"]WP_DEBUG_LOG['\"]\s*,\s*true\s*\)\s*;?\s*/i",
                "/define\s*\(\s*['\"]WP_DEBUG_DISPLAY['\"]\s*,\s*(true|false)\s*\)\s*;?\s*/i",
                "/@ini_set\s*\(\s*['\"]display_errors['\"]\s*,\s*[01]\s*\)\s*;?\s*/i",
            ];
            
            foreach ($debug_patterns as $pattern) {
                $content = preg_replace($pattern, '', $content);
            }
            
            // Remove any debug-related comments
            $content = preg_replace("/\/\/\s*(Enable|Disable)?\s*debug(ging)?\s*\n/i", '', $content);
            
            // Clean up multiple blank lines
            $content = preg_replace("/\n{3,}/", "\n\n", $content);
        }
        
        if ($enable) {
            // Add debug config before "That's all"
            $debug_config = "\n" . $marker_start . "\n";
            $debug_config .= "define('WP_DEBUG', true);\n";
            $debug_config .= "define('WP_DEBUG_LOG', true);\n";
            $debug_config .= "define('WP_DEBUG_DISPLAY', false);\n";
            $debug_config .= "@ini_set('display_errors', 0);\n";
            $debug_config .= $marker_end . "\n";
            
            $content = str_replace(
                "/* That's all, stop editing!",
                $debug_config . "/* That's all, stop editing!",
                $content
            );
        }
        
        if (file_put_contents($wp_config, $content) === false) {
            // Restore backup
            copy($backup, $wp_config);
            return ['success' => false, 'message' => 'Could not write to wp-config.php'];
        }
        
        return ['success' => true, 'message' => 'Debug mode ' . ($enable ? 'enabled' : 'disabled'), 'backup' => $backup];
    }
    
    public function ajax_toggle_debug() {
        check_ajax_referer('debug_toggle', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(esc_html__('Unauthorized', 'wpswitchboard'));
        }
        
        $operation = isset($_POST['operation']) ? sanitize_key(wp_unslash($_POST['operation'])) : '';
        
        if ($operation === 'clear_log') {
            $log_file = WP_CONTENT_DIR . '/debug.log';
            if (file_exists($log_file)) {
                file_put_contents($log_file, '');
                wp_send_json_success(esc_html__('Log cleared', 'wpswitchboard'));
            } else {
                wp_send_json_error(esc_html__('Log file not found', 'wpswitchboard'));
            }
        }
        
        if ($operation === 'enable_debug' || $operation === 'disable_debug') {
            $enable = $operation === 'enable_debug';
            $result = $this->modify_wp_config($enable);
            
            if ($result['success']) {
                wp_send_json_success($result);
            } else {
                wp_send_json_error($result['message']);
            }
        }
        
        if ($operation === 'toggle_constant') {
            $constant = isset($_POST['constant']) ? sanitize_text_field(wp_unslash($_POST['constant'])) : ''; // Don't use sanitize_key - it removes underscores!
            $action = isset($_POST['action_type']) ? sanitize_key(wp_unslash($_POST['action_type'])) : '';
            
            $allowed_constants = ['WP_DEBUG', 'WP_DEBUG_LOG', 'WP_DEBUG_DISPLAY'];
            if (!in_array($constant, $allowed_constants)) {
                // translators: %s is the name of the invalid WordPress constant
                wp_send_json_error(sprintf(esc_html__('Invalid constant: %s', 'wpswitchboard'), $constant));
            }
            
            $enable = $action === 'enable';
            $result = $this->toggle_constant($constant, $enable);
            
            if ($result['success']) {
                wp_send_json_success($result);
            } else {
                wp_send_json_error($result['message']);
            }
        }


        wp_send_json_error(esc_html__('Invalid operation', 'wpswitchboard'));
    }
}

// Initialize and register with data system
$switchboard_instance = new SwitchboardQuickDebugToggle();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
