<?php
// IV1 WP Tools – WP-Settings (Härtung & Optimierung)
defined('ABSPATH') || exit;

define('IV1WPT_WPSETTINGS_OPTION', 'iv1wpt_wp_settings');

function iv1wpt_wp_settings_pro_fields(): array {
    return [
        'limit_post_revisions',
		'disable_auto_update_emails',
		'remove_dashboard_welcome',
		'disable_rss',
		'disable_cf7_scripts',
		'disable_cf7_ptags',
		'disable_inline_scripts',
		'disable_text_copy',
		'disable_rest_api_public',
		'disable_xmlrpc'
    ];
}

function iv1wpt_default_wp_settings(): array {
    return [
        'disable_rss'                  => false,
        'disable_header_meta'          => false,
        'disable_emojis'               => false,
        'disable_comments'             => false,
        'disable_block_css'            => false,
        'disable_cf7_scripts'          => false,
        'disable_cf7_ptags'            => false,
        'disable_inline_scripts'       => false,
        'disable_embeds'               => false,
        'disable_media_pages'          => false,
        'disable_xmlrpc'               => false,
        'disable_xmlrpc_header'        => false,
        'remove_wp_version'            => false,
        'remove_version_from_assets'   => false,
        'hide_login_errors'            => false,
        'remove_dashboard_welcome'     => false,
        'disable_rest_api_public'      => false,
        'disable_self_pingbacks'       => false,
        'disable_heartbeat'            => false,
        'limit_post_revisions'         => false,
        'disable_file_edit'            => false,
        'remove_shortlink'             => false,
        'disable_author_archives'      => false,
		'disable_text_copy'            => false,
		'disable_auto_update_emails'   => false,
		'disable_aioseo_gsc_notice'    => false,
		'disable_enfold_debug_info'    => false,
		'enable_enfold_alb_debug'      => false,
    ];
}

function iv1wpt_wp_settings_fields(): array {
    return [
        __('Security', 'iv1-wp-tools') => [
            'disable_xmlrpc'              => [__('Disable XMLRPC interface', 'iv1-wp-tools'), __('Prevents brute-force attacks via XML-RPC', 'iv1-wp-tools')],
            'disable_xmlrpc_header'       => [__('Remove XMLRPC HTTP header', 'iv1-wp-tools'), __('Removes the X-Pingback header', 'iv1-wp-tools')],
            'remove_wp_version'           => [__('Hide WordPress version', 'iv1-wp-tools'), __('Removes WP version from HTML source', 'iv1-wp-tools')],
            'remove_version_from_assets'  => [__('Remove versions from styles & scripts', 'iv1-wp-tools'), __('Removes ?ver= parameter from CSS/JS URLs', 'iv1-wp-tools')],
            'hide_login_errors'           => [__('Hide login error messages', 'iv1-wp-tools'), __('Prevents username enumeration via login errors', 'iv1-wp-tools')],
            'disable_file_edit'           => [__('Disable file editor', 'iv1-wp-tools'), __('Disables the theme/plugin editor in dashboard', 'iv1-wp-tools')],
            'disable_rest_api_public'     => [__('Restrict REST API for guests', 'iv1-wp-tools'), __('Only logged-in users can use the REST API', 'iv1-wp-tools')],
            'disable_author_archives'     => [__('Disable author archives', 'iv1-wp-tools'), __('Prevents user enumeration via /?author=1', 'iv1-wp-tools')],
			'disable_auto_update_emails' => [
				__('Disable auto-update emails', 'iv1-wp-tools'),
				__('Prevents WordPress from sending emails after automatic core, plugin and theme updates.', 'iv1-wp-tools')
			],			
        ],
        __('Performance', 'iv1-wp-tools') => [
            'disable_emojis'              => [__('Disable WordPress emojis', 'iv1-wp-tools'), __('Removes emoji script and stylesheet', 'iv1-wp-tools')],
            'disable_block_css'           => [__('Disable block editor CSS', 'iv1-wp-tools'), __('Removes wp-block-library CSS in frontend', 'iv1-wp-tools')],
            'disable_embeds'              => [__('Disable WordPress oEmbed', 'iv1-wp-tools'), __('Removes the embed.min.js script', 'iv1-wp-tools')],
            'disable_heartbeat'           => [__('Limit Heartbeat API', 'iv1-wp-tools'), __('Reduces AJAX requests to post editing', 'iv1-wp-tools')],
            'limit_post_revisions'        => [__('Limit revisions (max. 5)', 'iv1-wp-tools'), __('Limits stored revisions to 5 per post', 'iv1-wp-tools')],
            'disable_self_pingbacks'      => [__('Disable self-pingbacks', 'iv1-wp-tools'), __('Prevents pingbacks to own site', 'iv1-wp-tools')],
        ],
        __('Cleanup', 'iv1-wp-tools') => [
            'disable_rss'                 => [__('Disable RSS feeds', 'iv1-wp-tools'), __('Disables all RSS and Atom feeds', 'iv1-wp-tools')],
            'disable_header_meta'         => [__('Remove unnecessary header meta', 'iv1-wp-tools'), __('Removes WLW Manifest, RSD, shortlinks, feed links', 'iv1-wp-tools')],
            'disable_comments'            => [__('Disable comments completely', 'iv1-wp-tools'), __('Disables comments site-wide', 'iv1-wp-tools')],
            'remove_dashboard_welcome'    => [__('Remove welcome widget', 'iv1-wp-tools'), __('Removes the welcome widget from dashboard', 'iv1-wp-tools')],
            'remove_shortlink'            => [__('Remove shortlinks', 'iv1-wp-tools'), __('Removes the rel="shortlink" header', 'iv1-wp-tools')],
            'disable_media_pages'         => [__('Disable media detail pages', 'iv1-wp-tools'), __('Redirects attachment pages to parent post', 'iv1-wp-tools')],
			'disable_text_copy'           => [__('Disable text copying', 'iv1-wp-tools'), __('Prevents visitors from selecting and copying text on the frontend', 'iv1-wp-tools')],
        ],
        __('Plugin-specific', 'iv1-wp-tools') => [
            'disable_cf7_scripts'         => [__('Contact Form 7 – CSS/JS only when needed', 'iv1-wp-tools'), __('Loads CF7 assets only on pages with forms', 'iv1-wp-tools')],
            'disable_cf7_ptags'           => [__('Contact Form 7 – disable auto p-tags', 'iv1-wp-tools'), __('Removes automatic p-tags in CF7 forms', 'iv1-wp-tools')],
            'disable_inline_scripts'      => [__('Block inline scripts in content', 'iv1-wp-tools'), __('Removes script tags from post content', 'iv1-wp-tools')],
			'disable_aioseo_gsc_notice'   => [__('Hide AIOSEO Search Console notice', 'iv1-wp-tools'),__('Hides the AIOSEO Google Search Console connection notice in the WordPress admin area.', 'iv1-wp-tools')],
			'disable_enfold_debug_info'   => [__('Enfold – disable debug info', 'iv1-wp-tools'),__('Removes Enfold debugging information from the frontend and admin area.', 'iv1-wp-tools')],
			'enable_enfold_alb_debug'     => [__('Enfold – enable layout builder debug field', 'iv1-wp-tools'),__('Shows the Advanced Layout Builder debug field when editing pages or posts with Enfold.', 'iv1-wp-tools')],			
        ],
    ];
}

// ────────────────────────────────────────────────
// Einstellungen anwenden
// ────────────────────────────────────────────────
function iv1wpt_apply_wp_settings(): void {
    $opts = get_option(IV1WPT_WPSETTINGS_OPTION, iv1wpt_default_wp_settings());

    // Sicherheit
    if (!empty($opts['disable_xmlrpc'])) {
        add_filter('xmlrpc_enabled', '__return_false');
    }
    if (!empty($opts['disable_xmlrpc_header'])) {
        add_filter('wp_headers', function ($headers) {
            unset($headers['X-Pingback']);
            return $headers;
        });
    }
    if (!empty($opts['remove_wp_version'])) {
        add_filter('the_generator', '__return_empty_string');
        remove_action('wp_head', 'wp_generator');
    }
    if (!empty($opts['remove_version_from_assets'])) {
        add_filter('style_loader_src', 'iv1wpt_remove_version_query', 9999);
        add_filter('script_loader_src', 'iv1wpt_remove_version_query', 9999);
    }
    if (!empty($opts['hide_login_errors'])) {
        add_filter('login_errors', function () {
            return __('Invalid credentials.', 'iv1-wp-tools');
        });
    }
    if (!empty($opts['disable_file_edit'])) {
        if (!defined('DISALLOW_FILE_EDIT')) {
            define('DISALLOW_FILE_EDIT', true);
        }
    }
    if (!empty($opts['disable_rest_api_public'])) {
        add_filter('rest_authentication_errors', function ($result) {
            if (!is_user_logged_in()) {
                return new WP_Error('rest_not_logged_in', __('REST API for logged-in users only.', 'iv1-wp-tools'), ['status' => 401]);
            }
            return $result;
        });
    }
    if (!empty($opts['disable_author_archives'])) {
        add_action('template_redirect', function () {
            if (is_author()) {
                wp_redirect(home_url(), 301);
                exit;
            }
        });
    }

    // Performance
    if (!empty($opts['disable_emojis'])) {
        remove_action('wp_head', 'print_emoji_detection_script', 7);
        remove_action('wp_print_styles', 'print_emoji_styles');
        remove_action('admin_print_scripts', 'print_emoji_detection_script');
        remove_action('admin_print_styles', 'print_emoji_styles');
        add_filter('emoji_svg_url', '__return_false');
    }
    if (!empty($opts['disable_block_css'])) {
        add_action('wp_enqueue_scripts', function () {
            wp_dequeue_style('wp-block-library');
            wp_dequeue_style('wp-block-library-theme');
            wp_dequeue_style('wc-blocks-style');
            wp_dequeue_style('global-styles');
        }, 100);
    }
    if (!empty($opts['disable_embeds'])) {
        add_action('init', function () {
            remove_action('wp_head', 'wp_oembed_add_discovery_links');
            remove_action('wp_head', 'wp_oembed_add_host_js');
        }, 20);
        add_action('wp_enqueue_scripts', function () {
            wp_deregister_script('wp-embed');
        });
    }
    if (!empty($opts['disable_heartbeat'])) {
        add_action('init', function () {
            if (!is_admin()) {
                wp_deregister_script('heartbeat');
            }
        }, 1);
        add_filter('heartbeat_settings', function ($settings) {
            $settings['interval'] = 120;
            return $settings;
        });
    }
    if (!empty($opts['limit_post_revisions'])) {
        if (!defined('WP_POST_REVISIONS')) {
            define('WP_POST_REVISIONS', 5);
        }
    }
    if (!empty($opts['disable_self_pingbacks'])) {
        add_action('pre_ping', function (&$links) {
            $home = home_url();
            foreach ($links as $l => $link) {
                if (strpos($link, $home) === 0) {
                    unset($links[$l]);
                }
            }
        });
    }

	// Auto-Update-E-Mails deaktivieren
	if (!empty($opts['disable_auto_update_emails'])) {
		add_filter('auto_core_update_send_email', '__return_false');
		add_filter('auto_plugin_update_send_email', '__return_false');
		add_filter('auto_theme_update_send_email', '__return_false');
	}

    // Bereinigung
    if (!empty($opts['disable_rss'])) {
        add_action('do_feed', 'iv1wpt_disable_feed', 1);
        add_action('do_feed_rdf', 'iv1wpt_disable_feed', 1);
        add_action('do_feed_rss', 'iv1wpt_disable_feed', 1);
        add_action('do_feed_rss2', 'iv1wpt_disable_feed', 1);
        add_action('do_feed_atom', 'iv1wpt_disable_feed', 1);
        remove_action('wp_head', 'feed_links', 2);
        remove_action('wp_head', 'feed_links_extra', 3);
    }
    if (!empty($opts['disable_header_meta'])) {
        remove_action('wp_head', 'wlwmanifest_link');
        remove_action('wp_head', 'rsd_link');
        remove_action('wp_head', 'wp_shortlink_wp_head');
        remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10);
        remove_action('wp_head', 'rest_output_link_wp_head', 10);
    }
    if (!empty($opts['disable_comments'])) {
        add_action('admin_init', function () {
            $post_types = get_post_types();
            foreach ($post_types as $pt) {
                remove_post_type_support($pt, 'comments');
                remove_post_type_support($pt, 'trackbacks');
            }
        });
        add_filter('comments_open', '__return_false', 20, 2);
        add_filter('pings_open', '__return_false', 20, 2);
        add_filter('comments_array', '__return_empty_array', 10, 2);
        add_action('admin_menu', function () {
            remove_menu_page('edit-comments.php');
        });
        add_action('wp_before_admin_bar_render', function () {
            global $wp_admin_bar;
            $wp_admin_bar->remove_menu('comments');
        });
    }
    if (!empty($opts['remove_dashboard_welcome'])) {
        add_action('wp_dashboard_setup', function () {
            remove_action('welcome_panel', 'wp_welcome_panel');
        });
    }
    if (!empty($opts['remove_shortlink'])) {
        add_filter('after_setup_theme', function () {
            remove_action('wp_head', 'wp_shortlink_wp_head', 10);
            remove_action('template_redirect', 'wp_shortlink_header', 11);
        });
    }
    if (!empty($opts['disable_media_pages'])) {
        add_action('template_redirect', function () {
            if (is_attachment()) {
                global $post;
                if ($post && $post->post_parent) {
                    wp_redirect(get_permalink($post->post_parent), 301);
                } else {
                    wp_redirect(home_url(), 301);
                }
                exit;
            }
        });
    }

    // Plugin-spezifisch
    if (!empty($opts['disable_cf7_scripts'])) {
        add_action('wp_enqueue_scripts', function () {
            global $post;
            if (is_a($post, 'WP_Post') && !has_shortcode($post->post_content, 'contact-form-7') && !has_shortcode($post->post_content, 'contact-form')) {
                wp_dequeue_style('contact-form-7');
                wp_dequeue_script('contact-form-7');
                wp_dequeue_script('wpcf7-recaptcha');
            }
        }, 20);
    }
    if (!empty($opts['disable_cf7_ptags'])) {
        add_filter('wpcf7_autop_or_not', '__return_false');
    }
    if (!empty($opts['disable_inline_scripts'])) {
        add_filter('the_content', function ($content) {
            return preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $content);
        });
    }
	
	if (!empty($opts['disable_text_copy'])) {
		add_action('wp_head', function () {
			echo '<style>body{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;}</style>';
		});
		add_action('wp_footer', function () {
			echo '<script>document.addEventListener("copy",function(e){e.preventDefault();});document.addEventListener("cut",function(e){e.preventDefault();});document.addEventListener("selectstart",function(e){e.preventDefault();});</script>';
		});
	}	
	
	// AIOSEO Google Search Console Site-Health-Test entfernen
	if (!empty($opts['disable_aioseo_gsc_notice'])) {
		add_filter('site_status_tests', function ($tests) {
			unset($tests['direct']['aioseo_google_search_console']);
			return $tests;
		}, 100);
	}	
	
	// Enfold debug information entfernen
	if (!empty($opts['disable_enfold_debug_info'])) {
		add_action('init', function () {
			remove_action('wp_head', 'avia_debugging_info', 1000);
			remove_action('admin_print_scripts', 'avia_debugging_info', 1000);
		});
	}	
	
	// Enfold Advanced Layout Builder debug field
	if (!empty($opts['enable_enfold_alb_debug'])) {
		add_action('avia_builder_mode', function () {
			return 'debug';
		});
	}
		
}

// Hilfsfunktionen
function iv1wpt_remove_version_query($src) {
    if (strpos($src, 'ver=')) {
        $src = remove_query_arg('ver', $src);
    }
    return $src;
}

function iv1wpt_wp_setting_is_pro(string $key): bool {
    return in_array($key, iv1wpt_wp_settings_pro_fields(), true);
}

function iv1wpt_disable_feed() {
    wp_die(__('RSS feeds are disabled on this website.', 'iv1-wp-tools'), '', ['response' => 403]);
}

// Einstellungen beim Laden anwenden
//add_action('init', 'iv1wpt_apply_wp_settings', 1);
add_action('plugins_loaded', 'iv1wpt_apply_wp_settings', 1);

// AJAX: WP-Settings speichern
add_action('wp_ajax_iv1wpt_save_wp_settings', 'iv1wpt_save_wp_settings_ajax');
function iv1wpt_save_wp_settings_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');

    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

	$has_pro = iv1wpt_has_pro();
    $defaults = iv1wpt_default_wp_settings();
    $new_opts = [];

    foreach ($defaults as $key => $default) {
        if (function_exists('iv1wpt_wp_setting_is_pro') && iv1wpt_wp_setting_is_pro($key) && !$has_pro) {
            $new_opts[$key] = false;
            continue;
        }

        $new_opts[$key] = !empty($_POST[$key]);
    }

    update_option(IV1WPT_WPSETTINGS_OPTION, $new_opts);

    wp_send_json_success(__('Settings saved.', 'iv1-wp-tools'));
}


