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

/**
 * Main class for the Sifency Theme Builder.
 * This class acts as a controller, initializing all hooks and functionality.
 */
final class Sifency_Addons_Theme_Builder_Master {
	private static $instance = null;
	private static $option_key    = 'sifency_license_key';
	private static $transient_key = 'sifency_ls_license_status';
	private static $is_premium    = null;
	public static $frontend_render = null; 
	public static $sifency_addons_frontend_render = null; 
	/**
	 * Ensures only one instance of the class is loaded.
	 * @return Sifency_Addons_Theme_Builder_Master - Main instance.
	 */
	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', [ $this, 'register_license_settings' ] );
		add_action( 'admin_post_sifency_deactivate_license', [ $this, 'handle_license_deactivation' ] );
		add_action( 'admin_notices', [ $this, 'show_license_notices' ] );
	}

	private function init_components() {
		new Sifency_CPT();
		new Sifency_Header_Loader();
		new Sifency_Below_Header_Render();
		new Sifency_Footer_Loader();
		new Sifency_404_Render();
		new Sifency_Frontend_Scrollup();
		new Sifency_Frontend_Popup();
		if ( is_admin() ) {
			new Sifency_Theme_Builder_Admin();
			new Sifency_Ajax();
			new Sifency_Assets();
		}
	}

	public function render_license_activation_form() {
		?>
		<div class="sifency-license-wrapper">
			<h2><?php esc_html_e( 'License Activation', 'sifency-addons' ); ?></h2>
			<?php if ( ! self::is_license_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_license_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_license_valid() ) {
					submit_button( esc_html__( 'Activate License', 'sifency-addons' ) );
				}
				?>
			</form>
		</div>
		<?php
	}

	public function register_license_settings() {
		register_setting( 'sifency_license_options', self::$option_key, [ $this, 'sanitize_and_validate_license_key' ] );
		add_settings_section( 'sifency_license_section', null, null, 'sifency_license_page' );
		add_settings_field( 'sifency_license_key_field', esc_html__( 'License Key', 'sifency-addons' ), [ $this, 'render_license_key_field' ], 'sifency_license_page', 'sifency_license_section' );
	}

	public function sanitize_and_validate_license_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_transient( self::$transient_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' );
			set_transient( self::$transient_key, 'valid', 12 * HOUR_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' );
			set_transient( self::$transient_key, 'invalid', 12 * HOUR_IN_SECONDS );
		}
		return $sanitized_key;
	}

	public function render_license_key_field() {
		$license_key = get_option( self::$option_key, '' );
		$is_valid    = self::is_license_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 ) {
			$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_license_deactivation() {
		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_transient( self::$transient_key );
		self::$is_premium = null;
		wp_safe_redirect( wp_get_referer() );
		exit;
	}

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

private static function _perform_api_validation( $license_key ) {
		
		$sifency_product_id = 706220;

		$response = wp_remote_post(
			'https://api.lemonsqueezy.com/v1/licenses/activate',
			[
				'timeout' => 20,
				'headers' => [
					'Accept'       => 'application/json',
					'Content-Type' => 'application/x-www-form-urlencoded',
				],
				'body' => [
					'license_key'   => $license_key,
					'instance_name' => home_url(),
				],
			]
		);

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

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

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

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

	public static function is_license_valid() {
		return 'valid' === get_transient( self::$transient_key );
	}

	public static function sifency_addons_is_legal() {
		if ( null !== self::$is_premium ) {
			return self::$is_premium;
		}
		if ( ! function_exists( 'is_plugin_active' ) ) {
			include_once ABSPATH . 'wp-admin/includes/plugin.php';
		}
		$theme_slug        = get_stylesheet();
		$theme_core_plugin = $theme_slug . '-core/' . $theme_slug . '-core.php';
		$plugin_one        = 'sifency-addons/sifency-addons.php';
		$plugins_ok        = ( is_plugin_active( $theme_core_plugin ) && is_plugin_active( $plugin_one ) );
		$license_ok        = self::is_license_valid();
		self::$is_premium = ( $plugins_ok || $license_ok );
		return self::$is_premium;
	}
}