<?php

namespace SugarCalendarBookings\Services\Admin;

use SugarCalendarBookings\Admin\Assets;
use SugarCalendarBookings\Plugin;
use SugarCalendarBookings\Support\Bootable;

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

/**
 * Conditionally enqueue the embed-service editor script.
 *
 * When the block editor is loaded with a `scb_embed_service` query parameter,
 * this class enqueues a small JS file that inserts the Booking Form block
 * (pre-configured with the target service) into the editor without saving.
 *
 * @since 1.5.0
 */
class EmbedServiceEditorScript implements Bootable {

	/**
	 * Register hooks.
	 *
	 * @since 1.5.0
	 */
	public function hooks(): void {

		add_action( 'enqueue_block_editor_assets', [ $this, 'enqueue_editor_script' ] );
	}

	/**
	 * Enqueue the embed service editor script.
	 *
	 * Only enqueues when `scb_embed_service` query param is present and valid.
	 *
	 * @since 1.5.0
	 */
	public function enqueue_editor_script(): void {

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only check, no state change.
		$service_id = isset( $_GET['scb_embed_service'] ) ? absint( $_GET['scb_embed_service'] ) : 0;

		if ( $service_id === 0 ) {
			return;
		}

		$assets   = Plugin::get( Assets::class );
		$manifest = $assets->get_asset_manifest( 'admin/embed-service-in-editor' );

		if ( $manifest === false ) {
			return;
		}

		$handle = 'sugar-calendar-bookings-embed-service-in-editor';

		wp_enqueue_script(
			$handle,
			$assets->get_src( 'admin/embed-service-in-editor.js' ),
			$manifest['dependencies'],
			$assets->is_dev() ? $manifest['version'] : SCBOOKINGS_PLUGIN_VERSION,
			true
		);

		wp_localize_script(
			$handle,
			'scb_embed_data',
			[
				'serviceId' => $service_id,
			]
		);
	}
}
