<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class Sifency_Addons_Theme_Builder_Master {
	private static $instance                      = null;
	private static $option_key                    = 'sifency_license_key';
	private static $token_key                     = 'sifency_env_token';
	private static $salt                          = 'SfNcY_X9@#_SeCrEt_sk_live_51N_7f9Xq2z9W8kM2B4v5R7x8Z9w0_K1m2N3b4V5c6X7z8Q9w0E1r2T3y4U5i6O7p8A9s0D1f2G3h4J5k6L7';
	private static $bundle_salt                   = 'sk_live_51N_7f9Xq2z9W8kM2B4v5R7x8Z9w0_K1m2N3b4V5c6X7z8Q9w0E1r2T3y4U5i6O7p8A9s0D1f2G3h4J5k6L7';
	private static $is_sync_state                 = null;
	public static $frontend_render                = null;
	public static $sifency_addons_frontend_render = null;

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		if ( is_admin() ) {
			new Sifency_Addons_CPT_Modules_Settings();
		}
		Sifency_Addons_CPT_Module_Manager::load_enabled_modules();
		$this->init_components();
		add_action( 'admin_init', array( $this, 'register_passcode_settings' ) );
		add_action( 'admin_post_sifency_deactivate_license', array( $this, 'handle_sifency_addons_disappear' ) );
		add_action( 'admin_notices', array( $this, 'show_sync_notices' ) );
		add_action( 'admin_init', array( $this, 'silent_background_validation' ) );
		add_action( 'init', array( $this, 'initialize_custom_frameworks' ), 1 );
	}

	private function init_components() {
		new Sifency_CPT();
		new Sifency_Addons_Header_Loader();
		new Sifency_Addons_Sub_Header_Render();
		new Sifency_Addons_Footer_Loader();
		new Sifency_Addons_404_Page_Render();
		new Sifency_Addons_Frontend_Scrollup();
		new Sifency_Addons_Frontend_Popup_Loader();
		new Sifency_Addons_Blog_Archive_Render();
		new Sifency_Addons_TB_Blog_Single_Render();
		if ( is_admin() ) {
			new Sifency_Theme_Builder_Admin();
			new Sifency_Ajax();
			new Sifency_Addons_TB_Assets_Manager();
		}
	}
	public function initialize_custom_frameworks() {
		if ( function_exists( 'sifency_get_all_metabox_definitions' ) ) {
			$metabox_definitions = sifency_get_all_metabox_definitions();
			if ( ! empty( $metabox_definitions ) ) {
				new Sifency_Metabox( $metabox_definitions );
			}
		}

		if ( function_exists( 'sifency_addons_get_user_profile_definitions' ) ) {
			$profile_definitions = sifency_addons_get_user_profile_definitions();
			if ( ! empty( $profile_definitions ) ) {
				new Sifency_Addons_User_Profile( $profile_definitions );
			}
		}
		if ( function_exists( 'sifency_get_nav_menu_definitions' ) ) {
			$nav_menu_definitions = sifency_get_nav_menu_definitions();
			if ( ! empty( $nav_menu_definitions ) ) {
				new Sifency_Nav_Menu_Fields( $nav_menu_definitions );
			}
		}
	}
	public static function sifency_addons_selective_environment() {
		$active_pass_selective_environment = wp_get_theme();
		if ( $active_pass_selective_environment->parent() ) {
			$active_pass_selective_environment = $active_pass_selective_environment->parent();
		}
		$theme_template                                   = $active_pass_selective_environment->get_template();
		$allowed_archive_pass_selective_environment       = array( 'axist' );
		$allowed_archive_valid_pass_selective_environment = false;
		foreach ( $allowed_archive_pass_selective_environment as $allowed_name ) {
			if ( stripos( $theme_template, $allowed_name ) !== false ) {
				$allowed_archive_valid_pass_selective_environment = true;
				break;
			}
		}
		if ( ! $allowed_archive_valid_pass_selective_environment ) {
			return false;
		}
		$theme_dir_success_selective_environment = get_template_directory();
		if ( ! file_exists( $theme_dir_success_selective_environment . '/inc/hello-sifency.php' ) ) {
			return false;
		}

		$bundle_token   = apply_filters( 'sifency_addons_selective_environmental_api', '' );
		$expected_token = md5( home_url() . self::$bundle_salt );

		if ( empty( $bundle_token ) || ! hash_equals( $expected_token, $bundle_token ) ) {
			return false;
		}

		return true;
	}
	public function render_sifency_addons_hidden_code_form() {
		?>
		<div class="sifency-license-wrapper">
			<h2><?php esc_html_e( 'License Activation', 'sifency-addons' ); ?></h2>
			
			<?php
			if ( self::sifency_addons_selective_environment() ) :
				?>
				<div class="notice notice-success inline">
					<p><strong><?php esc_html_e( 'Premium features are activated', 'sifency-addons' ); ?></strong></p>
				</div>
			<?php else : ?>
				
				<?php if ( ! self::is_sync_valid() ) : ?>
					<p><?php esc_html_e( 'Enter your license key to unlock premium features and receive automatic updates.', 'sifency-addons' ); ?></p>
				<?php endif; ?>
				
				<?php
				if ( get_option( self::$option_key ) ) {
					if ( self::is_sync_valid() ) {
						echo '<div class="notice notice-success inline"><p><strong>' . esc_html__( 'License is active!', 'sifency-addons' ) . '</strong></p></div>';
					} else {
						echo '<div class="notice notice-error inline"><p><strong>' . esc_html__( 'License is invalid or expired.', 'sifency-addons' ) . '</strong></p></div>';
					}
				}
				?>
				<form method="post" action="options.php" novalidate="novalidate">
					<?php
					settings_fields( 'sifency_license_options' );
					do_settings_sections( 'sifency_license_page' );

					if ( ! self::is_sync_valid() ) {
						submit_button( esc_html__( 'Activate License', 'sifency-addons' ) );
					}
					?>
				</form>

			<?php endif; ?>
		</div>
		<?php
	}

	public function register_passcode_settings() {
		register_setting( 'sifency_license_options', self::$option_key, array( $this, 'sanitize_and_validate_sifency_addons_key' ) );
		add_settings_section( 'sifency_license_section', null, null, 'sifency_license_page' );

		if ( ! self::sifency_addons_selective_environment() ) {
			add_settings_field( 'sifency_license_key_field', esc_html__( 'License Key', 'sifency-addons' ), array( $this, 'render_disappear_key_field' ), 'sifency_license_page', 'sifency_license_section' );
		}
	}

	public function sanitize_and_validate_sifency_addons_key( $new_key ) {
		$sanitized_key = trim( sanitize_text_field( $new_key ) );
		$old_key       = get_option( self::$option_key );

		if ( $sanitized_key === $old_key ) {
			return $sanitized_key;
		}

		delete_option( self::$token_key );

		if ( empty( $sanitized_key ) ) {
			add_settings_error( 'sifency_license_notices', 'license-cleared', esc_html__( 'License key removed.', 'sifency-addons' ), 'warning' );
			return '';
		}

		$validation_result = self::_perform_api_validation( $sanitized_key );

		if ( $validation_result['is_valid'] ) {
			add_settings_error( 'sifency_license_notices', 'license-activated', esc_html__( 'License activated successfully!', 'sifency-addons' ), 'success' );

			$secure_token = self::generate_secure_token( $sanitized_key );
			update_option( self::$token_key, $secure_token );
			set_transient( 'sifency_api_check_time', time(), 7 * DAY_IN_SECONDS );
		} else {
			$error_message = $validation_result['message'] ?: esc_html__( 'The license key is invalid or could not be verified.', 'sifency-addons' );
			add_settings_error( 'sifency_license_notices', 'license-invalid', $error_message, 'error' );
		}

		return $sanitized_key;
	}

	public function render_disappear_key_field() {
		$license_key = get_option( self::$option_key, '' );
		$is_valid    = self::is_sync_valid();
		echo '<input type="text" id="sifency_license_key_field" name="' . esc_attr( self::$option_key ) . '" value="' . esc_attr( $license_key ) . '" class="regular-text" placeholder="xxxxxxxx-xxxxxxxx-xxxxxxxx-xxxxxxxx" ' . ( $is_valid ? 'disabled' : '' ) . '/>';
		if ( $is_valid && ! self::sifency_addons_selective_environment() ) {
			$deactivate_url = wp_nonce_url( admin_url( 'admin-post.php?action=sifency_deactivate_license' ), 'sifency_deactivate_nonce', '_wpnonce' );
			echo ' <a href="' . esc_url( $deactivate_url ) . '" class="button button-secondary sifency-admin-btn sifency-deactive-licence">' . esc_html__( 'Deactivate License', 'sifency-addons' ) . '</a>';
			echo '<p class="description">' . esc_html__( 'Deactivate to use this key on another site.', 'sifency-addons' ) . '</p>';
		}
	}

	public function handle_sifency_addons_disappear() {
		if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'sifency_deactivate_nonce' ) ) {
			wp_die( 'Security check failed!' ); }
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( 'You do not have permission.' ); }

		delete_option( self::$option_key );
		delete_option( self::$token_key );
		delete_transient( 'sifency_api_check_time' );

		self::$is_sync_state = null;
		wp_safe_redirect( wp_get_referer() );
		exit;
	}

	public function show_sync_notices() {
		settings_errors( 'sifency_license_notices' );
	}

	private static function _perform_api_validation( $license_key ) {
		$sifency_product_id = 823881;
		$endpoint           = base64_decode( 'aHR0cHM6Ly9hcGkubGVtb25zcXVlZXp5LmNvbS92MS9saWNlbnNlcy92YWxpZGF0ZQ==' );

		$response = wp_remote_post(
			$endpoint,
			array(
				'timeout' => 20,
				'headers' => array(
					'Accept'       => 'application/json',
					'Content-Type' => 'application/x-www-form-urlencoded',
				),
				'body'    => array(
					'license_key'   => $license_key,
					'instance_name' => home_url(),
				),
			)
		);

		if ( is_wp_error( $response ) ) {
			return array(
				'is_valid' => false,
				'message'  => 'Server connection failed.',
			);
		}

		$body = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( isset( $body['valid'] ) && $body['valid'] === true ) {
			if ( (int) $body['meta']['product_id'] === (int) $sifency_product_id ) {
				update_option( 'sifency_license_instance_id', $body['instance']['id'] );
				return array(
					'is_valid' => true,
					'message'  => '',
				);
			} else {
				return array(
					'is_valid' => false,
					'message'  => 'This license key does not belong to Sifency Theme.',
				);
			}
		}

		$error = $body['error'] ?? 'Invalid or inactive license key.';
		return array(
			'is_valid' => false,
			'message'  => $error,
		);
	}

	public function silent_background_validation() {
		if ( ! self::is_sync_valid() || self::sifency_addons_selective_environment() ) {
			return;
		}

		if ( false === get_transient( 'sifency_api_check_time' ) ) {
			$saved_key  = get_option( self::$option_key );
			$validation = self::_perform_api_validation( $saved_key );

			if ( ! $validation['is_valid'] ) {
				delete_option( self::$token_key );
			} else {
				set_transient( 'sifency_api_check_time', time(), 7 * DAY_IN_SECONDS );
			}
		}
	}

	private static function generate_secure_token( $key ) {
		return wp_hash( $key . $_SERVER['HTTP_HOST'] . self::$salt );
	}

	public static function is_sync_valid() {
		if ( self::sifency_addons_selective_environment() ) {
			return true;
		}
		$saved_key   = get_option( self::$option_key );
		$saved_token = get_option( self::$token_key );

		if ( empty( $saved_key ) || empty( $saved_token ) ) {
			return false;
		}
		$expected_token = self::generate_secure_token( $saved_key );

		return hash_equals( $expected_token, $saved_token );
	}

	public static function sync_environment_state() {
		if ( null !== self::$is_sync_state ) {
			return self::$is_sync_state;
		}

		$is_valid = self::is_sync_valid();

		if ( ! $is_valid ) {
			self::$is_sync_state = false;
			return false;
		}

		self::$is_sync_state = array(
			'status'     => 'active',
			'hash_check' => wp_hash( self::$salt ),
			'signature'  => md5( $_SERVER['HTTP_HOST'] ),
		);

		return self::$is_sync_state;
	}

	public static function render_fallback_dom() {
		$activation_link = admin_url( 'admin.php?page=sifency_license_page' );

		ob_start();
		?>
		<div class="sifency-sync-widget-alert">
			<div class="sifency-alert-icon"><i class="eicon-lock"></i></div>
			<div class="sifency-alert-text">
				<h4 class="sifency-alert-title"><?php esc_html_e( 'Premium Widget Locked', 'sifency-addons' ); ?></h4>
				<p class="sifency-alert-desc"><?php esc_html_e( 'You need to activate Sifency Addons Pro to use this widget.', 'sifency-addons' ); ?></p>
			</div>
			<div class="sifency-alert-action">
				<a href="<?php echo esc_url( $activation_link ); ?>" class="sifency-btn-activate" target="_blank"><?php esc_html_e( 'Activate Pro', 'sifency-addons' ); ?></a>
			</div>
		</div>
		<?php
		return ob_get_clean();
	}

	public static function get_current_theme_builder_type() {
		$post_id = 0;
		if ( isset( $_REQUEST['post'] ) ) {
			$post_id = absint( $_REQUEST['post'] );
		} elseif ( isset( $_REQUEST['editor_post_id'] ) ) {
			$post_id = absint( $_REQUEST['editor_post_id'] );
		}

		if ( ! $post_id ) {
			return false; }
		if ( get_post_type( $post_id ) !== 'themebuilder' ) {
			return false; }

		$terms = wp_get_post_terms( $post_id, 'sifency_builder_type', array( 'fields' => 'slugs' ) );

		if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
			return $terms[0];
		}
		return false;
	}
}
