<?php

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

/**
 * Registers the Gutenberg block editor sidebar panel.
 *
 * Single JS file (assets/js/gutenberg.js) for both builds. The premium
 * panels and meta-key constants in that file are wrapped in
 * `<fs_premium_only>` block-comment markers; the Freemius deployment
 * tool strips the marker content when building the WP.org free zip.
 * No separate file, no conditional enqueue.
 */
class DOIG_Gutenberg {

	public static function init() {
		add_action( 'enqueue_block_editor_assets', array( __CLASS__, 'enqueue_sidebar_assets' ) );
	}

	public static function enqueue_sidebar_assets() {
		$screen = get_current_screen();

		// Only enqueue for post types DOIG is eligible to control. Posts
		// and Pages always; in Premium, every public viewable CPT
		// registered on the site (NOT only the ones ticked under Settings
		// > Custom post types - the per-post override is independent of
		// the sitewide tick, matching the Posts/Pages parallel where the
		// sidebar appears on every Post and every Page regardless of the
		// sitewide tick state). Built-in non-content types (attachment,
		// revision, nav_menu_item) are excluded via the
		// is_post_type_viewable filter inside DOIG_CPTs::available_cpts().
		// 2.3.0: widened from supported_post_types() to eligible_post_types()
		// to fix the sidebar-not-appearing-on-unticked-CPTs bug.
		if ( ! $screen || ! in_array( $screen->post_type, DOIG_Cron::eligible_post_types(), true ) ) {
			return;
		}

		wp_enqueue_script(
			'doig-gutenberg',
			DOIG_PLUGIN_URL . 'assets/js/gutenberg.js',
			array( 'wp-plugins', 'wp-edit-post', 'wp-element', 'wp-components', 'wp-data', 'wp-core-data', 'wp-i18n', 'wp-api-fetch' ),
			DOIG_VERSION,
			true
		);

		wp_set_script_translations( 'doig-gutenberg', 'dynamic-og-image-generator' );

		// Freemius plan details for quota/upgrade notices in the sidebar.
		$plan      = doig_fs()->is_paying() ? doig_fs()->get_plan() : null;
		$plan_name = ( $plan && ! empty( $plan->name ) ) ? (string) $plan->name : 'free';

		// Sidebar data. Separately distributed builds extend this via the
		// doig_sidebar_localize_data filter.
		// isSiteUrlHttps reads the persistent `home` option directly rather
		// than home_url(). home_url() uses is_ssl() to adjust the scheme and
		// returns https:// in an admin request loaded over https even when
		// the persistent value is http://. Cron has no HTTP request context
		// so it sees the raw DB scheme - which is what the proxy ultimately
		// rejects. The DB value is the canonical truth here.
		$doig_home_scheme = wp_parse_url( (string) get_option( 'home', '' ), PHP_URL_SCHEME );

		$data = array(
			'isConnected'    => DOIG_License::is_connected(),
			'isSiteUrlHttps' => ( 'https' === $doig_home_scheme ),
			'isTestProxy'    => DOIG_License::is_test_proxy(),
			'testProxyUrl'   => DOIG_License::is_test_proxy() ? DOIG_License::proxy_base_url() : '',
			'wpUrlsSettings' => esc_url( admin_url( 'options-general.php' ) ),
			// 2.4.0: top-level menu, Settings UI lives at the doig-settings sub-page.
			'settingsUrl'    => esc_url( admin_url( 'admin.php?page=doig-settings' ) ),
			// `globalEnabled` drives "DOIG will emit anything for the current
			// post type by default" - read by the Regenerate Now button gate
			// and similar UI checks. Kept for back-compat with sidebar code
			// that branches on the boolean; 2.4.0 derives this from the
			// resolved Source mode (any non-Off type-default counts as
			// enabled).
			'globalEnabled'  => DOIG_Source_Resolver::MODE_OFF !== DOIG_Source_Resolver::type_default( $screen->post_type ),

			// 2.4.0: resolved Source mode for the current post type. Drives
			// the Inherit radio subtext ("Currently inheriting (<label>)") in
			// the sidebar Source RadioControl. One of the five terminal
			// MODE_* string constants.
			'globalSource'   => DOIG_Source_Resolver::type_default( $screen->post_type ),
			'restBase'       => rest_url( 'doig/v1' ),
			'nonce'          => wp_create_nonce( 'wp_rest' ),
			'isPremium'      => DOIG_License::is_premium(),
			// Used by quota_exceeded notice to determine whether to show an upgrade link.
			'planName'       => $plan_name,
			'upgradeUrl'     => esc_url( doig_fs()->get_upgrade_url() ),
		);

		/**
		 * Filter the data localized to the Gutenberg sidebar.
		 *
		 * The premium build hooks this to add data that only the premium
		 * sidebar panels need (supportedCountries, globalIpCountryCode,
		 * globalSaveToMediaLibrary). No-op in the free build.
		 *
		 * @param array $data The data array passed to wp_localize_script.
		 */
		$data = (array) apply_filters( 'doig_sidebar_localize_data', $data );

		// 2.6.2: per-error-code guidance map (hint + troubleshooting deep
		// link) for the generic failed notice. Added AFTER the filter so a
		// filter callback returning a rebuilt array cannot silently drop it.
		$data['errorGuidance'] = DOIG_Error_Guidance::localised();

		wp_localize_script( 'doig-gutenberg', 'doigSidebar', $data );

		wp_enqueue_style(
			'doig-gutenberg',
			DOIG_PLUGIN_URL . 'assets/css/admin.css',
			array( 'wp-components' ),
			DOIG_VERSION
		);
	}
}
