<?php

if ( ! class_exists( 'MainWP_ITSEC_Ban_Users_Setup' ) ) {

	class MainWP_ITSEC_Ban_Users_Setup {

		private
			$defaults;

		public function __construct() {
			add_action( 'mainwp_itsec_modules_do_plugin_activation',   array( $this, 'execute_activate'   )          );
			add_action( 'mainwp_itsec_modules_do_plugin_deactivation', array( $this, 'execute_deactivate' )          );
			add_action( 'mainwp_itsec_modules_do_plugin_uninstall',    array( $this, 'execute_uninstall'  )          );
			add_action( 'mainwp_itsec_modules_do_plugin_upgrade',      array( $this, 'execute_upgrade'    ), null, 2 );
		}

		/**
		 * Execute module activation.
		 *
		 * @since 4.0
		 *
		 * @return void
		 */
		public function execute_activate() {
		}

		/**
		 * Execute module deactivation
		 *
		 * @return void
		 */
		public function execute_deactivate() {

		}

		/**
		 * Execute module uninstall
		 *
		 * @return void
		 */
		public function execute_uninstall() {

			$this->execute_deactivate();

			delete_site_option( 'itsec_ban_users' );

		}

		/**
		 * Execute module upgrade
		 *
		 * @return void
		 */
		public function execute_upgrade( $mainwp_itsec_old_version ) {

			if ( $mainwp_itsec_old_version < 4041 ) {				
				global $mainwp_itsec_globals;
				$current_options = null;				
				if (isset($mainwp_itsec_globals['current_itheme_settings']['itsec_ban_users'])) {
					$current_options = $mainwp_itsec_globals['current_itheme_settings']['itsec_ban_users'];
				}

				// If there are no current options, go with the new defaults by not saving anything
				if ( is_array( $current_options ) ) {
					$itsec_modules = MainWP_ITSEC_Modules::get_instance();

					// 'enable_ban_lists' was previously just 'enabled'
					// Make sure the new module is properly activated or deactivated
					if ( $current_options['enabled'] ) {
						MainWP_ITSEC_Modules::activate( 'backup' );
						$current_options['enable_ban_lists'] = true;
					} else {
						MainWP_ITSEC_Modules::deactivate( 'backup' );
						$current_options['enable_ban_lists'] = false;
					}
					unset( $current_options['enabled'] );

					// Filter out invalid IPs
					$current_options['host_list'] = array_map( 'trim', $current_options['host_list'] );

					if ( ! class_exists( 'MainWP_ITSEC_Lib_IP_Tools' ) ) {
						require_once( MainWP_ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-ip-tools.php' );
					}

					foreach ( $current_options['host_list'] as $index => $ip ) {
						if ( '' === $ip || false === MainWP_ITSEC_Lib_IP_Tools::ip_wild_to_ip_cidr( $ip ) ) {
							unset( $current_options['host_list'][ $index ] );
						}
					}

					$itsec_modules->set_settings( 'ban-users', $current_options );
					MainWP_IThemes_Security::unset_setting_field(array('itsec_ban_users') , $mainwp_itsec_globals['current_site_id']);
				}
			}

		}

	}

}

new MainWP_ITSEC_Ban_Users_Setup();
