<?php
/**
 * Starter Templares Onboarding Controller.
 *
 * @package starter-templares-onboarding
 * @since 1.0.0
 */

if ( ! class_exists( 'STO_Controller' ) ) :

	/**
	 * STO_Controller
	 *
	 * @since 1.0.0
	 */
	class STO_Controller {

		/**
		 * Instance
		 *
		 * @access public
		 * @var object Class Instance.
		 * @since 1.0.0
		 */
		private static $instance;

		/**
		 * Initiator
		 *
		 * @return object initialized object of class.
		 * @since 1.0.0
		 */
		public static function get_instance() {
			if ( ! isset( self::$instance ) ) {
				self::$instance = new self();
			}
			return self::$instance;
		}

		/**
		 * Constructor
		 *
		 * @since 1.0.0
		 */
		public function __construct() {
			add_filter( 'st_ai_onboarding_logo_dark', array( $this, 'change_onboarding_logo_dark' ) );
			add_filter( 'st_ai_onboarding_logo_light', array( $this, 'change_onboarding_logo_light' ) );
			add_filter( 'ai_builder_show_premium_badge', '__return_false' );
			add_filter( 'ai_builder_skip_features', array( $this, 'features_screen' ) );
			add_action( 'admin_head', array( $this, 'add_custom_css' ) );
			add_action( 'init', array( $this, 'maybe_check_redirection' ), 100 );
			add_action( 'init', array( $this, 'maybe_start_self_destruction' ), 999 );
			add_filter( 'ast_block_templates_bypass_auth', '__return_true' );
			add_filter( 'ai_builder_site_source', array( $this, 'update_site_source' ) );
			add_filter( 'ai_builder_migrate_svg', array( $this, 'update_migration_svg' ) );
			add_filter( 'option_zip_ai_settings', array( $this, 'set_partner_token' ), 10 );
			add_action( 'astra_sites_import_success', array( $this, 'maybe_self_destruction' ) );
			add_filter( 'ai_builder_limit_exceeded_popup_strings', array( $this, 'change_ai_builder_popup_strings' ), 10, 1 );
			add_filter( 'ai_builder_textdomain', array( $this, 'change_textdomain' ), 10, 1 );
			add_filter( 'ai_builder_languages_directory', array( $this, 'change_languages_directory' ), 10, 1 );
			add_action( 'astra_sites_import_complete', array( $this, 'disable_spectra_ai' ), 10, 1 );
			add_filter( 'ai_builder_default_website_language', array( $this, 'set_default_website_language' ), 10, 1 );
			add_filter( 'ai_builder_default_business_type', array( $this, 'set_default_business_type' ), 10, 1 );
			add_filter( 'ai_builder_show_zip_plan_details', array( $this, 'disable_showing_zip_plan' ), 10, 1 );
			add_filter( 'ai_builder_hidden_site_features', array( $this, 'hide_specified_features' ), 10, 1 );
		}

		/**
		 * Hide specified features.
		 *
		 * @param array<int, string> $features features.
		 *
		 * @return array<int, string>
		 * @since 1.1.4
		 */
		public function hide_specified_features( $features ) {

			$hidden_site_features = STO_Loader::get_partner_details( 'hidden_site_features' );
			if ( is_array( $hidden_site_features ) ) {
				return $hidden_site_features;
			}

			return $features;
		}

		/**
		 * Disable Zip plan info.
		 *
		 * @param bool $show_plan Is show plan.
		 *
		 * @return bool
		 * @since 1.1.1
		 */
		public function disable_showing_zip_plan( $show_plan ) {
			return false;
		}

		/**
		 * Set website languages.
		 *
		 * @param string $lang languages.
		 *
		 * @return string
		 * @since 1.1.0
		 */
		public function set_default_website_language( $lang ) {

			$default_language = STO_Loader::get_partner_details( 'default_website_language' );
			if ( ! empty( $default_language ) ) {
				return $default_language;
			}

			return $lang;
		}

		/**
		 * Set business type.
		 *
		 * @param string $business_type business type.
		 *
		 * @return string
		 * @since 1.1.6
		 */
		public function set_default_business_type( $business_type ) {

			$default_business_type = STO_Loader::get_partner_details( 'default_business_type' );
			if ( ! empty( $default_business_type ) ) {
				return $default_business_type;
			}

			return $business_type;
		}


		/**
		 * Disable Spectra AI.
		 *
		 * @return void
		 * @since 1.0.16
		 */
		public function disable_spectra_ai() {

			// Disable Spectra AI features.
			$is_disable_ai_features = STO_Loader::get_partner_details( 'disable_spectra_ai' );
			if ( 'yes' === $is_disable_ai_features ) {
				$this->update_zip_ai_modules_status();
			}
		}

		/**
		 * Update zipai modules status.
		 *
		 * @return void
		 */
		public function update_zip_ai_modules_status() {

			$zip_ai_modules = get_option( 'zip_ai_modules', array() );

			$zip_ai_modules = is_array( $zip_ai_modules ) ? $zip_ai_modules : array();

			$zip_ai_modules['ai_design_copilot']['status'] = 'disabled';
			$zip_ai_modules['ai_assistant']['status']      = 'disabled';

			update_option( 'zip_ai_modules', $zip_ai_modules );
		}

		/**
		 * Change textdomain.
		 *
		 * @param string $textdomain text domain.
		 *
		 * @return string
		 * @since 1.0.9
		 */
		public function change_textdomain( $textdomain ) {
			return 'starter-templates-onboarding';
		}

		/**
		 * Change languages directory.
		 *
		 * @param string $lang_dir languages directory.
		 *
		 * @return string
		 * @since 1.0.9
		 */
		public function change_languages_directory( $lang_dir ) {
			return STO_DIR . 'languages';
		}


		/**
		 * Update parent plugin.
		 *
		 * @param array<string, mixed> $popup_strings Popup strings.
		 * @return array<string, mixed>
		 * @since 1.0.13
		 */
		public function change_ai_builder_popup_strings( $popup_strings ) {

			$contact_url = STO_Loader::get_company_contact_url();

			$popup_strings['main_content']      = __( 'You have reached the maximum number of sites allowed to be created.', 'starter-templates-onboarding' );
			$popup_strings['secondary_content'] = __( 'Please contact your host in order to create more sites.', 'starter-templates-onboarding' );
			$popup_strings['upgrade_text']      = __( 'Contact Your Host', 'starter-templates-onboarding' );
			$popup_strings['upgrade_url']       = $contact_url;
			$popup_strings['contact_text']      = __( 'Contact Your Host', 'starter-templates-onboarding' );
			$popup_strings['contact_url']       = $contact_url;

			return $popup_strings;
		}

		/**
		 * Features screen.
		 *
		 * @return string
		 * @since 1.0.9
		 */
		public function features_screen() {
			return STO_Loader::get_partner_details( 'disable_features_screen' ) ?? 'no';
		}

		/**
		 * Set partner token.
		 *
		 * @return string
		 * @param mixed $value The option value.
		 * @since 1.0.5
		 */
		public function set_partner_token( $value ) {
			if ( isset( $value['zip_token'] ) ) {
				return $value;
			}
			$token_details              = $value;
			$partner_token              = isset( $value['partner_token'] ) ? $value['partner_token'] : '';
			$token_details['zip_token'] = $partner_token;
			return $token_details;
		}

		/**
		 * Maybe check redirection.
		 *
		 * @since 1.0.7
		 * @return void
		 */
		public function maybe_check_redirection() {

			// If WP CLI is running, then return.
			if ( defined( 'WP_CLI' ) && WP_CLI ) {
				return;
			}

			// If user is not logged in, then return.
			if ( ! is_user_logged_in() ) {
				return;
			}

			$redirect = STO_Loader::get_partner_details( 'domain_change_redirect' );

			if ( 'yes' !== $redirect ) {
				return;
			}

			$stored_domain = get_option( 'sto_domain', '' );
			$site_host     = wp_parse_url( get_site_url(), PHP_URL_HOST );
			if ( ! empty( $site_host ) && is_string( $site_host ) ) {
				$domain      = str_replace( 'www.', '', $site_host );
				$site_domain = str_replace( '.', '-', $domain );
				if ( $stored_domain !== $site_domain ) {
					update_option( 'sto_domain', $site_domain );
					wp_safe_redirect( admin_url( 'themes.php?page=ai-builder' ) );
					exit;
				}
			}
		}

		/**
		 * Maybe start self destruction.
		 *
		 * @since 1.0.4
		 * @return void
		 */
		public function maybe_start_self_destruction() {

			if ( defined( 'WP_CLI' ) && WP_CLI ) {
				return;
			}

			// If user is not logged in, then return.
			if ( ! is_user_logged_in() ) {
				return;
			}

			$destruct_plugin = STO_Loader::get_partner_details( 'domain_change_destruct' );

			if ( 'yes' !== $destruct_plugin ) {
				return;
			}

			$site_host = wp_parse_url( get_site_url(), PHP_URL_HOST );

			if ( empty( $site_host ) || ! is_string( $site_host ) ) {
				return;
			}

			$domain      = str_replace( 'www.', '', $site_host );
			$site_domain = str_replace( '.', '-', $domain );

			$stored_domain = get_option( 'sto_domain_destruct', '' );

			if ( empty( $stored_domain ) ) {
				update_option( 'sto_domain_destruct', $site_domain );
				return;
			}

			if ( $stored_domain !== $site_domain ) {
				$this->self_destruct_full_plugin();
			}
		}

		/**
		 * Self Destruct
		 *
		 * @since 1.0.4
		 * @return void
		 */
		public function self_destruct_full_plugin() {
			// Remove the partner token.
			$zip_ai_settings = get_option( 'zip_ai_settings', [] );
			if ( isset( $zip_ai_settings['partner_token'] ) ) {
				unset( $zip_ai_settings['partner_token'] );
				update_option( 'zip_ai_settings', $zip_ai_settings );
			}

			if ( ! function_exists( 'deactivate_plugins' ) ) {
				require_once ABSPATH . 'wp-admin/includes/plugin.php';
			}

			// Deactivate plugin.
			deactivate_plugins( STO_FILE, true );

			// Delete the full plugin.
			$this->delete_directory( STO_DIR );
		}

		/**
		 * Delete directory.
		 *
		 * @since 1.0.4
		 * @param string $dir Directory path.
		 * @return bool
		 */
		public function delete_directory( $dir ) {

			if ( ! is_dir( $dir ) ) {
				return false;
			}

			$files = scandir( $dir );

			if ( is_array( $files ) ) {
				foreach ( $files as $file ) {
					if ( '.' !== $file && '..' !== $file ) {
						if ( is_dir( $dir . '/' . $file ) ) {
							$this->delete_directory( $dir . '/' . $file );
						} else {
							unlink( $dir . '/' . $file );
						}
					}
				}
			}
			return rmdir( $dir );
		}

		/**
		 * Update migration SVG.
		 *
		 * @return string
		 * @param string $url The site source.
		 * @since 1.0.3
		 */
		public function update_migration_svg( $url ) {

			$url = STO_URL . '/inc/assets/images/migrating-site-graphic.svg';
			return $url;
		}

		/**
		 * Update site source.
		 *
		 * @return string
		 * @param string $site_source The site source.
		 * @since 1.0.0
		 */
		public function update_site_source( $site_source ) {

			$site_source = 'st-host-onboarding';
			return $site_source;
		}

		/**
		 * Add custom css.
		 *
		 * @return void
		 * @since 1.0.0
		 */
		public function add_custom_css() {
			if ( ! is_user_logged_in() ) {
				return;
			}
			if ( ! class_exists( 'STO_Loader' ) && is_callable( 'STO_Loader::get_partner_details' ) ) {
				return;
			}
			$bg_color           = STO_Loader::get_partner_details( 'secondary_color' );
			$accent_color       = STO_Loader::get_partner_details( 'primary_color' );
			$accent_color_hover = STO_Loader::get_partner_details( 'primary_color_dark' );
			if ( empty( $bg_color ) || empty( $accent_color ) || empty( $accent_color_hover ) ) {
				return;
			}
			?>
			<style id="st-ai-onboarding-style">
				body {
					--zip-dark-theme-bg: <?php echo $bg_color; ?>; <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
					--accent-st: <?php echo $accent_color; ?>; <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
					--st-color-accent: <?php echo $accent_color; ?>; <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
					--st-color-accent-hover: <?php echo $accent_color_hover; ?>; <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
					--accent-hover-st: <?php echo $accent_color_hover; ?>; <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
					--accent-st-tertiary: <?php echo $accent_color; ?>; <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
				}
				.ist-logo {
					--stc-logo-width: auto;
				}
				.st-page-builder-filter {
					display: none;
				}
			</style>
			<?php
		}

		/**
		 * Change onboarding logo.
		 *
		 * @return string
		 * @since 1.0.0
		 */
		public function change_onboarding_logo_dark() {
			$light_logo = STO_Loader::get_partner_details( 'logo_light' );
			if ( empty( $light_logo ) ) {
				return STO_URL . '/inc/assets/images/logo-light.svg';
			}
			return $light_logo;
		}

		/**
		 * Change onboarding logo.
		 *
		 * @return string
		 * @since 1.0.0
		 */
		public function change_onboarding_logo_light() {
			$dark_logo = STO_Loader::get_partner_details( 'logo_dark' );
			if ( empty( $dark_logo ) ) {
				return STO_URL . '/inc/assets/images/logo-dark.svg';
			}
			return $dark_logo;
		}

		/**
		 * Encrypt data using base64.
		 *
		 * @param string $input The input string which needs to be encrypted.
		 * @since 1.0.0
		 * @return string The encrypted string.
		 */
		public function encrypt( $input ) {
			// If the input is empty or not a string, then abandon ship.
			if ( empty( $input ) || ! is_string( $input ) ) {
				return '';
			}

			// Encrypt the input and return it.
			$base_64 = base64_encode( $input ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
			$encode  = rtrim( $base_64, '=' );
			return $encode;
		}

		/**
		 * Decrypt data using base64.
		 *
		 * @param string $input The input string which needs to be decrypted.
		 * @since 1.0.0
		 * @return string The decrypted string.
		 */
		public function decrypt( $input ) {
			// If the input is empty or not a string, then abandon ship.
			if ( empty( $input ) || ! is_string( $input ) ) {
				return '';
			}

			// Decrypt the input and return it.
			$base_64 = $input . str_repeat( '=', strlen( $input ) % 4 );
			$decode  = base64_decode( $base_64 ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
			return $decode;
		}

		/**
		 * Maybe self destruction.
		 *
		 * @since 1.0.0
		 * @return void
		 */
		public function maybe_self_destruction() {
			$destruct_plugin = STO_Loader::get_partner_details( 'successful_import_destruct' );

			if ( 'yes' !== $destruct_plugin ) {
				return;
			}

			update_option( 'sto_domain_destruct', '-' );
		}
	}

	/**
	 * Kicking this off by calling 'get_instance()' method
	 */
	STO_Controller::get_instance();

endif;
