<?php
namespace Pay4All\Pro\Admin\Brands;

use Pay4All\Form\Admin\Assets;
use Pay4All\Pro\PostTypes;
use Pay4All\Pro\Domain\Brand;

if ( ! defined( 'ABSPATH' ) ) { exit; }

/**
 * Adds the multi-language "display name" field AND the quantity-rule block
 * to the p4all_product_brand taxonomy edit screens — same UX as
 * Categories\RulesField but bound to the Brand meta keys so a product can
 * carry independent rules on each taxonomy without collision.
 */
final class RulesField {

	public static function register() : void {
		add_action( PostTypes::TAXONOMY_BRAND . '_add_form_fields',  [ self::class, 'render_add' ], 10 );
		add_action( PostTypes::TAXONOMY_BRAND . '_edit_form_fields', [ self::class, 'render_edit' ], 10 );
		add_action( 'created_' . PostTypes::TAXONOMY_BRAND,          [ self::class, 'save' ] );
		add_action( 'edited_'  . PostTypes::TAXONOMY_BRAND,          [ self::class, 'save' ] );

		add_filter( 'manage_edit-' . PostTypes::TAXONOMY_BRAND . '_columns', [ self::class, 'columns' ] );
		add_filter( 'manage_' . PostTypes::TAXONOMY_BRAND . '_custom_column', [ self::class, 'render_column' ], 10, 3 );
	}

	public static function render_add() : void {
		?>
		<div class="form-field p4all-cat-section">
			<h3><?php esc_html_e( 'Nom par langue', 'pay4all-pro' ); ?></h3>
			<?php self::render_name_input_fields( 0 ); ?>
			<p class="description">
				<?php esc_html_e( 'Nom affiché aux clients dans le formulaire de commande, par langue activée. Si un champ reste vide, le nom canonique de la marque (WordPress) est utilisé. La langue affichée côté client suit la langue du site.', 'pay4all-pro' ); ?>
				<br>
				<?php esc_html_e( 'L\'étiquette « Toutes les… » est affichée comme première option de la liste déroulante du filtre lorsque cette marque contient des sous-marques. Un champ vide affiche simplement « Tous ».', 'pay4all-pro' ); ?>
			</p>
		</div>
		<div class="form-field p4all-cat-section">
			<h3><?php esc_html_e( 'Règle de quantité', 'pay4all-pro' ); ?></h3>
			<?php self::render_inputs( 0 ); ?>
		</div>
		<?php
	}

	public static function render_edit( \WP_Term $term ) : void {
		?>
		<tr class="form-field">
			<th colspan="2">
				<h3 style="margin-top:0;"><?php esc_html_e( 'Nom par langue', 'pay4all-pro' ); ?></h3>
			</th>
		</tr>
		<?php self::render_name_inputs( (int) $term->term_id ); ?>
		<tr class="form-field">
			<th colspan="2">
				<h3 style="margin-top:0;"><?php esc_html_e( 'Règle de quantité', 'pay4all-pro' ); ?></h3>
			</th>
		</tr>
		<?php self::render_inputs( (int) $term->term_id ); ?>
		<?php
	}

	/**
	 * Table-row wrapper around the name inputs — used by render_edit().
	 * Add-screen uses render_name_input_fields() directly (div context).
	 */
	private static function render_name_inputs( int $term_id ) : void {
		?>
		<tr class="form-field">
			<th><?php esc_html_e( 'Nom affiché côté client', 'pay4all-pro' ); ?></th>
			<td>
				<?php self::render_name_input_fields( $term_id ); ?>
				<p class="description">
					<?php esc_html_e( 'Nom affiché aux clients dans le formulaire de commande, par langue activée. Si un champ reste vide, le nom canonique de la marque (WordPress) est utilisé. La langue affichée côté client suit la langue du site.', 'pay4all-pro' ); ?>
				</p>
			</td>
		</tr>
		<?php
	}

	private static function render_name_input_fields( int $term_id ) : void {
		$names      = $term_id ? Brand::names( $term_id ) : [];
		$all_labels = $term_id ? Brand::all_labels( $term_id ) : [];

		$langs = (array) \Pay4All\Form\Admin\Settings\Schema::get( 'languages', [] );
		$langs = array_values( array_intersect( $langs, \Pay4All\Form\Admin\Settings\Schema::SUPPORTED_LANGUAGES ) );
		if ( empty( $langs ) ) {
			$langs = \Pay4All\Form\Admin\Settings\Schema::default_languages();
		}
		$lang_labels = [
			'fr' => __( 'Français', 'pay4all-pro' ),
			'de' => __( 'Allemand', 'pay4all-pro' ),
			'it' => __( 'Italien',  'pay4all-pro' ),
			'en' => __( 'Anglais',  'pay4all-pro' ),
		];

		$fallback = '';
		if ( $term_id > 0 ) {
			$term = get_term( $term_id );
			$fallback = ( $term && ! is_wp_error( $term ) ) ? (string) $term->name : '';
		}
		$name_lbl  = __( 'Nom', 'pay4all-pro' );
		$all_lbl   = __( 'Étiquette « Toutes les… »', 'pay4all-pro' );
		// Per-language "Toutes les X" prefix map (feminine plural for FR/IT
		// since "marque"/"marca" are feminine). Hard-coded because each
		// language input needs its OWN localised prefix.
		$all_prefix_brand = [
			'fr' => 'Toutes les',
			'de' => 'Alle',
			'it' => 'Tutte',
			'en' => 'All',
		];
		$placeholder_for = static function ( string $code, string $name ) use ( $all_prefix_brand ) : string {
			$term = trim( $name );
			if ( $term === '' ) { return ''; }
			$prefix = $all_prefix_brand[ $code ] ?? 'All';
			return $prefix . ' ' . $term;
		};

		if ( count( $langs ) === 1 ) :
			$only     = $langs[0];
			$name_val = $names[ $only ] ?? $fallback;
			$all_val  = $all_labels[ $only ] ?? '';
			$all_ph   = $placeholder_for( $only, $name_val !== '' ? $name_val : $fallback );
			?>
			<div class="p4all-cat-lang-group" style="margin:0 0 10px;">
				<label for="p4all_brand_name_<?php echo esc_attr( $only ); ?>" style="display:block;font-size:12px;color:#555;margin:0 0 2px;"><?php echo esc_html( $name_lbl ); ?></label>
				<input id="p4all_brand_name_<?php echo esc_attr( $only ); ?>"
				       name="p4all_brand_name[<?php echo esc_attr( $only ); ?>]"
				       type="text" value="<?php echo esc_attr( $name_val ); ?>" class="regular-text" style="width:100%;">
				<label for="p4all_brand_all_label_<?php echo esc_attr( $only ); ?>" style="display:block;font-size:12px;color:#555;margin:8px 0 2px;"><?php echo esc_html( $all_lbl ); ?></label>
				<input id="p4all_brand_all_label_<?php echo esc_attr( $only ); ?>"
				       name="p4all_brand_all_label[<?php echo esc_attr( $only ); ?>]"
				       type="text" value="<?php echo esc_attr( $all_val ); ?>" class="regular-text" style="width:100%;"
				       placeholder="<?php echo esc_attr( $all_ph ); ?>">
			</div>
		<?php else : ?>
			<?php foreach ( $langs as $code ) :
				$name_val = $names[ $code ] ?? '';
				$all_val  = $all_labels[ $code ] ?? '';
				$label    = $lang_labels[ $code ] ?? strtoupper( $code );
				$all_ph   = $placeholder_for( $code, $name_val !== '' ? $name_val : $fallback ); ?>
				<div class="p4all-cat-lang-group" style="margin:0 0 16px;padding:0 0 12px;border-bottom:1px dashed #e6e6e6;">
					<div style="font-weight:600;margin:0 0 6px;">
						<?php echo esc_html( $label ); ?>
						<small style="color:#888;font-weight:400;">(<?php echo esc_html( $code ); ?>)</small>
					</div>
					<label for="p4all_brand_name_<?php echo esc_attr( $code ); ?>" style="display:block;font-size:12px;color:#555;margin:0 0 2px;"><?php echo esc_html( $name_lbl ); ?></label>
					<input id="p4all_brand_name_<?php echo esc_attr( $code ); ?>"
					       name="p4all_brand_name[<?php echo esc_attr( $code ); ?>]"
					       type="text" value="<?php echo esc_attr( $name_val ); ?>" class="regular-text" style="width:100%;"
					       placeholder="<?php echo esc_attr( $fallback ); ?>">
					<label for="p4all_brand_all_label_<?php echo esc_attr( $code ); ?>" style="display:block;font-size:12px;color:#555;margin:8px 0 2px;"><?php echo esc_html( $all_lbl ); ?></label>
					<input id="p4all_brand_all_label_<?php echo esc_attr( $code ); ?>"
					       name="p4all_brand_all_label[<?php echo esc_attr( $code ); ?>]"
					       type="text" value="<?php echo esc_attr( $all_val ); ?>" class="regular-text" style="width:100%;"
					       placeholder="<?php echo esc_attr( $all_ph ); ?>">
				</div>
			<?php endforeach; ?>
		<?php endif;
	}

	private static function render_inputs( int $term_id ) : void {
		$rule_type = $term_id ? Brand::rule_type( $term_id ) : 'none';
		$multiple  = $term_id ? Brand::multiple( $term_id ) : 1;
		$min       = $term_id ? Brand::min_total( $term_id ) : 0;
		$max       = $term_id ? Brand::max_total( $term_id ) : 0;
		$exact     = $term_id ? Brand::exact_total( $term_id ) : 0;
		$errs      = $term_id ? Brand::error_messages( $term_id ) : [];

		$langs = (array) \Pay4All\Form\Admin\Settings\Schema::get( 'languages', [] );
		$langs = array_values( array_intersect( $langs, \Pay4All\Form\Admin\Settings\Schema::SUPPORTED_LANGUAGES ) );
		if ( empty( $langs ) ) {
			$langs = \Pay4All\Form\Admin\Settings\Schema::default_languages();
		}
		$lang_labels = [
			'fr' => __( 'Français', 'pay4all-pro' ),
			'de' => __( 'Allemand', 'pay4all-pro' ),
			'it' => __( 'Italien',  'pay4all-pro' ),
			'en' => __( 'Anglais',  'pay4all-pro' ),
		];

		$explanations = [
			'none'         => __( 'Aucune contrainte de quantité ne sera appliquée pour les produits de cette marque.', 'pay4all-pro' ),
			'min'          => __( 'La somme des quantités des produits de cette marque devra être supérieure ou égale au minimum global.', 'pay4all-pro' ),
			'max'          => __( 'La somme des quantités des produits de cette marque ne pourra pas dépasser le maximum global.', 'pay4all-pro' ),
			'multiple'     => __( 'La somme des quantités des produits de cette marque devra être un multiple du nombre choisi (ex. 6, 12, 18 si Multiple = 6).', 'pay4all-pro' ),
			'min_multiple' => __( 'La somme des quantités des produits de cette marque devra être supérieure ou égale au minimum ET un multiple du nombre choisi.', 'pay4all-pro' ),
			'exact'        => __( 'La somme des quantités des produits de cette marque devra être exactement égale à la valeur choisie.', 'pay4all-pro' ),
		];

		$visible_fields = [
			'none'         => [],
			'min'          => [ 'min' ],
			'max'          => [ 'max' ],
			'multiple'     => [ 'multiple' ],
			'min_multiple' => [ 'min', 'multiple' ],
			'exact'        => [ 'exact' ],
		];

		wp_nonce_field( 'p4all_brand_save', '_p4all_brand_nonce' );
		?>
		<table class="form-table p4all-rules-table"
		       data-explanations="<?php echo esc_attr( wp_json_encode( $explanations ) ); ?>"
		       data-visible-fields="<?php echo esc_attr( wp_json_encode( $visible_fields ) ); ?>">
			<tr>
				<th><label for="p4all_brand_rule_type"><?php esc_html_e( 'Type de règle', 'pay4all-pro' ); ?></label></th>
				<td>
					<select id="p4all_brand_rule_type" name="p4all_brand_rule_type">
						<option value="none"         <?php selected( $rule_type, 'none' ); ?>><?php esc_html_e( 'Aucune', 'pay4all-pro' ); ?></option>
						<option value="min"          <?php selected( $rule_type, 'min' ); ?>><?php esc_html_e( 'Minimum global', 'pay4all-pro' ); ?></option>
						<option value="max"          <?php selected( $rule_type, 'max' ); ?>><?php esc_html_e( 'Maximum global', 'pay4all-pro' ); ?></option>
						<option value="multiple"     <?php selected( $rule_type, 'multiple' ); ?>><?php esc_html_e( 'Multiple obligatoire', 'pay4all-pro' ); ?></option>
						<option value="min_multiple" <?php selected( $rule_type, 'min_multiple' ); ?>><?php esc_html_e( 'Minimum + multiple', 'pay4all-pro' ); ?></option>
						<option value="exact"        <?php selected( $rule_type, 'exact' ); ?>><?php esc_html_e( 'Quantité exacte', 'pay4all-pro' ); ?></option>
					</select>
					<p class="description p4all-rule-explanation" style="margin-top:8px;background:#f6f7f7;border-left:3px solid #2271b1;padding:8px 12px;"></p>
				</td>
			</tr>
			<tr class="p4all-rule-row" data-field="multiple">
				<th><label for="p4all_brand_qty_multiple"><?php esc_html_e( 'Multiple', 'pay4all-pro' ); ?></label></th>
				<td><input id="p4all_brand_qty_multiple" name="p4all_brand_qty_multiple" type="number" min="1" value="<?php echo esc_attr( $multiple ); ?>" style="width:80px;">
				<p class="description"><?php esc_html_e( 'Ex. 6 pour les bouteilles de vin.', 'pay4all-pro' ); ?></p></td>
			</tr>
			<tr class="p4all-rule-row" data-field="min">
				<th><label for="p4all_brand_min_total"><?php esc_html_e( 'Minimum global', 'pay4all-pro' ); ?></label></th>
				<td><input id="p4all_brand_min_total" name="p4all_brand_min_total" type="number" min="0" value="<?php echo esc_attr( $min ); ?>" style="width:80px;"></td>
			</tr>
			<tr class="p4all-rule-row" data-field="max">
				<th><label for="p4all_brand_max_total"><?php esc_html_e( 'Maximum global', 'pay4all-pro' ); ?></label></th>
				<td><input id="p4all_brand_max_total" name="p4all_brand_max_total" type="number" min="0" value="<?php echo esc_attr( $max ); ?>" style="width:80px;"></td>
			</tr>
			<tr class="p4all-rule-row" data-field="exact">
				<th><label for="p4all_brand_exact_total"><?php esc_html_e( 'Quantité exacte', 'pay4all-pro' ); ?></label></th>
				<td><input id="p4all_brand_exact_total" name="p4all_brand_exact_total" type="number" min="0" value="<?php echo esc_attr( $exact ); ?>" style="width:80px;"></td>
			</tr>
			<tr>
				<th><?php esc_html_e( 'Message d\'erreur', 'pay4all-pro' ); ?></th>
				<td>
					<?php if ( count( $langs ) === 1 ) :
						$only = $langs[0];
						$val  = $errs[ $only ] ?? '';
						?>
						<input id="p4all_brand_error_message_<?php echo esc_attr( $only ); ?>"
						       name="p4all_brand_error_message[<?php echo esc_attr( $only ); ?>]"
						       type="text" value="<?php echo esc_attr( $val ); ?>" class="regular-text">
					<?php else : ?>
						<?php foreach ( $langs as $code ) :
							$val   = $errs[ $code ] ?? '';
							$label = $lang_labels[ $code ] ?? strtoupper( $code ); ?>
							<p style="margin:0 0 8px;">
								<label for="p4all_brand_error_message_<?php echo esc_attr( $code ); ?>"
								       style="display:inline-block;min-width:110px;font-weight:600;">
									<?php echo esc_html( $label ); ?>
									<small style="color:#888;font-weight:400;">(<?php echo esc_html( $code ); ?>)</small>
								</label>
								<input id="p4all_brand_error_message_<?php echo esc_attr( $code ); ?>"
								       name="p4all_brand_error_message[<?php echo esc_attr( $code ); ?>]"
								       type="text" value="<?php echo esc_attr( $val ); ?>" class="regular-text">
							</p>
						<?php endforeach; ?>
					<?php endif; ?>
					<p class="description">
						<?php esc_html_e( 'Optionnel. Si vide, un message automatique est affiché. La langue affichée côté client suit la langue du site (compatible WPML / Polylang).', 'pay4all-pro' ); ?>
					</p>
				</td>
			</tr>
		</table>
		<?php
		// Reuse the same rule-toggle JS as Categories — it targets any
		// #p4all_rule_type dropdown inside a .p4all-rules-table so we just
		// need a compatible ID. We rename to keep the two forms independent.
		wp_add_inline_script( Assets::HANDLE_JS, <<<'JS'
		(function () {
			var sel    = document.getElementById( 'p4all_brand_rule_type' );
			var table  = sel ? sel.closest( '.p4all-rules-table' ) : null;
			if ( ! sel || ! table ) { return; }
			var explanations   = JSON.parse( table.getAttribute( 'data-explanations'    ) || '{}' );
			var visibleFields  = JSON.parse( table.getAttribute( 'data-visible-fields'  ) || '{}' );
			var explanationBox = table.querySelector( '.p4all-rule-explanation' );
			var rows           = table.querySelectorAll( '.p4all-rule-row' );
			function apply() {
				var rule = sel.value;
				var keep = visibleFields[ rule ] || [];
				rows.forEach( function ( row ) {
					var field = row.getAttribute( 'data-field' );
					row.style.display = ( keep.indexOf( field ) !== -1 ) ? '' : 'none';
				} );
				if ( explanationBox ) {
					explanationBox.textContent = explanations[ rule ] || '';
				}
			}
			sel.addEventListener( 'change', apply );
			apply();
		})();
JS );
	}

	public static function save( int $term_id ) : void {
		if ( ! isset( $_POST['_p4all_brand_nonce'] ) ) { return; }
		if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_p4all_brand_nonce'] ) ), 'p4all_brand_save' ) ) { return; }
		if ( ! current_user_can( 'manage_options' ) ) { return; }

		$rule_type = isset( $_POST['p4all_brand_rule_type'] ) ? sanitize_key( wp_unslash( (string) $_POST['p4all_brand_rule_type'] ) ) : 'none';
		if ( ! in_array( $rule_type, Brand::RULES, true ) ) { $rule_type = 'none'; }
		update_term_meta( $term_id, Brand::META_RULE_TYPE, $rule_type );
		$qty_multiple = isset( $_POST['p4all_brand_qty_multiple'] ) ? absint( wp_unslash( $_POST['p4all_brand_qty_multiple'] ) ) : 1;
		$min_total    = isset( $_POST['p4all_brand_min_total'] )    ? absint( wp_unslash( $_POST['p4all_brand_min_total'] ) )    : 0;
		$max_total    = isset( $_POST['p4all_brand_max_total'] )    ? absint( wp_unslash( $_POST['p4all_brand_max_total'] ) )    : 0;
		$exact_total  = isset( $_POST['p4all_brand_exact_total'] )  ? absint( wp_unslash( $_POST['p4all_brand_exact_total'] ) )  : 0;
		update_term_meta( $term_id, Brand::META_MULTIPLE,    max( 1, $qty_multiple ) );
		update_term_meta( $term_id, Brand::META_MIN_TOTAL,   max( 0, $min_total ) );
		update_term_meta( $term_id, Brand::META_MAX_TOTAL,   max( 0, $max_total ) );
		update_term_meta( $term_id, Brand::META_EXACT_TOTAL, max( 0, $exact_total ) );

		// phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- per-element sanitization below.
		$raw = ( isset( $_POST['p4all_brand_error_message'] ) && is_array( $_POST['p4all_brand_error_message'] ) )
			? wp_unslash( $_POST['p4all_brand_error_message'] )
			: [];
		// phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		$messages = [];
		foreach ( $raw as $code => $msg ) {
			$code = strtolower( sanitize_key( (string) $code ) );
			if ( ! in_array( $code, \Pay4All\Form\Admin\Settings\Schema::SUPPORTED_LANGUAGES, true ) ) { continue; }
			$msg = sanitize_text_field( (string) $msg );
			if ( $msg !== '' ) { $messages[ $code ] = $msg; }
		}
		update_term_meta( $term_id, Brand::META_ERROR_MSG, $messages );

		// phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- per-element sanitization below.
		$raw_names = ( isset( $_POST['p4all_brand_name'] ) && is_array( $_POST['p4all_brand_name'] ) )
			? wp_unslash( $_POST['p4all_brand_name'] )
			: [];
		// phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		$names = [];
		foreach ( $raw_names as $code => $name ) {
			$code = strtolower( sanitize_key( (string) $code ) );
			if ( ! in_array( $code, \Pay4All\Form\Admin\Settings\Schema::SUPPORTED_LANGUAGES, true ) ) { continue; }
			$name = trim( sanitize_text_field( (string) $name ) );
			if ( $name !== '' ) { $names[ $code ] = $name; }
		}
		update_term_meta( $term_id, Brand::META_NAMES, $names );

		// phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- per-element sanitization below.
		$raw_all = ( isset( $_POST['p4all_brand_all_label'] ) && is_array( $_POST['p4all_brand_all_label'] ) )
			? wp_unslash( $_POST['p4all_brand_all_label'] )
			: [];
		// phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		$all_labels = [];
		foreach ( $raw_all as $code => $label ) {
			$code = strtolower( sanitize_key( (string) $code ) );
			if ( ! in_array( $code, \Pay4All\Form\Admin\Settings\Schema::SUPPORTED_LANGUAGES, true ) ) { continue; }
			$label = trim( sanitize_text_field( (string) $label ) );
			if ( $label !== '' ) { $all_labels[ $code ] = $label; }
		}
		update_term_meta( $term_id, Brand::META_ALL_LABELS, $all_labels );
	}

	public static function columns( array $cols ) : array {
		$cols['p4all_rule'] = __( 'Règle', 'pay4all-pro' );
		return $cols;
	}

	public static function render_column( $content, string $column, int $term_id ) {
		if ( $column !== 'p4all_rule' ) { return $content; }
		$type = Brand::rule_type( $term_id );
		switch ( $type ) {
			case 'min':
				/* translators: %d = minimum quantity */
				return esc_html( sprintf( __( 'min %d', 'pay4all-pro' ), Brand::min_total( $term_id ) ) );
			case 'max':
				/* translators: %d = maximum quantity */
				return esc_html( sprintf( __( 'max %d', 'pay4all-pro' ), Brand::max_total( $term_id ) ) );
			case 'multiple':
				/* translators: %d = required multiple */
				return esc_html( sprintf( __( '× %d', 'pay4all-pro' ), Brand::multiple( $term_id ) ) );
			case 'min_multiple':
				/* translators: 1: minimum quantity, 2: required multiple */
				return esc_html( sprintf( __( '≥ %1$d, × %2$d', 'pay4all-pro' ), Brand::min_total( $term_id ), Brand::multiple( $term_id ) ) );
			case 'exact':
				/* translators: %d = exact required quantity */
				return esc_html( sprintf( __( '= %d', 'pay4all-pro' ), Brand::exact_total( $term_id ) ) );
		}
		return '—';
	}
}
