<?php
/**
 * Layouts tab — single-listing renderer selection (plugin default /
 * Gutenberg / Elementor) and template picker.
 *
 * Extracted from AdminSettings per QUALITY-IMPROVEMENT-PLAN.md §T2-2.
 *
 * Shares the main `OPTION_GROUP` with the General tab — settings save through
 * the central `register_setting`/`sanitize` pipeline.
 *
 * @package ThemeREX\AutoDealer\Admin\Settings\Tabs
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Admin\Settings\Tabs;

defined( 'ABSPATH' ) || exit;

use ThemeREX\AutoDealer\Admin\AdminSettings;
use ThemeREX\AutoDealer\Admin\ElementorStarterTemplate;
use ThemeREX\AutoDealer\Admin\GutenbergStarterTemplate;
use ThemeREX\AutoDealer\Admin\Settings\AbstractSettingsTab;

final class LayoutsTab extends AbstractSettingsTab {

	public function getKey(): string {
		return 'layouts';
	}

	public function getLabel(): string {
		return __( 'Single Listing', 'trx-auto-dealer' );
	}

	public function register(): void {
		$page = AdminSettings::PAGE_SLUG . '_layouts';

		add_settings_section(
			'trx_ad_layouts',
			__( 'Single Listing Page', 'trx-auto-dealer' ),
			array( $this, 'renderSectionDescription' ),
			$page
		);

		add_settings_field(
			'single_layout',
			__( 'Active layout', 'trx-auto-dealer' ),
			array( $this, 'renderSingleLayout' ),
			$page,
			'trx_ad_layouts'
		);

		add_settings_field(
			'single_listing_template',
			__( 'Template', 'trx-auto-dealer' ),
			array( $this, 'renderSingleListingTemplate' ),
			$page,
			'trx_ad_layouts'
		);
	}

	public function render(): void {
		?>
		<form method="post" action="options.php">
			<?php
			settings_fields( 'trx_ad_settings_group' );
			do_settings_sections( AdminSettings::PAGE_SLUG . '_layouts' );
			submit_button();
			?>
		</form>
		<?php
	}

	public function renderSectionDescription(): void {
		printf(
			'<p>%s</p>',
			esc_html__( 'Choose which renderer drives single-listing pages. Three options ship as starter templates on activation; you can replace any with your own reusable block / Elementor template.', 'trx-auto-dealer' )
		);
	}

	public function renderSingleLayout(): void {
		$settings      = AdminSettings::getSettings();
		$current       = $settings['single_layout'];
		$has_elementor = defined( 'ELEMENTOR_VERSION' );

		printf( '<select name="%s[single_layout]" id="trx_ad_single_layout">', esc_attr( AdminSettings::OPTION_KEY ) );
		printf(
			'<option value="default"%s>%s</option>',
			selected( $current, 'default', false ),
			esc_html__( 'Plugin Default', 'trx-auto-dealer' )
		);
		printf(
			'<option value="gutenberg"%s>%s</option>',
			selected( $current, 'gutenberg', false ),
			esc_html__( 'Gutenberg Template', 'trx-auto-dealer' )
		);
		printf(
			'<option value="elementor"%s%s>%s</option>',
			selected( $current, 'elementor', false ),
			$has_elementor ? '' : ' disabled',
			esc_html__( 'Elementor Template', 'trx-auto-dealer' )
		);
		echo '</select>';

		echo '<div class="description" style="margin-top:8px; max-width:640px;">';
		echo '<p><strong>' . esc_html__( 'Plugin Default', 'trx-auto-dealer' ) . '</strong> — ';
		echo esc_html__( 'a fully-styled single-listing page rendered by the plugin. Includes media gallery, price header, trust badges, specs table, contact form, and dealer card. Works with any theme. Recommended for most sites.', 'trx-auto-dealer' );
		echo '</p>';
		echo '<p><strong>' . esc_html__( 'Gutenberg Template', 'trx-auto-dealer' ) . '</strong> — ';
		echo esc_html__( 'render single listings through a reusable block (`wp_block`) you design in the block editor. Pick a reusable block in "Single Listing Template" below. Use "Create Starter Gutenberg Template" to generate a default reusable block with our blocks pre-arranged.', 'trx-auto-dealer' );
		echo '</p>';
		echo '<p><strong>' . esc_html__( 'Elementor Template', 'trx-auto-dealer' ) . '</strong> — ';
		if ( $has_elementor ) {
			echo esc_html__( 'render single listings through an Elementor library template you design. Pick a template in "Single Listing Template" below — only single-listing-type templates appear (Default Kit, headers, footers, popups are filtered out). Use "Create Starter Elementor Template" to generate a basic page with our widgets.', 'trx-auto-dealer' );
		} else {
			echo esc_html__( 'Elementor is not active. Install Elementor to enable this option.', 'trx-auto-dealer' );
		}
		echo '</p>';
		echo '</div>';
	}

	public function renderSingleListingTemplate(): void {
		$settings      = AdminSettings::getSettings();
		$layout        = (string) ( $settings['single_layout'] ?? 'default' );
		$current_eleme = (int) ( $settings['single_elementor_template'] ?? 0 );
		$current_gut   = (int) ( $settings['single_gutenberg_template'] ?? 0 );

		// Render every pane *visible* on first paint; the inline JS hides the
		// non-matching ones once it boots. Previously the inline `display:none`
		// stuck if the JS hadn't bound yet (page load race / cached old script),
		// which forced users to save once before the template picker even
		// appeared — fix for bug #21 in the free-version-feedback report.

		// --- Plugin Default branch ---
		echo '<div data-layout-pane="default">';
		echo '<p class="description">';
		esc_html_e( 'Plugin Default uses our built-in PHP template — no extra selection needed.', 'trx-auto-dealer' );
		echo '</p></div>';

		// --- Gutenberg branch ---
		echo '<div data-layout-pane="gutenberg">';
		$gut_templates = $this->getGutenbergTemplates();
		printf(
			'<select name="%s[single_gutenberg_template]" id="trx_ad_single_gutenberg_template">',
			esc_attr( AdminSettings::OPTION_KEY )
		);
		printf( '<option value="">— %s —</option>', esc_html__( 'Select reusable block', 'trx-auto-dealer' ) );
		foreach ( $gut_templates as $id => $title ) {
			printf(
				'<option value="%d"%s>%s</option>',
				(int) $id,
				selected( $current_gut, $id, false ),
				esc_html( $title )
			);
		}
		echo '</select>';
		printf(
			'<p class="description">%s</p>',
			empty( $gut_templates )
				? esc_html__( 'No reusable blocks yet. Click the button below to create a starter, or build one in Editor → Patterns.', 'trx-auto-dealer' )
				: esc_html__( 'Pick a reusable block (`wp_block`) to render as the single listing page.', 'trx-auto-dealer' )
		);
		$gut_starter_url = wp_nonce_url(
			add_query_arg(
				array( 'action' => GutenbergStarterTemplate::ACTION ),
				admin_url( 'admin-post.php' )
			),
			GutenbergStarterTemplate::NONCE
		);
		printf(
			'<a href="%s" class="button" style="margin-top:8px;">%s</a>',
			esc_url( $gut_starter_url ),
			esc_html__( 'Create Starter Gutenberg Template', 'trx-auto-dealer' )
		);
		echo '</div>';

		// --- Elementor branch ---
		echo '<div data-layout-pane="elementor">';
		$ele_templates = $this->getElementorTemplates();
		printf(
			'<select name="%s[single_elementor_template]" id="trx_ad_single_elementor_template">',
			esc_attr( AdminSettings::OPTION_KEY )
		);
		printf( '<option value="">— %s —</option>', esc_html__( 'Select Elementor template', 'trx-auto-dealer' ) );
		foreach ( $ele_templates as $id => $title ) {
			printf(
				'<option value="%d"%s>%s</option>',
				(int) $id,
				selected( $current_eleme, $id, false ),
				esc_html( $title )
			);
		}
		echo '</select>';
		printf(
			'<p class="description">%s</p>',
			defined( 'ELEMENTOR_VERSION' )
				? ( empty( $ele_templates )
					? esc_html__( 'No Elementor templates yet. Click the button below to create a starter, or build one in Elementor → My Templates.', 'trx-auto-dealer' )
					: esc_html__( 'Pick an Elementor library template (only single-listing-suitable types appear).', 'trx-auto-dealer' ) )
				: esc_html__( 'Elementor is not active.', 'trx-auto-dealer' )
		);
		if ( defined( 'ELEMENTOR_VERSION' ) ) {
			$ele_starter_url = wp_nonce_url(
				add_query_arg(
					array( 'action' => ElementorStarterTemplate::ACTION ),
					admin_url( 'admin-post.php' )
				),
				ElementorStarterTemplate::NONCE
			);
			printf(
				'<a href="%s" class="button" style="margin-top:8px;">%s</a>',
				esc_url( $ele_starter_url ),
				esc_html__( 'Create Starter Elementor Template', 'trx-auto-dealer' )
			);
		}
		echo '</div>';

		// JS — toggle the visible pane when the layout select changes. Runs on
		// DOMContentLoaded (or immediately if already past) so we don't race the
		// `<select>` rendering before the script tag.
		?>
		<?php
		// The layout-pane toggle lives in assets/js/admin.js (initLayoutsTab,
		// guarded on #trx_ad_single_layout) -- pure DOM behavior, no data to
		// localize (wp.org 2026-07 review round 2: no PHP-composed script
		// bodies).
		?>
		<?php

		// Confirmation notice after creating a starter.
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( ! empty( $_GET['trx_ad_starter_created'] ) ) {
			$starter_id   = (int) $_GET['trx_ad_starter_created']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$starter_kind = isset( $_GET['kind'] ) ? sanitize_key( (string) $_GET['kind'] ) : 'elementor'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$edit_url     = 'gutenberg' === $starter_kind
				? admin_url( 'post.php?post=' . $starter_id . '&action=edit' )
				: admin_url( 'post.php?post=' . $starter_id . '&action=elementor' );
			printf(
				'<div class="notice notice-success inline" style="margin-top:8px;"><p>%s <a href="%s">%s</a></p></div>',
				'gutenberg' === $starter_kind
					? esc_html__( 'Starter Gutenberg template created and selected.', 'trx-auto-dealer' )
					: esc_html__( 'Starter Elementor template created and selected.', 'trx-auto-dealer' ),
				esc_url( $edit_url ),
				'gutenberg' === $starter_kind
					? esc_html__( 'Edit in Block Editor', 'trx-auto-dealer' )
					: esc_html__( 'Open in Elementor', 'trx-auto-dealer' )
			);
		}
	}

	/**
	 * @return array<int, string>
	 */
	private function getGutenbergTemplates(): array {
		$posts = get_posts(
			array(
				'post_type'      => 'wp_block',
				'post_status'    => 'publish',
				'posts_per_page' => 200, // phpcs:ignore WordPress.WP.PostsPerPage.posts_per_page_posts_per_page -- admin dropdown of reusable blocks; 200 is the explicit cap.
				'orderby'        => 'title',
				'order'          => 'ASC',
			)
		);
		$out   = array();
		foreach ( $posts as $post ) {
			$out[ (int) $post->ID ] = $post->post_title ?: __( '(Untitled)', 'trx-auto-dealer' );
		}
		return $out;
	}

	/**
	 * @return array<int, string>
	 */
	private function getElementorTemplates(): array {
		if ( ! defined( 'ELEMENTOR_VERSION' ) ) {
			return array();
		}
		$posts         = get_posts(
			array(
				'post_type'      => 'elementor_library',
				'post_status'    => 'publish',
				'posts_per_page' => -1,
				'orderby'        => 'title',
				'order'          => 'ASC',
			)
		);
		$allowed_types = array( 'page', 'section', 'container', 'single', 'single-post', 'wp-page' );
		$blocked_types = array( 'kit', 'header', 'footer', 'popup', 'error-404', 'archive' );
		$templates     = array();
		foreach ( $posts as $post ) {
			$type = (string) get_post_meta( $post->ID, '_elementor_template_type', true );
			if ( '' !== $type && in_array( $type, $blocked_types, true ) ) {
				continue;
			}
			if ( '' !== $type && ! in_array( $type, $allowed_types, true ) ) {
				$templates[ $post->ID ] = sprintf(
					'%s (%s)',
					$post->post_title ?: __( '(Untitled)', 'trx-auto-dealer' ),
					$type
				);
				continue;
			}
			$templates[ $post->ID ] = $post->post_title ?: __( '(Untitled)', 'trx-auto-dealer' );
		}
		return $templates;
	}
}
