<?php
/**
 * Auto-seeded Gutenberg + Elementor starter single-listing templates.
 *
 * Extracted from `Activator` in QUALITY-IMPROVEMENT-PLAN T2-2e — the seed
 * logic + the two static template-data builders made up ~190L of literal
 * markup/data that didn't belong in the activation orchestrator.
 *
 * The seeded posts are option-tracked + de-duplicated by title so re-runs
 * (every plugin activation, every SEED_VERSION bump via
 * `Activator::ensureUpgraded`) are idempotent. Phase 19 discovery meta
 * (`Activator::TEMPLATE_KIND_META` / `TEMPLATE_ORIGIN_META`) is stamped on
 * the canonical post so the Templates admin page can find it.
 *
 * Customer-created templates and admin-button-created copies are never
 * touched here — only the post(s) matching our exact seed title.
 *
 * @package ThemeREX\AutoDealer\Core\Activation
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Core\Activation;

defined( 'ABSPATH' ) || exit;

use ThemeREX\AutoDealer\Core\Activator;

final class StarterTemplates {

	private const GUTENBERG_TITLE = 'Auto Dealer — Starter Single Listing (Gutenberg)';
	private const ELEMENTOR_TITLE = 'Auto Dealer — Starter Single Listing (Elementor)';

	/**
	 * Seed one Gutenberg `wp_block` and (if Elementor is active) one
	 * `elementor_library` template. Idempotent.
	 *
	 * @return void
	 */
	public static function seed(): void {
		self::seedGutenberg();
		if ( defined( 'ELEMENTOR_VERSION' ) ) {
			self::seedElementor();
		}
	}

	private static function seedGutenberg(): void {
		global $wpdb;

		$gut_id       = (int) get_option( Activator::DEFAULT_GUTENBERG_TEMPLATE_OPTION, 0 );
		$gut_post     = $gut_id > 0 ? get_post( $gut_id ) : null;
		$gut_existing = $wpdb->get_col(
			$wpdb->prepare(
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery
				"SELECT ID FROM {$wpdb->posts} WHERE post_type=%s AND post_title=%s AND post_status<>'trash' ORDER BY ID DESC",
				'wp_block',
				self::GUTENBERG_TITLE
			)
		);
		if ( ! ( $gut_post instanceof \WP_Post ) || 'wp_block' !== $gut_post->post_type || 'trash' === $gut_post->post_status ) {
			if ( ! empty( $gut_existing ) ) {
				// Adopt the newest existing one as the canonical starter.
				$gut_id = (int) $gut_existing[0];
				update_option( Activator::DEFAULT_GUTENBERG_TEMPLATE_OPTION, $gut_id );
			} else {
				$new_id = wp_insert_post(
					array(
						'post_title'   => self::GUTENBERG_TITLE,
						'post_status'  => 'publish',
						'post_type'    => 'wp_block',
						'post_content' => self::gutenbergStarterMarkup(),
					),
					true
				);
				if ( ! is_wp_error( $new_id ) && (int) $new_id > 0 ) {
					$gut_id = (int) $new_id;
					update_option( Activator::DEFAULT_GUTENBERG_TEMPLATE_OPTION, $gut_id );
				}
			}
		}
		// Backfill Phase 19 discovery meta on the canonical starter
		// (idempotent — `update_post_meta` overwrites only when changed).
		if ( $gut_id > 0 ) {
			update_post_meta( $gut_id, Activator::TEMPLATE_KIND_META, Activator::TEMPLATE_KIND_VALUE );
			update_post_meta( $gut_id, Activator::TEMPLATE_ORIGIN_META, 'seed' );
		}
		// Delete any other copies left over from previous installs.
		foreach ( $gut_existing as $dup_id ) {
			$dup_id = (int) $dup_id;
			if ( $dup_id !== $gut_id && $dup_id > 0 ) {
				wp_delete_post( $dup_id, true );
			}
		}
	}

	private static function seedElementor(): void {
		global $wpdb;

		$ele_id       = (int) get_option( Activator::DEFAULT_ELEMENTOR_TEMPLATE_OPTION, 0 );
		$ele_post     = $ele_id > 0 ? get_post( $ele_id ) : null;
		$ele_existing = $wpdb->get_col(
			$wpdb->prepare(
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery
				"SELECT ID FROM {$wpdb->posts} WHERE post_type=%s AND post_title=%s AND post_status<>'trash' ORDER BY ID DESC",
				'elementor_library',
				self::ELEMENTOR_TITLE
			)
		);
		if ( ! ( $ele_post instanceof \WP_Post ) || 'elementor_library' !== $ele_post->post_type || 'trash' === $ele_post->post_status ) {
			if ( ! empty( $ele_existing ) ) {
				$ele_id = (int) $ele_existing[0];
				update_option( Activator::DEFAULT_ELEMENTOR_TEMPLATE_OPTION, $ele_id );
			} else {
				$new_id = wp_insert_post(
					array(
						'post_title'  => self::ELEMENTOR_TITLE,
						'post_status' => 'publish',
						'post_type'   => 'elementor_library',
					),
					true
				);
				if ( ! is_wp_error( $new_id ) && (int) $new_id > 0 ) {
					$encoded = wp_json_encode( self::elementorStarterData() );
					if ( false === $encoded ) {
						$encoded = '[]';
					}
					update_post_meta( (int) $new_id, '_elementor_template_type', 'page' );
					update_post_meta( (int) $new_id, '_elementor_edit_mode', 'builder' );
					update_post_meta( (int) $new_id, '_elementor_data', wp_slash( $encoded ) );
					// `seedElementor()` is only ever called from `seed()` after a
					// `defined('ELEMENTOR_VERSION')` check, but PHPStan can't see
					// the guard across the static-call boundary. Re-check inline.
					update_post_meta( (int) $new_id, '_elementor_version', defined( 'ELEMENTOR_VERSION' ) ? ELEMENTOR_VERSION : '' );
					$ele_id = (int) $new_id;
					update_option( Activator::DEFAULT_ELEMENTOR_TEMPLATE_OPTION, $ele_id );
				}
			}
		}
		// Backfill Phase 19 discovery meta on the canonical Elementor starter.
		if ( $ele_id > 0 ) {
			update_post_meta( $ele_id, Activator::TEMPLATE_KIND_META, Activator::TEMPLATE_KIND_VALUE );
			update_post_meta( $ele_id, Activator::TEMPLATE_ORIGIN_META, 'seed' );
		}
		foreach ( $ele_existing as $dup_id ) {
			$dup_id = (int) $dup_id;
			if ( $dup_id !== $ele_id && $dup_id > 0 ) {
				wp_delete_post( $dup_id, true );
			}
		}
	}

	/**
	 * Block markup for the auto-seeded Gutenberg starter — kept in sync
	 * with `Admin\GutenbergStarterTemplate::starterBlockMarkup()` (the
	 * one-click admin button creates the same content).
	 */
	private static function gutenbergStarterMarkup(): string {
		// Single block that renders the full default layout via the
		// `parts/single-listing.php` template part — byte-identical to
		// the plugin's PHP single template. Customers can still break
		// this apart and replace pieces with the individual blocks
		// (media-slider, specs-highlights, vehicle-card, specs-table,
		// similar-vehicles, recently-viewed, dealer-info, contact-form)
		// if they want a customized layout.
		return '<!-- wp:trx-auto-dealer/single-listing /-->';
	}

	/**
	 * Elementor data structure for the auto-seeded starter — kept in sync
	 * with `Admin\ElementorStarterTemplate::starterData()`.
	 *
	 * @return array<int, array<string, mixed>>
	 */
	private static function elementorStarterData(): array {
		$id     = static fn(): string => substr( md5( uniqid( '', true ) ), 0, 7 );
		$widget = static function ( string $type, array $settings = array() ) use ( $id ): array {
			return array(
				'id'         => $id(),
				'elType'     => 'widget',
				'widgetType' => $type,
				'settings'   => $settings,
				'elements'   => 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`. Customers can
		// edit the template in Elementor and swap this widget for the
		// individual ones (media-slider, specs-highlights, vehicle-card,
		// specs-table, dealer-info, listing-form) if they want a
		// custom layout.
		return array(
			array(
				'id'       => $id(),
				'elType'   => 'section',
				'settings' => array(
					'structure'     => '100',
					'content_width' => array(
						'unit' => 'px',
						'size' => 1280,
					),
					'gap'           => 'no',
				),
				'elements' => array(
					array(
						'id'       => $id(),
						'elType'   => 'column',
						'settings' => array( '_column_size' => 100 ),
						'elements' => array(
							$widget( 'trx_ad_single_listing' ),
						),
					),
				),
			),
		);
	}
}
