<?php
// IV1 WP Tools – Tools AJAX & Funktionen (Error Log, Cron, Options)
defined('ABSPATH') || exit;

/**
 * Ermittelt den Pfad zum WordPress Debug-Log.
 * Unterstützt WP_DEBUG_LOG als Pfad oder booleschen Wert.
 */
function iv1wpt_get_debug_log_path(): string {
    if (defined('WP_DEBUG_LOG') && is_string(WP_DEBUG_LOG) && WP_DEBUG_LOG !== '') {
        return WP_DEBUG_LOG;
    }
    return WP_CONTENT_DIR . '/debug.log';
}

/**
 * AJAX: Debug-Log laden (letzte N Zeilen, gefiltert).
 */
add_action('wp_ajax_iv1wpt_errorlog_load', 'iv1wpt_errorlog_load_ajax');
function iv1wpt_errorlog_load_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    $lines   = max(50, min(1000, (int) ($_POST['lines'] ?? 200)));
    $filter  = sanitize_text_field($_POST['filter'] ?? '');
    $logfile = iv1wpt_get_debug_log_path();

    if (!file_exists($logfile)) {
        wp_send_json_success([
            'lines'    => [],
            'total'    => 0,
            'filtered' => 0,
            'size'     => 0,
            'exists'   => false,
        ]);
    }

    $size    = filesize($logfile);
    $content = @file_get_contents($logfile);
    if ($content === false) {
        wp_send_json_error(__('Log file could not be read.', 'iv1-wp-tools'));
    }

    $all_lines = array_reverse(array_filter(explode("\n", $content), fn($l) => trim($l) !== ''));
    $total     = count($all_lines);

    // Filter anwenden
    if ($filter !== '') {
        $all_lines = array_values(array_filter($all_lines, fn($l) => stripos($l, $filter) !== false));
    }
    $filtered = count($all_lines);

    // Auf gewünschte Anzahl begrenzen
    $all_lines = array_slice($all_lines, 0, $lines);

    // Typ-Klassifizierung pro Zeile
    $classified = array_map(function ($line) {
        $type = 'info';
        if (stripos($line, 'fatal') !== false || stripos($line, 'uncaught') !== false) {
            $type = 'fatal';
        } elseif (stripos($line, 'error') !== false) {
            $type = 'error';
        } elseif (stripos($line, 'warning') !== false) {
            $type = 'warning';
        } elseif (stripos($line, 'notice') !== false || stripos($line, 'deprecated') !== false) {
            $type = 'notice';
        }
        return ['line' => $line, 'type' => $type];
    }, $all_lines);

    wp_send_json_success([
        'lines'    => $classified,
        'total'    => $total,
        'filtered' => $filtered,
        'size'     => $size,
        'exists'   => true,
        'path'     => $logfile,
    ]);
}

/**
 * AJAX: Debug-Log löschen.
 */
add_action('wp_ajax_iv1wpt_errorlog_clear', 'iv1wpt_errorlog_clear_ajax');
function iv1wpt_errorlog_clear_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    if (!iv1wpt_has_pro()) {
        wp_send_json_error(__('This feature requires IV1 WP Tools Pro.', 'iv1-wp-tools'));
    }

    $logfile = iv1wpt_get_debug_log_path();

    if (!file_exists($logfile)) {
        wp_send_json_error(__('Log file does not exist.', 'iv1-wp-tools'));
    }

    if (@file_put_contents($logfile, '') === false) {
        wp_send_json_error(__('Log file could not be cleared.', 'iv1-wp-tools'));
    }

    wp_send_json_success(['message' => __('Log file cleared.', 'iv1-wp-tools')]);
}

// ════════════════════════════════════════════════
// CRON JOBS
// ════════════════════════════════════════════════

/**
 * AJAX: Alle geplanten WP-Cron-Events laden.
 */
add_action('wp_ajax_iv1wpt_cron_list', 'iv1wpt_cron_list_ajax');
function iv1wpt_cron_list_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    $crons  = _get_cron_array();
    $events = [];

    if (!is_array($crons)) {
        wp_send_json_success(['events' => [], 'total' => 0]);
    }

    // Aktive Plugins für Zuordnung
    $active_plugins = (array) get_option('active_plugins', []);
    $plugin_names   = [];
    foreach ($active_plugins as $plugin_file) {
        $data = get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin_file, false, false);
        $slug = explode('/', $plugin_file)[0];
        $plugin_names[$slug] = $data['Name'] ?: $slug;
    }

    // WP-Core-Hooks
    $core_hooks = [
        'wp_version_check', 'wp_update_plugins', 'wp_update_themes',
        'wp_scheduled_delete', 'wp_scheduled_auto_draft_delete',
        'delete_expired_transients', 'wp_privacy_delete_old_export_files',
        'wp_site_health_scheduled_check', 'recovery_mode_clean_expired_keys',
        'do_pings', 'publish_future_post', 'importer_scheduled_cleanup',
        'wp_maybe_auto_update', 'wp_auto_updates_maybe_update',
        'update_network_counts', 'upgrader_scheduled_cleanup',
        'wp_https_detection', 'wp_update_user_counts',
    ];

    foreach ($crons as $timestamp => $hooks) {
        foreach ($hooks as $hook => $events_data) {
            foreach ($events_data as $key => $event) {
                $interval      = $event['interval'] ?? 0;
                $schedule_name = $event['schedule'] ?? '';

                // Schedule-Label ermitteln
                $schedule_label = $schedule_name;
                if ($interval > 0) {
                    $schedules = wp_get_schedules();
                    if (isset($schedules[$schedule_name])) {
                        $schedule_label = $schedules[$schedule_name]['display'];
                    }
                } elseif ($schedule_name === '') {
                    $schedule_label = __('Single event', 'iv1-wp-tools');
                }

                // Zuordnung: Core, Plugin oder Unbekannt
                $owner = __('Unknown', 'iv1-wp-tools');
                $owner_type = 'unknown';
                if (in_array($hook, $core_hooks, true) || str_starts_with($hook, 'wp_') || str_starts_with($hook, 'publish_') || str_starts_with($hook, 'do_')) {
                    $owner = 'WordPress Core';
                    $owner_type = 'core';
                } else {
                    foreach ($plugin_names as $slug => $name) {
                        if (stripos($hook, $slug) !== false || stripos($hook, str_replace('-', '_', $slug)) !== false) {
                            $owner = $name;
                            $owner_type = 'plugin';
                            break;
                        }
                    }
                }

                // Überfällig?
                $overdue = ($timestamp < time() && $schedule_name !== '');

                $events[] = [
                    'hook'           => $hook,
                    'timestamp'      => $timestamp,
                    'next_run'       => wp_date('d.m.Y H:i:s', $timestamp),
                    'schedule'       => $schedule_label,
                    'schedule_key'   => $schedule_name,
                    'interval'       => $interval,
                    'args'           => !empty($event['args']) ? $event['args'] : [],
                    'owner'          => $owner,
                    'owner_type'     => $owner_type,
                    'overdue'        => $overdue,
                    'key'            => $key,
                ];
            }
        }
    }

    // Sortieren: nächste zuerst
    usort($events, fn($a, $b) => $a['timestamp'] <=> $b['timestamp']);

    wp_send_json_success(['events' => $events, 'total' => count($events)]);
}

/**
 * AJAX: Einzelnen Cron-Event manuell auslösen.
 */
add_action('wp_ajax_iv1wpt_cron_run', 'iv1wpt_cron_run_ajax');
function iv1wpt_cron_run_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    if (!iv1wpt_has_pro()) {
        wp_send_json_error(__('This feature requires IV1 WP Tools Pro.', 'iv1-wp-tools'));
    }

    $hook = sanitize_text_field($_POST['hook'] ?? '');
    if ($hook === '') {
        wp_send_json_error(__('Invalid hook name.', 'iv1-wp-tools'));
    }

    // Nur existierende Hooks erlauben
    $crons = _get_cron_array();
    $found = false;
    $args  = [];
    foreach ($crons as $timestamp => $hooks) {
        if (isset($hooks[$hook])) {
            foreach ($hooks[$hook] as $event) {
                $args  = $event['args'] ?? [];
                $found = true;
                break 2;
            }
        }
    }

    if (!$found) {
        wp_send_json_error(__('Cron event not found.', 'iv1-wp-tools'));
    }

    do_action_ref_array($hook, $args);

    wp_send_json_success([
        'message' => sprintf(
            /* translators: %s: hook name */
            __('Hook "%s" executed.', 'iv1-wp-tools'),
            $hook
        ),
    ]);
}

/**
 * AJAX: Einzelnen Cron-Event löschen.
 */
add_action('wp_ajax_iv1wpt_cron_delete', 'iv1wpt_cron_delete_ajax');
function iv1wpt_cron_delete_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    if (!iv1wpt_has_pro()) {
        wp_send_json_error(__('This feature requires IV1 WP Tools Pro.', 'iv1-wp-tools'));
    }

    $hook      = sanitize_text_field($_POST['hook'] ?? '');
    $timestamp = (int) ($_POST['timestamp'] ?? 0);

    if ($hook === '' || $timestamp === 0) {
        wp_send_json_error(__('Invalid parameters.', 'iv1-wp-tools'));
    }

    $crons = _get_cron_array();
    if (!isset($crons[$timestamp][$hook])) {
        wp_send_json_error(__('Cron event not found.', 'iv1-wp-tools'));
    }

    // Core-Hooks schützen
    $core_hooks = [
        'wp_version_check', 'wp_update_plugins', 'wp_update_themes',
        'wp_scheduled_delete', 'delete_expired_transients',
        'wp_maybe_auto_update', 'wp_auto_updates_maybe_update',
    ];
    if (in_array($hook, $core_hooks, true)) {
        wp_send_json_error(__('WordPress Core events cannot be deleted.', 'iv1-wp-tools'));
    }

    wp_unschedule_event($timestamp, $hook);

    wp_send_json_success([
        'message' => sprintf(
            /* translators: %s: hook name */
            __('Event "%s" deleted.', 'iv1-wp-tools'),
            $hook
        ),
    ]);
}

// ════════════════════════════════════════════════
// OPTIONS CLEANUP
// ════════════════════════════════════════════════

/**
 * AJAX: wp_options scannen – Autoload-Analyse und verwaiste Optionen.
 */
add_action('wp_ajax_iv1wpt_options_scan', 'iv1wpt_options_scan_ajax');
function iv1wpt_options_scan_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    global $wpdb;

    $rows = $wpdb->get_results(
        "SELECT option_name, autoload, LENGTH(option_value) AS value_size
         FROM {$wpdb->options}
         ORDER BY value_size DESC",
        ARRAY_A
    );

    if (!is_array($rows)) {
        wp_send_json_error(__('Could not read options table.', 'iv1-wp-tools'));
    }

    $core_options   = iv1wpt_get_core_option_names();
    $plugin_map     = iv1wpt_get_option_plugin_map();
    $active_plugins = (array) get_option('active_plugins', []);

    // Plugin-Slugs der aktiven Plugins für Fallback-Matching
    $active_slugs = [];
    foreach ($active_plugins as $plugin_file) {
        $slug = explode('/', $plugin_file)[0];
        $active_slugs[] = $slug;
        $active_slugs[] = str_replace('-', '_', $slug);
    }

    $autoload_total_size = 0;
    $autoload_count      = 0;
    $total_size          = 0;
    $options             = [];

    foreach ($rows as $row) {
        $name     = $row['option_name'];
        $size     = (int) $row['value_size'];
        $autoload = ($row['autoload'] === 'yes' || $row['autoload'] === 'on');

        $total_size += $size;
        if ($autoload) {
            $autoload_total_size += $size;
            $autoload_count++;
        }

        $type  = 'unknown';
        $owner = '';

        // 1. Transients
        if (str_starts_with($name, '_transient_') || str_starts_with($name, '_site_transient_')) {
            $type = 'transient';

        // 2. WordPress Core
        } elseif (isset($core_options[$name])) {
            $type = 'core';
			$owner = 'WordPress Core';			
			

        // 3. Bekannte Plugin-Präfixe (plugin_map, längste zuerst)
        } else {
            foreach ($plugin_map as $prefix => $label) {
                if (str_starts_with($name, $prefix)) {
                    $type  = 'plugin';
                    $owner = $label;
                    break;
                }
            }

            // 4. Fallback: aktiver Plugin-Slug im Optionsnamen
            if ($type === 'unknown') {
                foreach ($active_slugs as $slug) {
                    if (strlen($slug) >= 4 && stripos($name, $slug) !== false) {
                        $type  = 'plugin';
                        $owner = $slug;
                        break;
                    }
                }
            }
        }

        // Nur relevante Einträge: autoload, groß (>10 KB) oder unbekannt
		if ($type != 'transient') {
			if ($autoload || $size > 10240 || $type === 'unknown') {
				$options[] = [
					'name'     => $name,
					'size'     => $size,
					'autoload' => $autoload,
					'type'     => $type,
					'owner'    => $owner,
				];
			}
		}	
    }

    wp_send_json_success([
        'options'             => $options,
        'total_options'       => count($rows),
        'autoload_count'      => $autoload_count,
        'autoload_total_size' => $autoload_total_size,
        'total_size'          => $total_size,
    ]);
}

/**
 * Bekannte Plugin-Optionspräfixe → Plugin-Name.
 * Längere Präfixe zuerst (spezifischerer Match gewinnt).
 */
function iv1wpt_get_option_plugin_map(): array {
    $map = [
        // WooCommerce
        'woocommerce_'              => 'WooCommerce',
        'wc_'                       => 'WooCommerce',
        // Yoast SEO
        'wpseo_'                    => 'Yoast SEO',
        'yoast_'                    => 'Yoast SEO',
        // Rank Math
        'rank_math_'                => 'Rank Math',
        // All in One SEO
        'aioseo_'                   => 'All in One SEO',
        // SEOPress
        'seopress_'                 => 'SEOPress',
        // Elementor
        'elementor_'                => 'Elementor',
        'elementor-'                => 'Elementor',
        // WP Rocket
        'wp_rocket_'                => 'WP Rocket',
        // W3 Total Cache
        'w3tc_'                     => 'W3 Total Cache',
        // LiteSpeed Cache
        'litespeed'                 => 'LiteSpeed Cache',
        // Wordfence
        'wordfence'                 => 'Wordfence',
        'wf_'                       => 'Wordfence',
        // Jetpack
        'jetpack_'                  => 'Jetpack',
        'jetpack-'                  => 'Jetpack',
        // Contact Form 7
        'wpcf7_'                    => 'Contact Form 7',
        // WPForms
        'wpforms_'                  => 'WPForms',
        // Gravity Forms
        'gform_'                    => 'Gravity Forms',
        // ACF
        'acf_'                      => 'Advanced Custom Fields',
        // UpdraftPlus
        'updraft_'                  => 'UpdraftPlus',
        'updraftplus_'              => 'UpdraftPlus',
        // Akismet
        'akismet_'                  => 'Akismet',
        // WP Mail SMTP
        'wp_mail_smtp'              => 'WP Mail SMTP',
        'wpmailsmtp_'               => 'WP Mail SMTP',
        // Post SMTP
        'postman_'                  => 'Post SMTP',
        'post_smtp_'                => 'Post SMTP',
        // MailPoet
        'mailpoet_'                 => 'MailPoet',
        // WPML
        'wpml_'                     => 'WPML',
        'icl_'                      => 'WPML',
        // Polylang
        'polylang'                  => 'Polylang',
        'pll_'                      => 'Polylang',
        // Complianz
        'cmplz_'                    => 'Complianz',
		'complianz_'                => 'Complianz',
		
        // WP Statistics
        'wps_'                      => 'WP Statistics',
        // MonsterInsights
        'monsterinsights_'          => 'MonsterInsights',
        // Solid Security / iThemes
        'itsec_'                    => 'Solid Security',
        // All In One WP Security
        'aiowps_'                   => 'All In One WP Security',
        // Redirection
        'redirection_'              => 'Redirection',
        // IV1 eigene Plugins
        'iv1_'                      => 'IV1 Plugin',
        'iv1wpt_'                   => 'IV1 WP Tools',
        'iv1_wp_tools_'             => 'IV1 WP Tools',
        // 2FA
        'iv1wpt_2fa_'               => 'IV1 WP Tools',

		'webpc_'                    => 'Converter for Media',	
		'dlm_'                      => 'Download Monitor',
		'__wpdm_'                   => 'Download Monitor',
		'_wpdm_'                    => 'Download Monitor',
		'wpdm_'                     => 'Download Monitor',
		
		// Enfold Theme (Avia Layout Builder)
		'av_alb_usage_'             => 'Enfold Theme',
		'av_'                       => 'Enfold Theme',
		'avia_'                     => 'Enfold Theme',
		'enfold_'                   => 'Enfold Theme',
		'theme_mods_enfold-child'   => 'Enfold Theme',
		'theme_mods_enfold'         => 'Enfold Theme',	
		'Enfold_version'            => 'Enfold Theme',
        'enfoldchild_'              => 'Enfold Theme',		

		'minify_'                   => 'WP Fastest Cache',		

		// Widget-Optionen von Plugins (nach Core-Check)
		'widget_wpdm_'              => 'WordPress Download Manager',
		
		'widget_avia_'              => 'Enfold Theme',
		'widget_newsbox'            => 'Enfold Theme',
		'widget_portfoliobox'       => 'Enfold Theme',
		
		
    ];

    // Längste Präfixe zuerst
    uksort($map, fn($a, $b) => strlen($b) <=> strlen($a));

    return $map;
}


// ════════════════════════════════════════════════
// DEBUG LOG TOGGLE (wp-config.php)
// ════════════════════════════════════════════════

/**
 * AJAX: Debug-Status aus wp-config.php lesen.
 */
add_action('wp_ajax_iv1wpt_debug_status', 'iv1wpt_debug_status_ajax');
function iv1wpt_debug_status_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    $config   = iv1wpt_read_wpconfig();
    $writable = $config !== null && is_writable(iv1wpt_wpconfig_path());

    wp_send_json_success([
        'wp_debug'           => defined('WP_DEBUG') && WP_DEBUG,
        'wp_debug_log'       => defined('WP_DEBUG_LOG') && WP_DEBUG_LOG,
        'wp_debug_display'   => defined('WP_DEBUG_DISPLAY') && WP_DEBUG_DISPLAY,
        'log_path'           => iv1wpt_get_debug_log_path(),
        'config_writable'    => $writable,
        'mu_plugin_active'   => file_exists(WPMU_PLUGIN_DIR . '/iv1-debug-log.php'),
        'config_in_file'     => $config !== null ? [
            'WP_DEBUG'         => iv1wpt_wpconfig_get_const($config, 'WP_DEBUG'),
            'WP_DEBUG_LOG'     => iv1wpt_wpconfig_get_const($config, 'WP_DEBUG_LOG'),
            'WP_DEBUG_DISPLAY' => iv1wpt_wpconfig_get_const($config, 'WP_DEBUG_DISPLAY'),
        ] : null,
    ]);
}

/**
 * AJAX: Debug-Konstanten in wp-config.php setzen.
 */
add_action('wp_ajax_iv1wpt_debug_toggle', 'iv1wpt_debug_toggle_ajax');
function iv1wpt_debug_toggle_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    if (!iv1wpt_has_pro()) {
        wp_send_json_error(__('This feature requires IV1 WP Tools Pro.', 'iv1-wp-tools'));
    }

    $enable = (bool) ($_POST['enable'] ?? false);
    $method = sanitize_text_field($_POST['method'] ?? 'config');

    // Methode 1: wp-config.php direkt bearbeiten
    if ($method === 'config') {
        $config = iv1wpt_read_wpconfig();
        if ($config === null) {
            wp_send_json_error(__('wp-config.php could not be read.', 'iv1-wp-tools'));
        }
        if (!is_writable(iv1wpt_wpconfig_path())) {
            wp_send_json_error(__('wp-config.php is not writable. Use the MU-Plugin method or edit manually.', 'iv1-wp-tools'));
        }

        $config = iv1wpt_wpconfig_set_const($config, 'WP_DEBUG', $enable ? 'true' : 'false');
        $config = iv1wpt_wpconfig_set_const($config, 'WP_DEBUG_LOG', $enable ? 'true' : 'false');
        $config = iv1wpt_wpconfig_set_const($config, 'WP_DEBUG_DISPLAY', 'false');

        if (file_put_contents(iv1wpt_wpconfig_path(), $config) === false) {
            wp_send_json_error(__('wp-config.php could not be written.', 'iv1-wp-tools'));
        }

        wp_send_json_success([
            'message' => $enable
                ? __('Debug logging enabled in wp-config.php. Reload the page to see the effect.', 'iv1-wp-tools')
                : __('Debug logging disabled in wp-config.php.', 'iv1-wp-tools'),
            'method'  => 'config',
        ]);
    }

    // Methode 2: MU-Plugin erstellen/löschen
    if ($method === 'muplugin') {
        $mu_file = WPMU_PLUGIN_DIR . '/iv1-debug-log.php';

        if ($enable) {
            wp_mkdir_p(WPMU_PLUGIN_DIR);
            $code  = "<?php";
            $code .= "// IV1 WP Tools – Debug Log (auto-generated, do not edit)";
            $code .= "if (!defined('WP_DEBUG_LOG')) {";
            $code .= "    define('WP_DEBUG_LOG', WP_CONTENT_DIR . '/debug.log');";
            $code .= "}";
            if (file_put_contents($mu_file, $code) === false) {
                wp_send_json_error(__('MU-Plugin could not be created. Check folder permissions.', 'iv1-wp-tools'));
            }
            wp_send_json_success([
                'message' => __('MU-Plugin created. WP_DEBUG_LOG is now active. Note: WP_DEBUG must still be set in wp-config.php for errors to be logged.', 'iv1-wp-tools'),
                'method'  => 'muplugin',
            ]);
        } else {
            if (file_exists($mu_file) && !unlink($mu_file)) {
                wp_send_json_error(__('MU-Plugin could not be deleted.', 'iv1-wp-tools'));
            }
            wp_send_json_success([
                'message' => __('MU-Plugin removed.', 'iv1-wp-tools'),
                'method'  => 'muplugin',
            ]);
        }
    }

    wp_send_json_error(__('Invalid method.', 'iv1-wp-tools'));
}

/**
 * Gibt den Pfad zur wp-config.php zurück.
 * Prüft auch eine Ebene über ABSPATH (Standard-Setup).
 */
function iv1wpt_wpconfig_path(): string {
    $path = ABSPATH . 'wp-config.php';
    if (!file_exists($path)) {
        $path = dirname(ABSPATH) . '/wp-config.php';
    }
    return $path;
}

/**
 * Liest wp-config.php als String.
 */
function iv1wpt_read_wpconfig(): ?string {
    $path = iv1wpt_wpconfig_path();
    if (!file_exists($path) || !is_readable($path)) {
        return null;
    }
    $content = file_get_contents($path);
    return $content !== false ? $content : null;
}

/**
 * Liest den Wert einer Konstante aus wp-config.php (als String).
 */
function iv1wpt_wpconfig_get_const(string $config, string $const): ?string {
    $pattern = '/define\s*\(\s*[\'"]' . preg_quote($const, '/') . '[\'"]\s*,\s*([^)]+)\)/i';
    if (preg_match($pattern, $config, $m)) {
        return trim($m[1]);
    }
    return null;
}

/**
 * Setzt oder ergänzt eine Konstante in wp-config.php.
 */
function iv1wpt_wpconfig_set_const(string $config, string $const, string $value): string {
    $pattern = '/define\s*\(\s*[\'"]' . preg_quote($const, '/') . '[\'"]\s*,\s*[^)]+\)/i';
    $replace  = "define('" . $const . "', " . $value . ")";

    if (preg_match($pattern, $config)) {
        return preg_replace($pattern, $replace, $config);
    }

    // Konstante noch nicht vorhanden – vor bekannten Markern einfügen
    $markers = [
        "/* That's all, stop editing!",
        '/** Sets up WordPress vars and included files.',
    ];
    foreach ($markers as $marker) {
        if (strpos($config, $marker) !== false) {
            return str_replace($marker, $replace . ";\n" . $marker, $config);
        }
    }

    // Fallback: ans Ende
    return $config . "\n" . $replace . ";\n";
}

/**
 * AJAX: Autoload-Status einer Option ändern.
 */
add_action('wp_ajax_iv1wpt_options_toggle_autoload', 'iv1wpt_options_toggle_autoload_ajax');
function iv1wpt_options_toggle_autoload_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    if (!iv1wpt_has_pro()) {
        wp_send_json_error(__('This feature requires IV1 WP Tools Pro.', 'iv1-wp-tools'));
    }

    global $wpdb;

    $name     = sanitize_text_field($_POST['option_name'] ?? '');
    $autoload = ($_POST['autoload'] ?? 'yes') === 'yes' ? 'yes' : 'no';

    if ($name === '') {
        wp_send_json_error(__('Invalid option name.', 'iv1-wp-tools'));
    }

    // Core-Optionen schützen
    $core = iv1wpt_get_core_option_names();
    if (isset($core[$name])) {
        wp_send_json_error(__('WordPress Core options cannot be modified.', 'iv1-wp-tools'));
    }

    $result = $wpdb->update(
        $wpdb->options,
        ['autoload' => $autoload],
        ['option_name' => $name],
        ['%s'],
        ['%s']
    );

    if ($result === false) {
        wp_send_json_error(__('Could not update option.', 'iv1-wp-tools'));
    }

    wp_cache_flush();

    wp_send_json_success([
        'message' => sprintf(
            /* translators: 1: option name, 2: autoload status */
            __('Option "%1$s" autoload set to "%2$s".', 'iv1-wp-tools'),
            $name,
            $autoload
        ),
        'autoload' => $autoload,
    ]);
}

/**
 * AJAX: Option löschen.
 */
add_action('wp_ajax_iv1wpt_options_delete', 'iv1wpt_options_delete_ajax');
function iv1wpt_options_delete_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    if (!iv1wpt_has_pro()) {
        wp_send_json_error(__('This feature requires IV1 WP Tools Pro.', 'iv1-wp-tools'));
    }

    $name = sanitize_text_field($_POST['option_name'] ?? '');

    if ($name === '') {
        wp_send_json_error(__('Invalid option name.', 'iv1-wp-tools'));
    }

    // Core-Optionen schützen
    $core = iv1wpt_get_core_option_names();
    if (isset($core[$name])) {
        wp_send_json_error(__('WordPress Core options cannot be deleted.', 'iv1-wp-tools'));
    }

    if (!delete_option($name)) {
        wp_send_json_error(__('Option could not be deleted.', 'iv1-wp-tools'));
    }

    wp_send_json_success([
        'message' => sprintf(
            /* translators: %s: option name */
            __('Option "%s" deleted.', 'iv1-wp-tools'),
            $name
        ),
    ]);
}

/**
 * Gibt bekannte WordPress-Core-Optionsnamen zurück.
 * Diese sind vor Löschung und Autoload-Änderung geschützt.
 */
function iv1wpt_get_core_option_names(): array {
    return array_flip([
        'siteurl', 'home', 'blogname', 'blogdescription', 'admin_email',
        'users_can_register', 'active_plugins', 'template', 'stylesheet',
        'db_version', 'wp_user_roles', 'initial_db_version',

        'permalink_structure', 'category_base', 'tag_base',
        'upload_path', 'upload_url_path', 'uploads_use_yearmonth_folders',

        'blog_charset', 'default_role', 'timezone_string', 'gmt_offset',
        'date_format', 'time_format', 'links_updated_date_format',
        'start_of_week',

        'posts_per_page', 'posts_per_rss', 'rss_use_excerpt',
        'default_category', 'default_email_category', 'default_link_category',
        'default_post_format',

        'default_comment_status', 'default_ping_status',
        'default_pingback_flag', 'comment_moderation',
        'comment_registration', 'thread_comments', 'thread_comments_depth',
        'page_comments', 'comments_per_page', 'default_comments_page',
        'comment_order', 'comments_notify', 'moderation_notify',
        'require_name_email', 'comment_max_links',
        'close_comments_for_old_posts', 'close_comments_days_old',
        'comment_previously_approved', 'show_comments_cookies_opt_in',
        'moderation_keys', 'disallowed_keys',

        'show_on_front', 'page_on_front', 'page_for_posts',
        'blog_public', 'WPLANG',

        'show_avatars', 'avatar_rating', 'avatar_default',

        'thumbnail_size_w', 'thumbnail_size_h', 'thumbnail_crop',
        'medium_size_w', 'medium_size_h',
        'medium_large_size_w', 'medium_large_size_h',
        'large_size_w', 'large_size_h',

        'image_default_link_type', 'image_default_size', 'image_default_align',

        'cron', 'rewrite_rules', 'sidebars_widgets',
        'sticky_posts', 'uninstall_plugins',

        'update_core', 'update_plugins', 'update_themes',
        'auto_update_core_dev', 'auto_update_core_minor', 'auto_update_core_major',
        'auto_plugin_theme_update_emails',

        'can_compress_scripts',
        'use_balanceTags', 'use_smilies', 'use_trackback',
        'mailserver_url', 'mailserver_login', 'mailserver_pass', 'mailserver_port',
        'ping_sites', 'hack_file', 'html_type',

        'link_manager_enabled',
        'finished_splitting_shared_terms',
        'site_icon',
        'wp_page_for_privacy_policy',
        'admin_email_lifespan',
        'wp_force_deactivated_plugins',
        'wp_attachment_pages_enabled',
        'wp_notes_notify',

        // Core-Widgets.
        'widget_block',
        'widget_calendar',
        'widget_search',
        'widget_recent-posts',
        'widget_recent-comments',
        'widget_archives',
        'widget_meta',
        'widget_pages',
        'widget_categories',
        'widget_text',
        'widget_rss',
        'widget_tag_cloud',
        'widget_nav_menu',
        'widget_custom_html',
        'widget_media_audio',
        'widget_media_gallery',
        'widget_media_image',
        'widget_media_video',
        'widget_recent_entries',
        'widget_recent_comments',
    ]);
}

function iv1wpt_is_protected_core_option(string $name): bool {
    $core = iv1wpt_get_core_option_names();

    if (isset($core[$name])) {
        return true;
    }

    $protected_prefixes = [
        'auto_update_core_',
        'widget_',
        '_site_transient_update_',
        '_transient_update_',
        '_site_transient_timeout_update_',
        '_transient_timeout_update_',
    ];

    foreach ($protected_prefixes as $prefix) {
        if (str_starts_with($name, $prefix)) {
            return true;
        }
    }

    return false;
}