<?php
/**
 * Quick-edit fields for the vehicle admin list table.
 *
 * Renders Price + Status + Featured inputs into WP's inline-edit row, and
 * on save writes them to post meta (the canonical source) and re-syncs the
 * specs table via VehicleSpecsSync — see the D5 note in the save() body for
 * why a direct table write is wrong here. The JS that copies the current
 * cell values into the inputs when the user opens a row for quick-edit
 * (WP only populates core fields by default) lives in assets/js/admin.js.
 *
 * @package ThemeREX\AutoDealer\Admin\ListTable
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Admin\ListTable;

defined( 'ABSPATH' ) || exit;

use ThemeREX\AutoDealer\Database\VehicleSpecsSync;
use ThemeREX\AutoDealer\PostTypes\VehiclePostType;

final class QuickEdit {

	private const NONCE_ACTION = 'trx_ad_quick_edit_save';
	private const NONCE_FIELD  = '_trx_ad_quick_edit_nonce';

	public function register(): void {
		add_action( 'quick_edit_custom_box', array( $this, 'renderFields' ), 10, 2 );
		add_action( 'save_post_' . VehiclePostType::POST_TYPE, array( $this, 'save' ), 10, 1 );
		// The row-open value-copy JS lives in assets/js/admin.js
		// (initQuickEdit, guarded on window.inlineEditPost + the
		// .trx-ad-qe-price input) -- no PHP-composed script body
		// (wp.org 2026-07 review round 2).
	}

	public function renderFields( string $columnName, string $postType ): void {
		if ( $postType !== VehiclePostType::POST_TYPE ) {
			return;
		}

		if ( $columnName === 'trx_ad_price' ) {
			wp_nonce_field( self::NONCE_ACTION, self::NONCE_FIELD );
			?>
			<fieldset class="inline-edit-col-right">
				<div class="inline-edit-col">
					<label>
						<span class="title"><?php esc_html_e( 'Price', 'trx-auto-dealer' ); ?></span>
						<span class="input-text-wrap">
							<input type="number" name="_trx_ad_qe_price" class="trx-ad-qe-price" step="0.01" min="0">
						</span>
					</label>
				</div>
			</fieldset>
			<?php
		}

		if ( $columnName === 'trx_ad_status' ) {
			?>
			<fieldset class="inline-edit-col-right">
				<div class="inline-edit-col">
					<label>
						<span class="title"><?php esc_html_e( 'Status', 'trx-auto-dealer' ); ?></span>
						<select name="_trx_ad_qe_status" class="trx-ad-qe-status">
							<option value="available"><?php esc_html_e( 'Available', 'trx-auto-dealer' ); ?></option>
							<option value="sold"><?php esc_html_e( 'Sold', 'trx-auto-dealer' ); ?></option>
							<option value="reserved"><?php esc_html_e( 'Reserved', 'trx-auto-dealer' ); ?></option>
							<option value="coming_soon"><?php esc_html_e( 'Coming Soon', 'trx-auto-dealer' ); ?></option>
						</select>
					</label>
					<label class="alignleft">
						<input type="checkbox" name="_trx_ad_qe_featured" value="1" class="trx-ad-qe-featured">
						<span class="checkbox-title"><?php esc_html_e( 'Featured', 'trx-auto-dealer' ); ?></span>
					</label>
				</div>
			</fieldset>
			<?php
		}
	}

	public function save( int $postId ): void {
		if (
			! isset( $_POST[ self::NONCE_FIELD ] )
			|| ! wp_verify_nonce(
				sanitize_text_field( wp_unslash( $_POST[ self::NONCE_FIELD ] ) ),
				self::NONCE_ACTION
			)
		) {
			return;
		}

		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( ! current_user_can( 'edit_post', $postId ) ) {
			return;
		}

		// Write post meta (the canonical source) and push it through
		// VehicleSpecsSync, instead of updating the specs table directly:
		// a direct table write left meta stale, so the next save_post
		// re-synced the OLD values over the quick-edit (demo-site finding
		// D5, same divergence class as R2-8).
		$dirty = false;

		if ( isset( $_POST['_trx_ad_qe_price'] ) ) {
			$price = (float) sanitize_text_field( wp_unslash( (string) $_POST['_trx_ad_qe_price'] ) );
			if ( $price >= 0 ) {
				update_post_meta( $postId, '_trx_ad_price', (string) $price );
				$dirty = true;
			}
		}

		if ( isset( $_POST['_trx_ad_qe_status'] ) ) {
			$status  = sanitize_key( wp_unslash( (string) $_POST['_trx_ad_qe_status'] ) );
			$allowed = array( 'available', 'sold', 'reserved', 'coming_soon' );
			if ( in_array( $status, $allowed, true ) ) {
				update_post_meta( $postId, '_trx_ad_status', $status );
				$dirty = true;
			}
		}

		// Featured is a checkbox: presence of the *status* field signals
		// the row was edited, so an unchecked Featured box means "clear it".
		if ( isset( $_POST['_trx_ad_qe_status'] ) ) {
			update_post_meta( $postId, '_trx_ad_featured', ! empty( $_POST['_trx_ad_qe_featured'] ) ? '1' : '0' );
			$dirty = true;
		}

		if ( $dirty ) {
			( new VehicleSpecsSync() )->syncOnSave( $postId );
		}
	}
}
