<?php
/**
 * Elementor integration bootstrap.
 *
 * @package SEOvaultSEO
 */

namespace SEOvaultSEO\Integrations\Elementor;

/**
 * Registers Elementor editor hooks without loading editor assets elsewhere.
 */
class Bootstrap {

	/**
	 * Whether init() has already run.
	 *
	 * @var bool
	 */
	private static $initialized = false;

	/**
	 * Register integration hooks.
	 *
	 * The AJAX save hook must be available on admin-ajax.php, where the
	 * Elementor editor request query is not present.
	 *
	 * @return void
	 */
	public static function init() {
		if ( self::$initialized ) {
			return;
		}

		self::$initialized = true;

		SaveHandler::init();
		add_action( 'init', array( __CLASS__, 'register_editor_hooks' ), PHP_INT_MAX );
	}

	/**
	 * Register asset hooks for an eligible Elementor editor request.
	 *
	 * @return void
	 */
	public static function register_editor_hooks() {
		if ( ! self::is_editor_request() ) {
			return;
		}

		if ( ! class_exists( '\Elementor\Plugin' ) ) {
			return;
		}

		if ( ! \SEOvaultSEO\Compatibility\Detector::should_output_seo() ) {
			return;
		}

		$post_id = self::get_request_post_id();
		$post    = $post_id ? get_post( $post_id ) : null;

		if ( ! $post || ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		$public_post_types = get_post_types( array( 'public' => true ), 'names' );
		$excluded_types    = apply_filters( 'seovaultseo_excluded_post_types', array( 'attachment' ) );

		if ( ! in_array( $post->post_type, $public_post_types, true ) || in_array( $post->post_type, $excluded_types, true ) ) {
			return;
		}

		add_action( 'elementor/editor/before_enqueue_scripts', array( EditorAssets::class, 'enqueue' ) );
	}

	/**
	 * Whether the current request is the full-screen Elementor post editor.
	 *
	 * This is a routing check only; authorization is enforced separately.
	 *
	 * @return bool
	 */
	public static function is_editor_request() {
		global $pagenow;

		if ( 'post.php' !== $pagenow ) {
			return false;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only request routing check.
		if ( ! isset( $_GET['action'] ) || ! is_string( $_GET['action'] ) ) {
			return false;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only request routing check.
		return 'elementor' === sanitize_key( wp_unslash( $_GET['action'] ) );
	}

	/**
	 * Read the post ID from the Elementor editor request.
	 *
	 * @return int
	 */
	public static function get_request_post_id() {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only request routing value.
		if ( ! isset( $_GET['post'] ) || ! is_scalar( $_GET['post'] ) ) {
			return 0;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Cast to an integer for lookup only.
		return absint( wp_unslash( $_GET['post'] ) );
	}
}
