<?php
/**
 * Custom Fields section — renders dynamic admin-defined meta fields, grouped.
 *
 * 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\CustomFieldMetaBox;
use ThemeREX\AutoDealer\Admin\MetaBoxes\AbstractVehicleDataSection;

final class CustomFieldsSection extends AbstractVehicleDataSection {

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

	/**
	 * Whether this section has any fields to render. The orchestrator uses
	 * this to skip the tab entirely when no custom fields are configured.
	 */
	public function hasFields(): bool {
		return ! empty( AdminSettings::getCustomFields() );
	}

	public function render( \WP_Post $post ): void {
		$fields = AdminSettings::getCustomFields();

		$groups = array();
		foreach ( $fields as $field ) {
			$group              = $field['group'] ?? '';
			$groups[ $group ][] = $field;
		}

		echo '<div class="trx-ad-cf-panel">';

		foreach ( $groups as $groupName => $groupFields ) {
			if ( $groupName !== '' ) {
				printf( '<h4 class="trx-ad-cf-group-title">%s</h4>', esc_html( $groupName ) );
			}

			echo '<div class="trx-ad-cf-grid">';

			foreach ( $groupFields as $field ) {
				$metaKey = CustomFieldMetaBox::META_PREFIX . $field['key'];
				$value   = get_post_meta( $post->ID, $metaKey, true );
				$value   = is_string( $value ) ? $value : '';
				$label   = $field['label'] ?? '';
				$type    = $field['type'] ?? 'text';
				$desc    = $field['description'] ?? '';

				$wrapClass = 'trx-ad-cf-field';
				if ( $type === 'textarea' ) {
					$wrapClass .= ' trx-ad-cf-field--full';
				}

				echo '<div class="' . esc_attr( $wrapClass ) . '">';
				printf( '<label for="%s" class="trx-ad-cf-label">%s</label>', esc_attr( $metaKey ), esc_html( $label ) );

				switch ( $type ) {
					case 'textarea':
						printf(
							'<textarea id="%1$s" name="%1$s" class="widefat" rows="3">%2$s</textarea>',
							esc_attr( $metaKey ),
							esc_textarea( $value )
						);
						break;

					case 'select':
						$options = array_map( 'trim', explode( ',', $field['options'] ?? '' ) );
						printf( '<select id="%1$s" name="%1$s" class="trx-ad-cf-select">', esc_attr( $metaKey ) );
						echo '<option value="">' . esc_html__( '-- Select --', 'trx-auto-dealer' ) . '</option>';
						foreach ( $options as $opt ) {
							if ( $opt === '' ) {
								continue; }
							printf( '<option value="%s"%s>%s</option>', esc_attr( $opt ), selected( $value, $opt, false ), esc_html( $opt ) );
						}
						echo '</select>';
						break;

					case 'checkbox':
						printf(
							'<label class="trx-ad-cf-checkbox"><input type="checkbox" id="%1$s" name="%1$s" value="1"%2$s> %3$s</label>',
							esc_attr( $metaKey ),
							checked( $value, '1', false ),
							esc_html__( 'Yes', 'trx-auto-dealer' )
						);
						break;

					default:
						printf(
							'<input type="%1$s" id="%2$s" name="%2$s" value="%3$s" class="widefat" step="any">',
							esc_attr( $type ),
							esc_attr( $metaKey ),
							esc_attr( $value )
						);
						break;
				}

				if ( $desc !== '' ) {
					printf( '<p class="description">%s</p>', esc_html( $desc ) );
				}

				echo '</div>';
			}

			echo '</div>'; // .trx-ad-cf-grid
		}

		echo '</div>';
	}

	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;
		}

		$fields = AdminSettings::getCustomFields();
		if ( empty( $fields ) ) {
			return;
		}

		foreach ( $fields as $field ) {
			$metaKey = CustomFieldMetaBox::META_PREFIX . $field['key'];
			$type    = $field['type'] ?? 'text';

			if ( $type === 'checkbox' ) {
				$value = isset( $_POST[ $metaKey ] ) ? '1' : '0';
			} elseif ( $type === 'url' ) {
				$value = isset( $_POST[ $metaKey ] )
					? esc_url_raw( wp_unslash( (string) $_POST[ $metaKey ] ) )
					: '';
			} else {
				$value = isset( $_POST[ $metaKey ] )
					? sanitize_text_field( wp_unslash( (string) $_POST[ $metaKey ] ) )
					: '';
			}

			if ( $value !== '' && $value !== '0' ) {
				update_post_meta( $postId, $metaKey, $value );
			} else {
				delete_post_meta( $postId, $metaKey );
			}
		}
	}
}
