<?php
/**
 * One-click "Create Starter Template" for Elementor single-listing mode.
 *
 * The "Single Listing Layout → Elementor Template" option needs an
 * Elementor library template_id to actually render anything. Hand-rolling
 * one in Elementor's editor takes 30+ minutes and blocks first-run users.
 *
 * This class adds an admin-post handler that creates a minimal Elementor
 * library post (`elementor_library`) using our existing widgets
 * (vehicle-card, specs-table, contact-form, dealer-info), publishes it,
 * and auto-selects it in the AdminSettings option so the user can hit
 * "Update" once and have a working Elementor-mode page.
 *
 * Idempotent: re-clicking creates additional starter templates 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 ElementorStarterTemplate {

	public const ACTION = 'trx_ad_create_starter_elementor';
	public const NONCE  = 'trx_ad_create_starter_elementor_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 );

		if ( ! defined( 'ELEMENTOR_VERSION' ) ) {
			wp_die( esc_html__( 'Elementor is not active.', 'trx-auto-dealer' ) );
		}

		$post_id = wp_insert_post(
			array(
				'post_title'  => __( 'Auto Dealer — Starter Single Listing', 'trx-auto-dealer' ),
				'post_status' => 'publish',
				'post_type'   => 'elementor_library',
			),
			true
		);

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

		// Mark it as a 'page' template type so Elementor's editor opens it
		// without the section-locked UX.
		$encoded = wp_json_encode( self::starterData() );
		if ( false === $encoded ) {
			$encoded = '[]';
		}
		update_post_meta( $post_id, '_elementor_template_type', 'page' );
		update_post_meta( $post_id, '_elementor_edit_mode', 'builder' );
		update_post_meta( $post_id, '_elementor_data', wp_slash( $encoded ) );
		update_post_meta( $post_id, '_elementor_version', defined( 'ELEMENTOR_VERSION' ) ? ELEMENTOR_VERSION : '3.20.0' );

		// Auto-select in settings.
		$settings = get_option( AdminSettings::OPTION_KEY, array() );
		if ( ! is_array( $settings ) ) {
			$settings = array();
		}
		$settings['single_layout']             = 'elementor';
		$settings['single_elementor_template'] = (int) $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' => (int) $post_id,
			),
			admin_url( 'edit.php' )
		);
		wp_safe_redirect( $redirect );
		exit;
	}

	/**
	 * Minimal Elementor data structure using our widgets. Each widget's
	 * `widgetType` matches the slug Elementor registered (see
	 * `Elementor/ElementorIntegration::registerWidgets`).
	 *
	 * @return array<int, array<string, mixed>>
	 */
	private static function starterData(): array {
		// Single full-width section with one Single Listing widget.
		// Renders byte-identical to the plugin's PHP single template
		// because both call `parts/single-listing.php`. Customer can
		// edit and replace this widget with the individual ones
		// (media-slider, specs-highlights, vehicle-card, specs-table,
		// dealer-info, listing-form) for a custom layout.
		return array(
			array(
				'id'       => self::id(),
				'elType'   => 'section',
				'settings' => array(
					'structure'     => '100',
					'content_width' => array(
						'unit' => 'px',
						'size' => 1280,
					),
					'gap'           => 'no',
				),
				'elements' => array(
					array(
						'id'       => self::id(),
						'elType'   => 'column',
						'settings' => array( '_column_size' => 100 ),
						'elements' => array(
							self::widget( 'trx_ad_single_listing' ),
						),
					),
				),
			),
		);
	}

	/**
	 * @param array<string, mixed> $settings
	 * @return array<string, mixed>
	 */
	private static function widget( string $widgetType, array $settings = array() ): array {
		return array(
			'id'         => self::id(),
			'elType'     => 'widget',
			'widgetType' => $widgetType,
			'settings'   => $settings,
			'elements'   => array(),
		);
	}

	/**
	 * Elementor element IDs are 7-character hex strings.
	 */
	private static function id(): string {
		return substr( md5( uniqid( '', true ) ), 0, 7 );
	}
}
