<?php
declare( strict_types=1 );

namespace Flow\EditorialWorkflow;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Breakdance {

	const BUILDER_HOOK = 'unofficial_i_am_kevin_geary_master_of_all_things_css_and_html';

	public function boot(): void {
		add_action( self::BUILDER_HOOK, [ $this, 'render_panel' ], 1 );
		add_action( self::BUILDER_HOOK, [ $this, 'print_builder_assets' ], 999 );
	}

	public function render_panel(): void {
		if ( ! $this->is_builder_request() ) {
			return;
		}

		$post_id = $this->get_editor_post_id();
		if ( $post_id <= 0 ) {
			return;
		}

		$post_type = (string) get_post_type( $post_id );
		if ( '' === $post_type || ! Settings::is_post_type_supported( $post_type ) ) {
			return;
		}

		$post = get_post( $post_id );
		if ( ! $post instanceof \WP_Post ) {
			return;
		}

		$this->enqueue_builder_assets( $post_id );

		$review = DB::get_active_review( $post_id );
		$status = $review ? (string) $review->status : '';

		$template = (string) apply_filters(
			'flow_ew_breakdance_panel_template',
			FLOW_EW_PLUGIN_DIR . 'templates/breakdance/panel.php'
		);
		if ( is_readable( $template ) ) {
			include $template;
		}
	}

	private function enqueue_builder_assets( int $post_id ): void {
		Assets::enqueue_classic_editor_companion( $post_id );
		Assets::enqueue_builder_bundle( 'breakdance' );
	}

	public function print_builder_assets(): void {
		if ( ! $this->is_builder_request() ) {
			return;
		}
		if ( ! wp_script_is( 'flow-ew-classic-editor', 'enqueued' ) ) {
			return;
		}
		// Breakdance's loader template bypasses wp_head/wp_footer, so we print the
		// queued assets explicitly from its custom builder hook.
		wp_print_styles( [ 'flow-ew-classic-editor', 'flow-ew-breakdance' ] );
		wp_print_scripts( [ 'flow-ew-classic-editor', 'flow-ew-breakdance' ] );
		wp_print_footer_scripts();
	}

	private function is_builder_request(): bool {
		if ( ! defined( 'BREAKDANCE_MODE' ) ) {
			return false;
		}
		// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Builder-mode read-only query args.
		if ( ! isset( $_GET['breakdance'] ) ) {
			return false;
		}
		$mode = sanitize_key( wp_unslash( $_GET['breakdance'] ) );
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
		return 'builder' === $mode;
	}

	private function get_editor_post_id(): int {
		// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Builder-mode read-only query args.
		if ( ! isset( $_GET['id'] ) ) {
			return 0;
		}
		$post_id = absint( wp_unslash( $_GET['id'] ) );
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
		return $post_id;
	}
}
