<?php
/**
 * Details section — description, price, sale price.
 *
 * Extracted from VehicleDataMetaBox per QUALITY-IMPROVEMENT-PLAN.md §T2-2.
 *
 * @package ThemeREX\AutoDealer\Admin\MetaBoxes\Sections
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Admin\MetaBoxes\Sections;

defined( 'ABSPATH' ) || exit;

use ThemeREX\AutoDealer\Admin\AdminSettings;
use ThemeREX\AutoDealer\Admin\MetaBoxes\AbstractVehicleDataSection;

final class DetailsSection extends AbstractVehicleDataSection {

	/**
	 * Callable that unhooks + rehooks the parent meta box save during the
	 * recursive `wp_update_post()` call that writes post_content. The parent
	 * registers `save_post_{cpt}` at priority 12; the unhook+rehook pair has
	 * to match those exact args. Injected so this section doesn't need a
	 * reference to the orchestrator.
	 *
	 * @var callable|null
	 */
	private $rehookGuard;

	public function __construct( ?callable $rehookGuard = null ) {
		$this->rehookGuard = $rehookGuard;
	}

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

	public function render( \WP_Post $post ): void {
		$price     = $this->metaOrSpec( $post->ID, '_trx_ad_price' );
		$salePrice = $this->metaOrSpec( $post->ID, '_trx_ad_sale_price' );
		$currency  = AdminSettings::get( 'currency_symbol', '$' );
		?>
		<table class="form-table" style="margin:0;">
			<tr>
				<th scope="row">
					<label for="trx_ad_description"><?php esc_html_e( 'Description', 'trx-auto-dealer' ); ?></label>
				</th>
				<td>
					<?php
					wp_editor(
						$post->post_content,
						'trx_ad_description',
						array(
							'textarea_name' => 'trx_ad_description',
							'media_buttons' => true,
							'textarea_rows' => 10,
							'teeny'         => false,
							'quicktags'     => true,
						)
					);
					?>
				</td>
			</tr>
			<tr>
				<th scope="row">
					<label for="trx_ad_price"><?php esc_html_e( 'Price', 'trx-auto-dealer' ); ?></label>
				</th>
				<td>
					<div style="display:flex;align-items:center;gap:4px;">
						<span><?php echo esc_html( $currency ); ?></span>
						<input type="number" id="trx_ad_price" name="_trx_ad_price"
							value="<?php echo esc_attr( $price ); ?>"
							class="regular-text" min="0" step="0.01"
							placeholder="0.00">
					</div>
				</td>
			</tr>
			<tr>
				<th scope="row">
					<label for="trx_ad_sale_price"><?php esc_html_e( 'Sale Price', 'trx-auto-dealer' ); ?></label>
				</th>
				<td>
					<div style="display:flex;align-items:center;gap:4px;">
						<span><?php echo esc_html( $currency ); ?></span>
						<input type="number" id="trx_ad_sale_price" name="_trx_ad_sale_price"
							value="<?php echo esc_attr( $salePrice ); ?>"
							class="regular-text" min="0" step="0.01"
							placeholder="0.00">
					</div>
					<p class="description"><?php esc_html_e( 'Leave empty if not on sale.', 'trx-auto-dealer' ); ?></p>
				</td>
			</tr>
		</table>
		<?php
	}

	public function save( int $postId ): void {
		// Re-verify the meta-box nonce here as well as in the VehicleDataMetaBox
		// dispatcher -- defense in depth, and each save path is independently
		// auditable (wp.org 2026-07 review round 2).
		if (
			! isset( $_POST['_trx_ad_vehicle_data_nonce'] )
			|| ! wp_verify_nonce( sanitize_text_field( wp_unslash( (string) $_POST['_trx_ad_vehicle_data_nonce'] ) ), 'trx_ad_vehicle_data_save' )
		) {
			return;
		}

		if ( isset( $_POST['trx_ad_description'] ) ) {
			$content = wp_kses_post( wp_unslash( $_POST['trx_ad_description'] ) );

			// Recursive wp_update_post would re-trigger save_post_{cpt};
			// rehookGuard temporarily detaches and reattaches the parent's
			// save handler. Same priority + same callable args required.
			if ( is_callable( $this->rehookGuard ) ) {
				( $this->rehookGuard )(
					function () use ( $postId, $content ): void {
						wp_update_post(
							array(
								'ID'           => $postId,
								'post_content' => $content,
							)
						);
					}
				);
			} else {
				wp_update_post(
					array(
						'ID'           => $postId,
						'post_content' => $content,
					)
				);
			}
		}

		if ( isset( $_POST['_trx_ad_price'] ) ) {
			$price = sanitize_text_field( wp_unslash( $_POST['_trx_ad_price'] ) );
			if ( '' !== $price ) {
				update_post_meta( $postId, '_trx_ad_price', $price );
			} else {
				delete_post_meta( $postId, '_trx_ad_price' );
			}
		}

		if ( isset( $_POST['_trx_ad_sale_price'] ) ) {
			$salePrice = sanitize_text_field( wp_unslash( $_POST['_trx_ad_sale_price'] ) );
			if ( '' !== $salePrice ) {
				update_post_meta( $postId, '_trx_ad_sale_price', $salePrice );
			} else {
				delete_post_meta( $postId, '_trx_ad_sale_price' );
			}
		}
	}
}
