<?php
/**
 * One-click "Create Starter Gutenberg Template" — sister to
 * `ElementorStarterTemplate`. Produces a `wp_block` (reusable block) post
 * containing block markup that uses our SSR blocks (vehicle-card,
 * specs-table, contact-form, dealer-info), publishes it, and auto-selects
 * it in the AdminSettings option.
 *
 * Idempotent: re-clicking creates additional starter blocks rather than
 * overwriting (safer; the user can pick whichever).
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Admin;

defined( 'ABSPATH' ) || exit;
final class GutenbergStarterTemplate {

	public const ACTION = 'trx_ad_create_starter_gutenberg';
	public const NONCE  = 'trx_ad_create_starter_gutenberg_nonce';

	public function register(): void {
		add_action( 'admin_post_' . self::ACTION, array( $this, 'handle' ) );
	}

	public function handle(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission.', 'trx-auto-dealer' ), '', array( 'response' => 403 ) );
		}
		check_admin_referer( self::NONCE );

		$post_id = wp_insert_post(
			array(
				'post_title'   => __( 'Auto Dealer — Starter Single Listing (Gutenberg)', 'trx-auto-dealer' ),
				'post_status'  => 'publish',
				'post_type'    => 'wp_block',
				'post_content' => self::starterBlockMarkup(),
			),
			true
		);

		if ( is_wp_error( $post_id ) || (int) $post_id <= 0 ) {
			wp_die( esc_html__( 'Failed to create Gutenberg template.', 'trx-auto-dealer' ) );
		}
		$post_id = (int) $post_id;

		// Auto-select in settings.
		$settings = get_option( AdminSettings::OPTION_KEY, array() );
		if ( ! is_array( $settings ) ) {
			$settings = array();
		}
		$settings['single_layout']             = 'gutenberg';
		$settings['single_gutenberg_template'] = $post_id;
		update_option( AdminSettings::OPTION_KEY, $settings );

		$redirect = add_query_arg(
			array(
				'post_type'              => 'trx_ad_listing',
				'page'                   => AdminSettings::PAGE_SLUG,
				'trx_ad_starter_created' => $post_id,
				'kind'                   => 'gutenberg',
			),
			admin_url( 'edit.php' )
		);
		wp_safe_redirect( $redirect );
		exit;
	}

	/**
	 * Block markup for the starter — uses our SSR blocks. The blocks
	 * resolve `vehicleId` from the Query Loop / global context at render
	 * time, so the same reusable block renders any listing.
	 *
	 * Layout is two columns: media + specs on the left, contact form +
	 * dealer info on the right. Themes can edit the reusable block in
	 * the editor to change the layout without touching code.
	 */
	private static function starterBlockMarkup(): string {
		return '<!-- wp:group {"layout":{"type":"constrained"},"className":"trx-ad-single trx-ad-single--gutenberg"} -->
<div class="wp-block-group trx-ad-single trx-ad-single--gutenberg">
<!-- wp:trx-auto-dealer/vehicle-card /-->

<!-- wp:columns -->
<div class="wp-block-columns">
<!-- wp:column {"width":"66.66%"} -->
<div class="wp-block-column" style="flex-basis:66.66%">
<!-- wp:trx-auto-dealer/specs-table /-->
</div>
<!-- /wp:column -->

<!-- wp:column {"width":"33.33%"} -->
<div class="wp-block-column" style="flex-basis:33.33%">
<!-- wp:trx-auto-dealer/dealer-info /-->

<!-- wp:trx-auto-dealer/contact-form {"formId":"inquiry"} /-->
</div>
<!-- /wp:column -->
</div>
<!-- /wp:columns -->
</div>
<!-- /wp:group -->';
	}
}
