<?php
/**
 * Forms tab — configure submission forms (lead, test drive, contact) and email routing.
 *
 * Extracted from AdminSettings per QUALITY-IMPROVEMENT-PLAN.md §T2-2.
 *
 * @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\Settings\AbstractSettingsTab;
use ThemeREX\AutoDealer\Forms\FormConfig;
use ThemeREX\AutoDealer\Admin\AdminAssets;

final class FormsTab extends AbstractSettingsTab {

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

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

	public function register(): void {
		// Bug fix: this tab's register() runs *inside* AdminSettings::registerSettings,
		// which is itself hooked to `admin_init`. Adding another `admin_init` hook from
		// there is too late — WP has already fired admin_init for this request, so the
		// save handler never ran and edits silently vanished. Switching to
		// `admin_post_trx_ad_save_forms` works because admin-post.php fires
		// `admin_init` first, *then* the admin_post_* action, so a hook added during
		// admin_init still binds before its action fires.
		add_action( 'admin_post_trx_ad_save_forms', array( $this, 'handleFormsSave' ) );
	}

	/**
	 * Custom POST handler for the Forms tab (not Settings API — writes to
	 * FormConfig storage rather than the central plugin option).
	 */
	public function handleFormsSave(): void {
		if (
			! isset( $_POST['trx_ad_forms_nonce'] )
			|| ! wp_verify_nonce(
				sanitize_text_field( wp_unslash( $_POST['trx_ad_forms_nonce'] ) ),
				'trx_ad_save_forms'
			)
		) {
			wp_die( esc_html__( 'Invalid request.', 'trx-auto-dealer' ), 400 );
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Permission denied.', 'trx-auto-dealer' ), 403 );
		}

		// Sanitized at the read: unslash + text-field-sanitize every leaf of
		// the nested form-config array; the loop below then applies the
		// per-key sanitizers (sanitize_key, wp_kses_post for templates, ...).
		$rawForms = isset( $_POST['trx_ad_form'] ) && is_array( $_POST['trx_ad_form'] )
			? map_deep( wp_unslash( $_POST['trx_ad_form'] ), 'sanitize_text_field' )
			: array();

		$forms = array();

		foreach ( $rawForms as $formId => $formData ) {
			$formId = sanitize_key( $formId );
			if ( '' === $formId ) {
				continue;
			}

			$fields    = array();
			$rawFields = $formData['fields'] ?? array();
			if ( is_array( $rawFields ) ) {
				foreach ( $rawFields as $field ) {
					if ( ! is_array( $field ) ) {
						continue;
					}
					$label = sanitize_text_field( $field['label'] ?? '' );
					if ( '' === $label ) {
						continue;
					}
					$type = sanitize_key( $field['type'] ?? 'text' );
					if ( ! in_array( $type, FormConfig::FIELD_TYPES, true ) ) {
						$type = 'text';
					}
					$width = sanitize_text_field( $field['width'] ?? '100' );
					if ( ! in_array( $width, array( '25', '33', '50', '100' ), true ) ) {
						$width = '100';
					}
					$fields[] = array(
						'id'          => sanitize_key( $field['id'] ?? sanitize_title( $label ) ),
						'label'       => $label,
						'type'        => $type,
						'required'    => ! empty( $field['required'] ),
						'placeholder' => sanitize_text_field( $field['placeholder'] ?? '' ),
						'width'       => $width,
						'options'     => sanitize_text_field( $field['options'] ?? '' ),
					);
				}
			}

			$forms[ $formId ] = array(
				'title'           => sanitize_text_field( $formData['title'] ?? $formId ),
				'fields'          => $fields,
				'email_to'        => sanitize_email( $formData['email_to'] ?? '' ),
				'email_subject'   => sanitize_text_field( $formData['email_subject'] ?? '' ),
				'email_body'      => sanitize_textarea_field( $formData['email_body'] ?? '' ),
				'success_message' => sanitize_text_field( $formData['success_message'] ?? '' ),
				'submit_label'    => sanitize_text_field( $formData['submit_label'] ?? '' ),
			);
		}

		FormConfig::saveAll( $forms );

		wp_safe_redirect(
			add_query_arg(
				array(
					'post_type' => 'trx_ad_listing',
					'page'      => AdminSettings::PAGE_SLUG,
					'tab'       => 'forms',
					'updated'   => '1',
				),
				admin_url( 'edit.php' )
			)
		);
		exit;
	}

	public function render(): void {
		$forms = FormConfig::getAll();

		if ( isset( $_GET['updated'] ) && '1' === $_GET['updated'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			echo '<div class="notice notice-success is-dismissible"><p>';
			esc_html_e( 'Forms saved.', 'trx-auto-dealer' );
			echo '</p></div>';
		}
		?>
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
			<input type="hidden" name="action" value="trx_ad_save_forms">
			<?php wp_nonce_field( 'trx_ad_save_forms', 'trx_ad_forms_nonce' ); ?>

			<?php foreach ( $forms as $formId => $form ) : ?>
				<div class="trx-ad-form-config" style="margin-bottom:30px;">
					<h3 style="display:flex;align-items:center;gap:10px;">
						<span class="dashicons dashicons-feedback"></span>
						<input type="text"
							name="trx_ad_form[<?php echo esc_attr( $formId ); ?>][title]"
							value="<?php echo esc_attr( $form['title'] ?? '' ); ?>"
							class="regular-text"
							style="font-size:16px;font-weight:600;">
					</h3>

					<!-- Fields -->
					<h4><?php esc_html_e( 'Form Fields', 'trx-auto-dealer' ); ?></h4>
					<p class="description"><?php esc_html_e( 'Add, remove, and reorder fields. Drag rows to change order.', 'trx-auto-dealer' ); ?></p>

					<table class="widefat trx-ad-form-fields-table" data-form-id="<?php echo esc_attr( $formId ); ?>" style="max-width:900px;margin:10px 0;">
						<thead>
							<tr>
								<th style="width:30px;"></th>
								<th><?php esc_html_e( 'Label', 'trx-auto-dealer' ); ?></th>
								<th style="width:80px;"><?php esc_html_e( 'ID', 'trx-auto-dealer' ); ?></th>
								<th style="width:110px;"><?php esc_html_e( 'Type', 'trx-auto-dealer' ); ?></th>
								<th style="width:70px;"><?php esc_html_e( 'Required', 'trx-auto-dealer' ); ?></th>
								<th><?php esc_html_e( 'Placeholder', 'trx-auto-dealer' ); ?></th>
								<th style="width:80px;"><?php esc_html_e( 'Width', 'trx-auto-dealer' ); ?></th>
								<th style="width:40px;"></th>
							</tr>
						</thead>
						<tbody>
							<?php
							$fields = $form['fields'] ?? array();
							foreach ( $fields as $fi => $field ) :
								$pfx = "trx_ad_form[{$formId}][fields][{$fi}]";
								?>
								<tr>
									<td><span class="dashicons dashicons-move" style="cursor:grab;color:#999;"></span></td>
									<td><input type="text" name="<?php echo esc_attr( $pfx ); ?>[label]" value="<?php echo esc_attr( $field['label'] ?? '' ); ?>" class="regular-text" required></td>
									<td><input type="text" name="<?php echo esc_attr( $pfx ); ?>[id]" value="<?php echo esc_attr( $field['id'] ?? '' ); ?>" class="small-text" style="width:70px;"></td>
									<td>
										<select name="<?php echo esc_attr( $pfx ); ?>[type]">
											<?php foreach ( FormConfig::FIELD_TYPES as $ft ) : ?>
												<option value="<?php echo esc_attr( $ft ); ?>" <?php selected( $field['type'] ?? 'text', $ft ); ?>><?php echo esc_html( ucfirst( $ft ) ); ?></option>
											<?php endforeach; ?>
										</select>
									</td>
									<td style="text-align:center;"><input type="checkbox" name="<?php echo esc_attr( $pfx ); ?>[required]" value="1" <?php checked( ! empty( $field['required'] ) ); ?>></td>
									<td><input type="text" name="<?php echo esc_attr( $pfx ); ?>[placeholder]" value="<?php echo esc_attr( $field['placeholder'] ?? '' ); ?>" class="regular-text"></td>
									<td>
										<select name="<?php echo esc_attr( $pfx ); ?>[width]">
											<option value="100" <?php selected( $field['width'] ?? '100', '100' ); ?>>100%</option>
											<option value="50" <?php selected( $field['width'] ?? '100', '50' ); ?>>50%</option>
											<option value="33" <?php selected( $field['width'] ?? '100', '33' ); ?>>33%</option>
											<option value="25" <?php selected( $field['width'] ?? '100', '25' ); ?>>25%</option>
										</select>
									</td>
									<td><button type="button" class="button-link trx-ad-remove-field" style="color:#b32d2e;"><span class="dashicons dashicons-trash"></span></button></td>
								</tr>
							<?php endforeach; ?>
						</tbody>
					</table>

					<button type="button" class="button trx-ad-add-field" data-form-id="<?php echo esc_attr( $formId ); ?>">
						<?php esc_html_e( '+ Add Field', 'trx-auto-dealer' ); ?>
					</button>

					<!-- Email Settings -->
					<h4 style="margin-top:20px;"><?php esc_html_e( 'Email Settings', 'trx-auto-dealer' ); ?></h4>

					<table class="form-table" style="max-width:700px;">
						<tr>
							<th><label><?php esc_html_e( 'Recipient Email', 'trx-auto-dealer' ); ?></label></th>
							<td>
								<input type="email"
									name="trx_ad_form[<?php echo esc_attr( $formId ); ?>][email_to]"
									value="<?php echo esc_attr( $form['email_to'] ?? '' ); ?>"
									class="regular-text"
									placeholder="<?php echo esc_attr( get_option( 'admin_email' ) ); ?>">
								<p class="description"><?php esc_html_e( 'Leave empty to use the site admin email.', 'trx-auto-dealer' ); ?></p>
							</td>
						</tr>
						<tr>
							<th><label><?php esc_html_e( 'Email Subject', 'trx-auto-dealer' ); ?></label></th>
							<td>
								<input type="text"
									name="trx_ad_form[<?php echo esc_attr( $formId ); ?>][email_subject]"
									value="<?php echo esc_attr( $form['email_subject'] ?? '' ); ?>"
									class="large-text">
							</td>
						</tr>
						<tr>
							<th><label><?php esc_html_e( 'Email Body', 'trx-auto-dealer' ); ?></label></th>
							<td>
								<textarea name="trx_ad_form[<?php echo esc_attr( $formId ); ?>][email_body]"
									rows="8" class="large-text" style="font-family:monospace;"><?php echo esc_textarea( $form['email_body'] ?? '' ); ?></textarea>
								<p class="description">
									<?php esc_html_e( 'Available merge tags:', 'trx-auto-dealer' ); ?><br>
									<?php
									foreach ( FormConfig::getMergeTags() as $tag => $desc ) {
										printf( '<code>%s</code> &mdash; %s<br>', esc_html( $tag ), esc_html( $desc ) );
									}
									?>
								</p>
							</td>
						</tr>
					</table>

					<!-- Form Settings -->
					<h4><?php esc_html_e( 'Form Settings', 'trx-auto-dealer' ); ?></h4>
					<table class="form-table" style="max-width:700px;">
						<tr>
							<th><label><?php esc_html_e( 'Submit Button Text', 'trx-auto-dealer' ); ?></label></th>
							<td>
								<input type="text"
									name="trx_ad_form[<?php echo esc_attr( $formId ); ?>][submit_label]"
									value="<?php echo esc_attr( $form['submit_label'] ?? '' ); ?>"
									class="regular-text">
							</td>
						</tr>
						<tr>
							<th><label><?php esc_html_e( 'Success Message', 'trx-auto-dealer' ); ?></label></th>
							<td>
								<input type="text"
									name="trx_ad_form[<?php echo esc_attr( $formId ); ?>][success_message]"
									value="<?php echo esc_attr( $form['success_message'] ?? '' ); ?>"
									class="large-text">
							</td>
						</tr>
					</table>

					<hr>
				</div>
			<?php endforeach; ?>

			<?php submit_button( __( 'Save Forms', 'trx-auto-dealer' ) ); ?>
		</form>

		<?php
		// The form-builder behavior lives in assets/js/admin.js (initFormsTab,
		// guarded on .trx-ad-form-fields-table); only DATA crosses the PHP->JS
		// boundary, via wp_localize_script (wp.org 2026-07 review round 2: no
		// PHP-composed script bodies).
		wp_localize_script(
			AdminAssets::JS_HANDLE,
			'trxAdFormsTab',
			array(
				'fieldTypes' => FormConfig::FIELD_TYPES,
			)
		);
		?>
		<?php
	}
}
