<?php
/**
 * Button for refreshing the configs.
 *
 * @package EaLab\WP_Deployer
 */

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

if ( ! function_exists( 'deploy_sync_content__bundle_ui_switch_button' ) ) {
	/**
	 * Buttons for enabling or disabling the new bundle UI.
	 */
	function deploy_sync_content__bundle_ui_switch_button(): void {
		$endpoint_url = rest_url( 'deploy-sync-content/v1/deployment/config/bundle-ui/switch' );

		$label = __( 'Switch the bundle UI style', 'deploy-sync-content' );

		$current_style         = __( 'Current style', 'deploy-sync-content' );
		$interactive_bundle_ui = __( 'Interactive bundle UI', 'deploy-sync-content' );
		$classic_bundle_ui     = __( 'Classic bundle UI', 'deploy-sync-content' );

		$current_style_option     = get_option( '_transient_' . DEPLOY_SYNC_CONTENT__TRANSIENT_BUNDLE_FORM_V2, null ) ?? true;
		$interactive_style_active = $current_style_option ? '' : ' hidden';
		$classic_style_active     = $current_style_option ? ' hidden' : '';

		?>
		<deploy-sync-content--bundle-ui-switch-button data-url="<?php echo esc_attr( $endpoint_url ) ?>">
			<button class="button"><?php echo esc_html( $label ) ?></button>
			<p class="description style-text interactive<?php echo esc_attr( $interactive_style_active ) ?>"><?php echo esc_html( $current_style ) ?>: <?php echo esc_html( $interactive_bundle_ui ) ?></p>
			<p class="description style-text classic<?php echo esc_attr( $classic_style_active ) ?>"><?php echo esc_html( $current_style ) ?>: <?php echo esc_html( $classic_bundle_ui ) ?></p>
			<p class="description status-text"></p>
		</deploy-sync-content--bundle-ui-switch-button>
		<?php

		/**
		 * Enqueue the assets.
		 */
		wp_enqueue_style(
			'deploy-sync-content--bundle-ui-switch-button',
			plugins_url( '/admin/assets/css/bundle-ui-switch-button.css', DEPLOY_SYNC_CONTENT__PLUGIN_FILE ),
			array(),
			DEPLOY_SYNC_CONTENT__VERSION
		);

		wp_enqueue_script(
			'deploy-sync-content--bundle-ui-switch-button',
			plugins_url( '/admin/assets/js/bundle-ui-switch-button.js', DEPLOY_SYNC_CONTENT__PLUGIN_FILE ),
			array(),
			DEPLOY_SYNC_CONTENT__VERSION,
			true
		);

		// Attach the nonce to the script.
		wp_localize_script(
			'deploy-sync-content--bundle-ui-switch-button',
			'deploy_sync_content__button_settings',
			array(
				'rest' => array(
					'nonce' => wp_create_nonce( 'wp_rest' ),
				),
				'text' => array(
					'error'            => esc_html__( 'An error occurred. Please check your network status or the basic Deploy & Sync Content settings, or try again later.', 'deploy-sync-content' ),
					'updateError'      => esc_html__( 'The configuration could not be refreshed.', 'deploy-sync-content' ),
					'updateSuccessful' => esc_html__( 'The configuration has been updated successfully.', 'deploy-sync-content' ),
					'updating'         => esc_html__( 'Updating the configuration…', 'deploy-sync-content' ),
				),
			)
		);
	}
}

deploy_sync_content__bundle_ui_switch_button();
