<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    iron-security
 * @subpackage iron-security/admin
 * @author     WPIron <info@wpiron.com>
 */
class iron_security_Admin {

	private $plugin_name;
	private $version;
	private $login_logout_functionality;
	private $general_security;
	private $authentication2fa;
	private $helper;
	private $logs;
	private $file_directory_protection;
	private $security_headers;


	public function __construct(
		$plugin_name,
		$version,
		iron_security_general_security $general_security,
		iron_securi_Login_Logout_Functionality $login_logout_functionality,
		WpironHelper $helper,
		WpironFilesDirectoryProtection $file_directory_protection,
		WpironSecurityHeaders $security_headers,
		WpironTwoFactorAuth $twoFactorAuthenticator,
		WpironLogging $logs
	) {
		$this->plugin_name                = $plugin_name;
		$this->version                    = $version;
		$this->login_logout_functionality = $login_logout_functionality;
		$this->general_security           = $general_security;
		$this->helper                     = $helper;
		$this->file_directory_protection  = $file_directory_protection;
		$this->security_headers           = $security_headers;
		$this->authentication2fa     = $twoFactorAuthenticator;
		$this->logs                       = $logs;
	}

	public function wpironis_enqueue_styles() {
		$screen = get_current_screen();
		if ( strpos( $screen->id, 'wpironis-plugin' ) !== false ) {
			wp_enqueue_style( $this->plugin_name,
				plugin_dir_url( __FILE__ ) . 'css/admin.css',
				array(),
				$this->version,
				'all' );
			wp_enqueue_style( $this->plugin_name . '-dashboard',
				plugin_dir_url( __FILE__ ) . 'css/dashboard.css',
				array(),
				$this->version,
				'all' );
			wp_enqueue_style( $this->plugin_name . '-transitions',
				plugin_dir_url( __FILE__ ) . 'css/transitions.css',
				array(),
				$this->version,
				'all' );
		}
	}

	public function wpironis_enqueue_scripts( $hook ) {
		$screen = get_current_screen();

		wp_enqueue_script(
			$this->plugin_name,
			plugin_dir_url( __FILE__ ) . 'js/iron-security-admin.js',
			array( 'jquery', 'wp-element', 'wp-components' ),
			$this->version,
			false
		);

		$options = get_option( 'wpironis_plugin_settings_loginlogout', array() );
		if ( ! empty( $options['enable_session_timeout'] ) && $options['enable_session_timeout'] === '1' ) {
			wp_enqueue_script(
				$this->plugin_name . '-session-timeout',
				plugin_dir_url( __FILE__ ) . 'js/session-timeout.js',
				array( 'jquery' ),
				$this->version,
				true
			);

			wp_localize_script(
				$this->plugin_name . '-session-timeout',
				'ironSecurityTimeout',
				array(
					'timeout'    => isset( $options['session_timeout_value'] ) ? (int) $options['session_timeout_value'] : 3600,
					'logout_url' => wp_logout_url(),
					'nonce'      => wp_create_nonce( 'iron_security_session_nonce' )
				)
			);
		}

		if ( strpos( $hook, 'iron-security-2fa' ) !== false && $hook == 'profile.php' && $hook == 'user-edit.php' ) {
			wp_enqueue_script(
				'iron-security-2fa-admin',
				plugin_dir_url( dirname( dirname( __FILE__ ) ) ) . 'admin/js/iron-security-2fa-admin.js',
				[ 'jquery' ],
				'1.0.0',
				true
			);

			wp_localize_script( 'iron-security-2fa-admin', 'ironSecurity2FA', [
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'nonce'   => wp_create_nonce( 'iron_security_2fa_ajax' ),
				'strings' => [
					'verifyError'   => __( 'Invalid verification code. Please try again.', 'iron-security' ),
					'verifySuccess' => __( 'Two-factor authentication has been successfully set up!', 'iron-security' ),
					'saveSuccess'   => __( 'Settings saved successfully.', 'iron-security' ),
					'saveError'     => __( 'Failed to save settings.', 'iron-security' ),
				],
			] );

			wp_enqueue_style(
				'iron-security-2fa',
				plugin_dir_url( dirname( dirname( __FILE__ ) ) ) . 'admin/css/iron-security-2fa.css',
				[],
				'1.0.0'
			);
		}

		wp_enqueue_script(
			'iron-security-2fa-login',
			plugin_dir_url( dirname( dirname( __FILE__ ) ) ) . 'admin/js/iron-security-2fa-login.js',
			[ 'jquery' ],
			'1.0.0',
			true
		);

		wp_localize_script( 'iron-security-2fa-login', 'ironSecurity2FA', [
			'ajaxUrl' => admin_url( 'admin-ajax.php' ),
			'nonce'   => wp_create_nonce( 'iron_security_2fa_ajax' ),
		] );


		if ( strpos( $screen->id, 'wpironis-plugin' ) !== false ) {
			wp_enqueue_script(
				$this->plugin_name . '-dashboard',
				plugin_dir_url( __FILE__ ) . 'js/dist/' . $this->get_hashed_filename( 'dashboard' ) . '?v=' . $this->version,
				array( 'wp-element', 'wp-components', 'wp-i18n' ),
				$this->version,
				true
			);

			wp_enqueue_script(
				$this->plugin_name . '-vendors',
				plugin_dir_url( __FILE__ ) . 'js/dist/' . $this->get_hashed_filename( 'vendors' ) . '?v=' . $this->version,
				array( 'wp-element', 'wp-components', 'wp-i18n' ),
				$this->version,
				true
			);
		}

		$settings_data = array(
			'general'          => get_option( 'wpironis_plugin_settings_general' ),
			'login_logout'     => get_option( 'wpironis_plugin_settings_loginlogout' ),
			'wpironis_options' => get_option( 'wpironis_options', array() ),
			'ajaxurl'          => admin_url( 'admin-ajax.php' ),
			'nonce'            => wp_create_nonce( 'iron_security_nonce' ),
			'pluginUrl'        => plugin_dir_url( dirname( __FILE__ ) )
		);

		wp_localize_script( $this->plugin_name . '-dashboard', 'ironSecuritySettings', $settings_data );
	}

	public function wpironis_plugin_menu() {
		add_menu_page( 'Iron Security',
			'Iron Security',
			'manage_options',
			'wpironis-plugin',
			array( $this, 'wpironis_plugin_settings_page' ),
			'dashicons-shield-alt',
			100 );
	}

	public function wpironis_plugin_settings_page() {
		$settings_data = array(
			'general'      => get_option( 'wpironis_plugin_settings_general' ),
			'login_logout' => get_option( 'wpironis_plugin_settings_loginlogout' ),
		);
		require_once 'partials/iron-security-settings-dashboard.php';
	}

//	public function wpironis_plugin_settings_init() {
//		register_setting(
//			'wpironis_plugin_settings_loginlogout',
//			'wpironis_plugin_settings_loginlogout',
//			array( $this, 'sanitize_loginlogout_settings' )
//		);
//		$this->login_logout_functionality->settingsFields( $this );
//
//		register_setting(
//			'wpironis_plugin_settings_general',
//			'wpironis_plugin_settings_general',
//			array( $this, 'sanitize_general_settings' )
//		);
//		$this->general_security->settingsFields( $this );
//	}

	public function sanitize_loginlogout_settings( $input ) {
		$sanitized_input = array();
		foreach ( $input as $key => $value ) {
			$sanitized_input[ $key ] = sanitize_text_field( $value );
		}

		return $sanitized_input;
	}

	public function sanitize_general_settings( $input ) {
		$sanitized_input = array();
		foreach ( $input as $key => $value ) {
			if ( in_array( $key, array(
				'wpironis_disable_xmlrpc',
				'wpironis_disable_php_uploads',
				'wpironis_block_ai_bots'
			) ) ) {
				$sanitized_input[ $key ] = isset( $value ) ? 1 : 0;
			} else {
				$sanitized_input[ $key ] = sanitize_text_field( $value );
			}
		}

		return $sanitized_input;
	}

	public function wpironis_additional_links($links) {
		$url2 = "admin.php?page=wpironis-plugin";
		$settings_link = "<a href='$url2' >" . __( 'Settings', 'iron-security' ) . '</a>';

		$links[] = $settings_link;

		return $links;
	}

	public function wpironis_display_2fa_setup_notice() {

		$this->authentication2fa->display_2fa_setup_notice();
	}

	// AUTH
	public function wpironis_handle_custom_url_toggle() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}
		$enabled = filter_var( $_POST['enabled'], FILTER_VALIDATE_BOOLEAN );

		$this->login_logout_functionality->customUrlToggle( $enabled );
	}

	public function wpironis_handle_custom_url_save() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}
		if ( ! isset( $_POST['url'] ) ) {
			wp_send_json_error( 'No URL provided' );

			return;
		}

		$url = sanitize_title( sanitize_text_field( $_POST['url'] ) );
		$this->login_logout_functionality->customUrlSave( $url );
	}

	public function wpironis_handle_session_timeout_toggle() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}

		$enabled = filter_var( $_POST['enabled'], FILTER_VALIDATE_BOOLEAN );
		$this->login_logout_functionality->sessionTimeoutToggle( $enabled );
	}

	public function wpironis_handle_session_timeout_save() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}

		if ( ! isset( $_POST['timeout'] ) ) {
			wp_send_json_error( 'No timeout value provided' );

			return;
		}
		$timeout = absint( $_POST['timeout'] );

		$this->login_logout_functionality->sessionTimeoutSave( $timeout );
	}

	public function wpironis_handle_limit_login_toggle() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}

		$enabled = filter_var( $_POST['enabled'], FILTER_VALIDATE_BOOLEAN );
		$this->login_logout_functionality->limitLoginToggle( $enabled );
	}

	public function wpironis_handle_limit_login_save() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}

		if ( ! isset( $_POST['attempts'] ) || ! isset( $_POST['duration'] ) ) {
			wp_send_json_error( 'Missing required parameters' );

			return;
		}

		$attempts = absint( $_POST['attempts'] );
		$duration = absint( $_POST['duration'] );

		$this->login_logout_functionality->limitLoginSave( $attempts, $duration );
	}

	public function wpironis_handle_user_enum_toggle() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}

		$enabled = filter_var( $_POST['enabled'], FILTER_VALIDATE_BOOLEAN );
		$this->login_logout_functionality->userEnumerationToggle( $enabled );
	}

	public function wpironis_handle_user_enum_message_save() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}

		if ( ! isset( $_POST['message'] ) ) {
			wp_send_json_error( 'No message provided' );

			return;
		}

		$message = sanitize_text_field( $_POST['message'] );
		$this->login_logout_functionality->userEnumerationSave( $message );
	}

	public function wpironis_modify_login_errors( $error ) {
		return $this->login_logout_functionality->modifyAdminLoginErrorMessage( $error );
	}

	public function wpironis_block_user_enumeration() {
		$this->login_logout_functionality->wpironsecwp_block_locked_out_ip_early();
		$author = isset( $_GET['author'] ) ? absint( $_GET['author'] ) : false;

		$this->login_logout_functionality->blockUserEnumeration( $author );
	}

	public function wpironis_handle_admin_id_protection_toggle() {
		if ( ! check_ajax_referer( 'iron_security_nonce', 'nonce', false ) ) {
			wp_send_json_error( __( 'Invalid security token. Please refresh the page and try again.',
				'iron-security' ) );

			return;
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( __( 'You do not have permission to change this setting.', 'iron-security' ) );

			return;
		}

		$enabled = isset( $_POST['enabled'] ) ? filter_var( $_POST['enabled'], FILTER_VALIDATE_BOOLEAN ) : false;
		$this->login_logout_functionality->handleAdminIdChangesToggle( $enabled );
	}

	public function wpironis_handle_change_admin_username_toggle() {
		if ( ! check_ajax_referer( 'iron_security_nonce', 'nonce', false ) ) {
			wp_send_json_error( __( 'Invalid security token. Please refresh the page and try again.',
				'iron-security' ) );

			return;
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( __( 'You do not have permission to change this setting.', 'iron-security' ) );

			return;
		}

		$enabled = isset( $_POST['enabled'] ) ? filter_var( $_POST['enabled'], FILTER_VALIDATE_BOOLEAN ) : false;
		$this->login_logout_functionality->handleAdminIdChangesToggle( $enabled );
	}

	public function wpironis_handle_change_admin_username_save() {
		if ( ! check_ajax_referer( 'iron_security_nonce', 'nonce', false ) ) {
			wp_send_json_error( __( 'Invalid security token. Please refresh the page and try again.',
				'iron-security' ) );

			return;
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( __( 'You do not have permission to change admin username.', 'iron-security' ) );

			return;
		}

		$new_username = isset( $_POST['new_username'] ) ? sanitize_user( $_POST['new_username'] ) : '';
		$new_nickname = isset( $_POST['new_nickname'] ) ? sanitize_text_field( $_POST['new_nickname'] ) : '';

		$this->login_logout_functionality->handleAdminUsernameSave( $new_username, $new_nickname );
	}

	public function wpironis_handle_limit_admins_toggle() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}

		$enabled = isset( $_POST['enabled'] ) ? filter_var( $_POST['enabled'], FILTER_VALIDATE_BOOLEAN ) : false;
		$this->login_logout_functionality->handleLimitsForAdminAccountsToggle( $enabled );
	}

	public function wpironis_handle_limit_admins_save() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}

		$max_admins    = isset( $_POST['max_admins'] ) ? absint( $_POST['max_admins'] ) : 1;
		$fallback_role = isset( $_POST['fallback_role'] ) ? sanitize_text_field( $_POST['fallback_role'] ) : 'subscriber';

		$this->login_logout_functionality->LimitsForAdminAccountsSave( $max_admins, $fallback_role );
	}


	public function wpironis_register_rewrites() {
		$is_enabled = $this->helper->wpironis_getOption( $this->login_logout_functionality::OPTION_NAME,
			'enable_slug_change' ) ?? false;

		if ( isset( $is_enabled ) && $is_enabled && ! empty( $custom_url ) ) {
			$this->login_logout_functionality->wpironis_register_rewrites();
		}
	}

	public function wpironis_template_redirect() {
		$custom_url = $this->helper->wpironis_getOption( $this->login_logout_functionality::OPTION_NAME,
			'wpironis_custom_login_slug' );
		$is_enabled = $this->helper->wpironis_getOption( $this->login_logout_functionality::OPTION_NAME,
			'enable_slug_change' ) ?? false;
		if ( isset( $is_enabled ) && $is_enabled && ! empty( $custom_url ) ) {
			if ( get_query_var( 'wpironis_login' ) ) {
				define( 'WPIRONIS_CUSTOM_LOGIN', true );

				if ( isset( $_GET['action'] ) && $_GET['action'] === 'logout' ) {
					$logout_nonce = $_GET['_wpnonce'] ?? '';

					if ( ! wp_verify_nonce( $logout_nonce, 'log-out' ) ) {
						wp_die( esc_html(__( 'Logout nonce failed.', 'iron-security' )) );
					}

					wp_logout();
					wp_safe_redirect( add_query_arg( 'loggedout', 'true', home_url( '/' . cau_get_slug() ) ) );
					exit;
				}

				global $user_login, $error, $interim_login;
				$user_login    = '';
				$error         = '';
				$interim_login = false;

				require_once ABSPATH . 'wp-login.php';
				exit;
			}
		}
	}

	public function wpironis_parse_request( $wp ) {
		$is_enabled = $this->helper->wpironis_getOption( $this->login_logout_functionality::OPTION_NAME,
			'enable_slug_change' ) ?? false;
		$custom_url = $this->helper->wpironis_getOption( $this->login_logout_functionality::OPTION_NAME,
			'wpironis_custom_login_slug' );
		if ( isset( $is_enabled ) && $is_enabled && ! empty( $custom_url ) ) {
			$this->login_logout_functionality->wpironis_parseRequest( $wp );
		}
	}

	public function wpironis_block_entry_points() {
		$is_enabled = $this->helper->wpironis_getOption( $this->login_logout_functionality::OPTION_NAME,
			'enable_slug_change' ) ?? false;
		$custom_url = $this->helper->wpironis_getOption( $this->login_logout_functionality::OPTION_NAME,
			'wpironis_custom_login_slug' );

		if ( isset( $is_enabled ) && $is_enabled && ! empty( $custom_url ) ) {
			$this->login_logout_functionality->wpironis_block_entry_points();
		}
	}

	public function wpironis_login_url( $login_url, $redirect, $force_reauth ) {
		$custom_url = $this->helper->wpironis_getOption( $this->login_logout_functionality::OPTION_NAME,
			'wpironis_custom_login_slug' );
		$is_enabled = $this->helper->wpironis_getOption( $this->login_logout_functionality::OPTION_NAME,
			'enable_slug_change' ) ?? false;

		if ( isset( $is_enabled ) && $is_enabled && ! empty( $custom_url ) ) {
			return $this->login_logout_functionality->wpironis_loginUrl( $redirect );
		}

		return $login_url;
	}

	public function wpironis_site_url( $url, $path, $scheme ) {
		$custom_url = $this->helper->wpironis_getOption( $this->login_logout_functionality::OPTION_NAME,
			'wpironis_custom_login_slug' );
		$is_enabled = $this->helper->wpironis_getOption( $this->login_logout_functionality::OPTION_NAME,
			'enable_slug_change' ) ?? false;

		if ( isset( $is_enabled ) && $is_enabled && ! empty( $custom_url ) ) {
			return $this->login_logout_functionality->wpironis_siteUrl( $url, $path, $scheme );
		}

		return $url;
	}

	public function wpironis_query_vars( $vars ) {
		$custom_url = $this->helper->wpironis_getOption( $this->login_logout_functionality::OPTION_NAME,
			'wpironis_custom_login_slug' );
		$is_enabled = $this->helper->wpironis_getOption( $this->login_logout_functionality::OPTION_NAME,
			'enable_slug_change' ) ?? false;

		if ( isset( $is_enabled ) && $is_enabled && ! empty( $custom_url ) ) {
			$vars[] = 'wpironis_login';

			return $vars;
		}

		return $vars;
	}

	public function wpironis_set_session_timeout( $expirein ) {
		$is_enabled    = $this->helper->wpironis_getOption( $this->login_logout_functionality::OPTION_NAME,
			'enable_session_timeout' );
		$timeout_value = $this->helper->wpironis_getOption( $this->login_logout_functionality::OPTION_NAME,
			'session_timeout_value' );

		return $this->login_logout_functionality->wpironis_set_session_timeout( $expirein,
			$is_enabled,
			$timeout_value );
	}

	public function wpironis_block_locked_out_users( $user, $username, $password ) {
		$this->login_logout_functionality->wpironsecwp_block_locked_out_ip_early();

		return $this->login_logout_functionality->wpironsecwp_block_locked_out_users( $user, $username, $password );
	}

	public function wpironis_block_locked_out_ip_early() {
		$this->login_logout_functionality->wpironsecwp_block_locked_out_ip_early();
	}

	public function wpironsecwp_verify_nonce_before_authentication() {
		if ( isset( $_POST['_wpnonce'] ) && ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ),
				'wp-login' ) ) {
			return new WP_Error( 'nonce_verification_failed', __( 'Nonce verification failed.', 'iron-security' ) );
		}
	}

	public function wpironis_handle_failed_login( $username ) {
		$options = get_option( 'wpironis_plugin_settings_loginlogout' );
		if ( empty( $options['enable_limit_login_attempts'] ) ) {
			return;
		}
		$this->logs->log_failed_login( $username );

		$ip_address = $this->login_logout_functionality->get_user_ip();
		$attempts   = get_transient( $ip_address . '_wpis_attempts' ) ?: 0;
		$attempts ++;

		set_transient( $ip_address . '_wpis_attempts', $attempts, $options['wpironis_lockout_duration'] );
		if ( $attempts >= $options['wpironis_limit_login_attempts'] ) {
			set_transient( $ip_address . '_wpis_lockout', true, $options['wpironis_lockout_duration'] );
			set_transient( $ip_address . '_wpis_lockout_time', time(), $options['wpironis_lockout_duration'] );

			$this->logs->log_lockout( $username, $attempts );
		}
	}

	public function extend_session() {
		check_ajax_referer( 'iron_security_session_nonce', 'nonce' );

		if ( ! is_user_logged_in() ) {
			wp_send_json_error( 'User not logged in' );

			return;
		}

		update_user_meta( get_current_user_id(), 'iron_security_last_activity', time() );
		wp_send_json_success( 'Session extended' );
	}

	public function log_successful_login( $user_login, $user ) {
		$this->login_logout_functionality->clearActivity();
		$this->logs->log_successful_login( $user_login, $user->ID );
	}

	public function wpironsec_custom_function_for_logout() {
		$this->login_logout_functionality->clearUserActivity();
	}

	public function wpironis_enforce_admin_limit( $user_id, $role, $old_roles ) {
		if ( $role !== 'administrator' ) {
			return;
		}

		$this->login_logout_functionality->enforceAdminLimits( $user_id );
	}

	public function wpironis_check_admin_limit_on_register( $user_id ) {
		$this->login_logout_functionality->checkAdminLimitOnRegister( $user_id );
	}

	public function wpironsec_get_admin_info() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'iron_security_nonce' ) ) {
			wp_send_json_error( 'Invalid security token sent.' );
			wp_die();
		}


		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'You do not have permission to perform this action.' );
			wp_die();
		}
		$this->login_logout_functionality->getAdminInfo();
	}

	// ***---
	// General

	public function wpironis_manage_htaccess( $old_value, $new_value ) {
		if ( isset( $new_value['wpironis_disable_php_uploads'] ) && $new_value['wpironis_disable_php_uploads'] ) {
			$this->general_security->wpironis_create_htaccess();
		} else {
			$this->general_security->wpironis_remove_htaccess();
		}
	}

	public function wpironis_handle_xmlrpc_toggle() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}

		$enabled = isset( $_POST['enabled'] ) ? filter_var( $_POST['enabled'], FILTER_VALIDATE_BOOLEAN ) : false;
		$this->general_security->handleXmlrpcTogge( $enabled );
	}

	public function wpironis_handle_wp_version_toggle() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}

		$enabled = isset( $_POST['enabled'] ) ? filter_var( $_POST['enabled'], FILTER_VALIDATE_BOOLEAN ) : false;
		$this->general_security->handleWpVersionToggle( $enabled );
	}

	public function wpironis_handle_security_headers_toggle() {
		if ( ! check_ajax_referer( 'iron_security_nonce', 'nonce', false ) ) {
			wp_send_json_error( [ 'message' => 'Security check failed' ], 403 );
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => 'Insufficient permissions' ], 403 );
		}
		$enabled        = isset( $_POST['enabled'] ) ? rest_sanitize_boolean( $_POST['enabled'] ) : false;
		$header_name_js = sanitize_text_field( $_POST['header_name'] ?? '' );
		$this->general_security->handleSecurityHeadersToggle( $enabled, $header_name_js );
	}

	public function wpironis_handle_rest_api_toggle() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}

		$enabled = isset( $_POST['enabled'] ) ? filter_var( $_POST['enabled'], FILTER_VALIDATE_BOOLEAN ) : false;
		$this->general_security->handleRestApiToggle( $enabled );
	}

	public function wpironis_handle_plugin_autoupdate_toggle() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}

		$enabled = isset( $_POST['enabled'] ) ? filter_var( $_POST['enabled'], FILTER_VALIDATE_BOOLEAN ) : false;
		$this->general_security->handlePluginAutoupdateToggle( $enabled );
	}

	public function wpironis_handle_core_autoupdate_toggle() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}

		$enabled = isset( $_POST['enabled'] ) ? filter_var( $_POST['enabled'], FILTER_VALIDATE_BOOLEAN ) : false;
		$this->general_security->handleCoreUpdatesToggle( $enabled );
	}

	public function wpironis_handle_file_editor_toggle() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}

		$enabled = isset( $_POST['enabled'] ) ? filter_var( $_POST['enabled'], FILTER_VALIDATE_BOOLEAN ) : false;
		$this->general_security->handleFileEditorToggle( $enabled );
	}

	public function wpironis_handle_ai_bot_blocking_toggle( $forceDelete = false ) {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( __( 'You do not have permission to modify this setting.', 'iron-security' ) );
		}

		$enabled = isset( $_POST['enabled'] ) ? filter_var( $_POST['enabled'], FILTER_VALIDATE_BOOLEAN ) : false;
		$this->general_security->handleAiBlockingToggle( $enabled, $forceDelete );
	}

	//@todo DELETE IT
	public function wpironis_filter_rest_user_responses( $response, $handler, $request ) {
		$this->login_logout_functionality->filterRestUserresponse( $response, $handler, $request );
	}

	// ***---
	// Files Protection

	public function wpironis_handle_php_uploads_toggle() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}

		$enabled = isset( $_POST['enabled'] ) ? filter_var( $_POST['enabled'], FILTER_VALIDATE_BOOLEAN ) : false;
		$this->file_directory_protection->handlePhpUploadToggle( $enabled );
	}

	public function wpironis_prevent_php_upload( $file ) {
		return $this->file_directory_protection->wpironis_preventProgrammableFileUploads( $file );
	}

	public function wpironis_handle_direct_file_access_toggle() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}

		$enabled = isset( $_POST['enabled'] ) ? filter_var( $_POST['enabled'], FILTER_VALIDATE_BOOLEAN ) : false;
		$this->file_directory_protection->handleDirectFileAccessToggle( $enabled );
	}

	// ***---
	// Logs

	public function wpironsec_get_security_logs() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}
		$this->logs->getSecurityLogs();
	}

	public function wpironsec_clear_security_logs() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}
		$log_type = isset( $_POST['log_type'] ) ? sanitize_text_field( $_POST['log_type'] ) : '';
		$this->logs->clearSecurityLogs( $log_type );
	}

	// ***---
	// Security headers

	public function wpironis_handle_security_header_toggle() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}

		$enabled     = isset( $_POST['enabled'] ) ? filter_var( $_POST['enabled'], FILTER_VALIDATE_BOOLEAN ) : false;
		$header_name = isset( $_POST['header_name'] ) ? sanitize_text_field( $_POST['header_name'] ) : '';

		$this->security_headers->handleSecurityHeadersToggle( $enabled, $header_name );
	}

	// ***---

	// 2fa

	public function wpironis_check_auth_status() {
		$verify2fa   = isset( $_GET['iron_security_2fa_verify'] ) ? $_GET['iron_security_2fa_verify'] : null;
		$setup2fa    = isset( $_GET['iron_security_2fa_setup'] ) ? $_GET['iron_security_2fa_setup'] : null;
		$currentPage = isset( $_GET['page'] ) ? $_GET['page'] : null;

		register_setting(
			'wpironis_plugin_settings_loginlogout',
			'wpironis_plugin_settings_loginlogout',
			array( $this, 'sanitize_loginlogout_settings' )
		);
		$this->login_logout_functionality->settingsFields( $this );

		register_setting(
			'wpironis_plugin_settings_general',
			'wpironis_plugin_settings_general',
			array( $this, 'sanitize_general_settings' )
		);
		$this->general_security->settingsFields( $this );

		$this->authentication2fa->checkAuthStatus( $verify2fa, $setup2fa, $currentPage );
		$this->authentication2fa->check2faOnAdminInit();
		$this->login_logout_functionality->wpironsecwp_block_locked_out_ip_early();

		if ( is_user_logged_in() ) {
			$this->login_logout_functionality->checkSessionTimeout();
		}

	}

	public function wpironis_verify2fa() {
		$verify2fa = isset( $_GET['iron_security_2fa_verify'] ) ? sanitize_text_field( $_GET['iron_security_2fa_verify'] ) : '';

		$this->authentication2fa->verify2fa( $verify2fa );
	}

	public function wpironis_add_2fa_field() {
		$this->authentication2fa->add2faFields();
	}

	public function wpironis_auth_redirect( $user_login, $user ) {
		$this->authentication2fa->authRedirect( $user_login, $user );
	}

	public function wpironis_add_user_profile_fields( $user ) {
		$this->authentication2fa->addUserProfilefields( $user );
	}

	public function wpironis_save_user_profile_fields( $user_id ) {
		$this->authentication2fa->saveUserProfileFields( $user_id );
	}

	public function wpironis_ajax_verify_2fa_code() {
		$this->authentication2fa->ajax_verify_2fa_code();
	}

	public function wpironis_ajax_verify_2fa_setup() {
		$this->authentication2fa->ajax_verify_2fa_setup();
	}

	public function wpironis_ajax_save_2fa_settings() {
		$this->authentication2fa->ajax_save_2fa_settings();
	}

	public function wpironis_ajax_toggle_2fa() {
		$this->authentication2fa->ajax_toggle_2fa();
	}

	public function wpironis_ajax_save_2fa_settings_from_loginlogout() {
		$this->authentication2fa->save2faSettingsForLoginLogout();
	}

	public function wpironis_check_2fa_required() {
		$this->authentication2fa->check2faRequired();
	}

	public function wpironis_clear_2fa_verification_on_logout() {
		$this->authentication2fa->clear2faVerificationOnLogout();
	}

//	public function wpironis_check_2fa_on_admin_init() {
//		$this->authentication2fa->check2faOnAdminInit();
//	}

	// ***---

	public function wpironis_upgrader_process_complete( $upgrader, $hook_extra ) {
		if ( ! empty( $hook_extra['type'] ) && $hook_extra['type'] === 'core' ) {
			$old = get_bloginfo( 'version' );
			$new = $upgrader->result['destination_name'] ?? 'unknown';
			$this->logs->log_core_update( $old, $new );
		}
	}

	public function wpironis_activate_plugin( $plugin ) {
		$this->logs->log_plugin_action( 'activated', $plugin );
	}

	public function wpironis_deactivate_plugin( $plugin ) {
		$this->logs->log_plugin_action( 'deactivated', $plugin );
	}

	public function wpironis_delete_plugin( $plugin ) {
		$this->logs->log_plugin_action( 'deleted', $plugin );
	}


	public function wpironis_get_settings() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}

		$settings_data = array(
			'general'          => get_option( 'wpironis_plugin_settings_general' ),
			'login_logout'     => get_option( 'wpironis_plugin_settings_loginlogout' ),
			'wpironis_options' => get_option( 'wpironis_options', array() ),
			'ajaxurl'          => admin_url( 'admin-ajax.php' ),
			'nonce'            => wp_create_nonce( 'iron_security_nonce' ),
			'pluginUrl'        => plugin_dir_url( dirname( __FILE__ ) )
		);

		wp_send_json_success( $settings_data );
	}

	/**
	 * Get system information for the dashboard
	 */
	public function wpironis_get_system_info() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );

			return;
		}

		global $wpdb;

		// Get WordPress version
		$wp_version = get_bloginfo( 'version' );

		// Get PHP version
		$php_version = phpversion();

		// Server information
		$server_info = isset( $_SERVER['SERVER_SOFTWARE'] ) ? $_SERVER['SERVER_SOFTWARE'] : __( 'Not available',
			'iron-security' );

		// Get MySQL/MariaDB version
		$db_version = $wpdb->get_var( "SELECT VERSION()" );

		// Count admin users
		$admin_count = count( get_users( [ 'role' => 'administrator' ] ) );

		// Get latest WordPress version via API
		$latest_wp_info = null;
		$wp_outdated    = false;

		$response = wp_remote_get( 'https://api.wordpress.org/core/version-check/1.7/' );
		if ( ! is_wp_error( $response ) && wp_remote_retrieve_response_code( $response ) === 200 ) {
			$data = json_decode( wp_remote_retrieve_body( $response ), true );
			if ( isset( $data['offers'] ) && ! empty( $data['offers'] ) ) {
				$latest_wp_version = $data['offers'][0]['version'];
				$latest_wp_info    = $data['offers'][0];
				$wp_outdated       = version_compare( $wp_version, $latest_wp_version, '<' );
			}
		}

		$system_info = array(
			'wp_version'        => $wp_version,
			'wp_outdated'       => $wp_outdated,
			'latest_wp_version' => $latest_wp_info ? $latest_wp_info['version'] : null,
			'php_version'       => $php_version,
			'php_outdated'      => version_compare( $php_version, '8.0', '<' ),
			'server_info'       => $server_info,
			'db_version'        => $db_version,
			'admin_count'       => $admin_count
		);

		wp_send_json_success( $system_info );
	}

	private function get_hashed_filename( $base_name ) {
		$manifest_path = plugin_dir_path( __FILE__ ) . 'js/dist/manifest.json';

		if ( file_exists( $manifest_path ) ) {
			$manifest = json_decode( file_get_contents( $manifest_path ), true );
			if ( isset( $manifest[ $base_name . '.js' ] ) ) {
				return $manifest[ $base_name . '.js' ];
			}
		}


		$dist_path = plugin_dir_path( __FILE__ ) . 'js/dist/';
		$files     = glob( $dist_path . $base_name . '.*.js' );

		if ( ! empty( $files ) ) {
			$file = basename( $files[0] );

			return $file;
		}


		return $base_name . '.bundle.js';
	}

	public function wpironis_get_security_score() {
		check_ajax_referer( 'iron_security_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );
			return;
		}

		$security_score = $this->helper->calculate_security_score();
		error_log('security score');
		error_log(print_r($security_score, true));
		wp_send_json_success( $security_score );
	}

}
