<?php
namespace Pay4All\Pro\Integrations\Age;

// phpcs:disable WordPress.WP.I18n.TextDomainMismatch -- Bridge to pay4all-age :
// the product-level « Requires age verification » labels are the exact same
// strings the free plugin exposes on the Pay4All Shop product screen, we just
// re-emit them on the WooCommerce product screen. Reusing the pay4all-age
// text domain avoids duplicating 4 msgids × 4 locales in pay4all-pro's .po files.

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

/**
 * "Requires age verification" support across three admin surfaces:
 *
 *   1. Product edit screen — checkbox in the General product-data tab.
 *   2. Products list column — small shield badge showing at a glance
 *      whether the product requires the KYC flow.
 *   3. Quick Edit row — inline checkbox so the merchant can toggle the
 *      flag from the list without opening the full editor.
 *
 * Meta key `_pay4all_age_required`, stored as WooCommerce boolean
 * (`'yes'` when set, meta deleted when unset).
 */
final class ProductFields {

	public const META_KEY = '_pay4all_age_required';

	public static function register() : void {
		// Full edit screen
		add_action( 'woocommerce_product_options_general_product_data', [ __CLASS__, 'render_field' ] );
		add_action( 'woocommerce_process_product_meta',                 [ __CLASS__, 'save_field' ] );

		// Products list column
		add_filter( 'manage_edit-product_columns',            [ __CLASS__, 'add_column' ] );
		add_action( 'manage_product_posts_custom_column',     [ __CLASS__, 'render_column' ], 10, 2 );

		// Quick Edit
		add_action( 'quick_edit_custom_box',                  [ __CLASS__, 'render_quick_edit' ], 10, 2 );
		add_action( 'woocommerce_product_quick_edit_save',    [ __CLASS__, 'save_quick_edit' ] );
		add_action( 'admin_enqueue_scripts',                  [ __CLASS__, 'enqueue_admin_assets' ] );
	}

	// ---------------------------------------------------------------
	// Product edit screen
	// ---------------------------------------------------------------

	public static function render_field() : void {
		woocommerce_wp_checkbox( [
			'id'          => self::META_KEY,
			'label'       => __( 'Age verification required', 'pay4all-age-verification' ),
			'description' => __( 'When ticked, this product triggers ID + selfie capture at checkout.', 'pay4all-age-verification' ),
			'desc_tip'    => true,
		] );
	}

	public static function save_field( int $post_id ) : void {
		// WC convention : `woocommerce_wp_checkbox` reads the meta value
		// and only pre-checks the box when it equals its `cbvalue` (default
		// `'yes'`). Storing `'1'` would make the box appear unchecked
		// after each save even when the merchant just ticked it.
		// Nonce : this handler is bound to `woocommerce_process_product_meta`
		// which fires from `WC_Meta_Box_Product_Data::save()`, itself gated
		// by `check_admin_referer( 'update-post_' . $post_id )` upstream.
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified by WC upstream on woocommerce_process_product_meta.
		if ( isset( $_POST[ self::META_KEY ] ) ) {
			update_post_meta( $post_id, self::META_KEY, 'yes' );
		} else {
			delete_post_meta( $post_id, self::META_KEY );
		}
	}

	// ---------------------------------------------------------------
	// Products-list column
	// ---------------------------------------------------------------

	public static function add_column( array $columns ) : array {
		// Insert the column right after `name` (the product title column)
		// when possible so it sits near the top of the row for scanability.
		$title = \Pay4All\Age\Services\Config::admin( 'col_age_title' );
		$out   = [];
		foreach ( $columns as $key => $label ) {
			$out[ $key ] = $label;
			if ( $key === 'name' ) {
				$out['p4all_age_required'] = $title;
			}
		}
		// Fallback if `name` wasn't in the columns for some reason.
		if ( ! isset( $out['p4all_age_required'] ) ) {
			$out['p4all_age_required'] = $title;
		}
		return $out;
	}

	public static function render_column( string $column, int $post_id ) : void {
		if ( $column !== 'p4all_age_required' ) { return; }
		$required = get_post_meta( $post_id, self::META_KEY, true ) === 'yes';

		// Hidden marker read by the Quick-Edit JS to pre-fill the
		// checkbox — WordPress doesn't expose per-row meta to inline-
		// edit so we inline the value in the cell where JS can find it.
		echo '<span class="p4all-age-required-flag" data-value="' . esc_attr( $required ? 'yes' : 'no' ) . '" style="display:none;"></span>';

		if ( $required ) {
			echo '<span title="' . esc_attr( \Pay4All\Age\Services\Config::admin( 'col_age_tooltip' ) ) . '"'
				. ' aria-label="' . esc_attr( \Pay4All\Age\Services\Config::admin( 'col_age_badge' ) ) . '"'
				. ' style="display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;background:#fff5e5;color:#a85a00;border:1px solid #f2c896;border-radius:4px;">'
				. '<span class="dashicons dashicons-shield-alt" style="font-size:16px;width:16px;height:16px;line-height:16px;"></span>'
				. '</span>';
		} else {
			echo '<span style="color:#bbb;">—</span>';
		}
	}

	// ---------------------------------------------------------------
	// Quick Edit
	// ---------------------------------------------------------------

	/**
	 * @param string $column_name Currently-rendered Quick-Edit column.
	 * @param string $post_type   Post type of the row being edited.
	 */
	public static function render_quick_edit( string $column_name, string $post_type ) : void {
		if ( $post_type !== 'product' ) { return; }
		if ( $column_name !== 'p4all_age_required' ) { return; }
		?>
		<fieldset class="inline-edit-col-right p4all-age-quickedit">
			<div class="inline-edit-col">
				<label class="alignleft">
					<input type="checkbox" name="<?php echo esc_attr( self::META_KEY ); ?>" value="yes">
					<span class="checkbox-title"><?php esc_html_e( 'Age verification required', 'pay4all-age-verification' ); ?></span>
				</label>
			</div>
		</fieldset>
		<?php
	}

	/**
	 * Fires during a Quick-Edit save. Receives the `WC_Product` object.
	 *
	 * @param \WC_Product $product
	 */
	public static function save_quick_edit( $product ) : void {
		if ( ! is_object( $product ) || ! method_exists( $product, 'get_id' ) ) { return; }
		$post_id = (int) $product->get_id();
		if ( ! $post_id ) { return; }

		// Nonce : bound to `woocommerce_product_quick_edit_save` fired from
		// WC's Quick-Edit AJAX handler which itself verifies the WC inline
		// edit nonce upstream.
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified by WC upstream on woocommerce_product_quick_edit_save.
		if ( isset( $_POST[ self::META_KEY ] ) ) {
			update_post_meta( $post_id, self::META_KEY, 'yes' );
		} else {
			delete_post_meta( $post_id, self::META_KEY );
		}
	}

	// ---------------------------------------------------------------
	// Admin JS for Quick-Edit pre-fill
	// ---------------------------------------------------------------

	public static function enqueue_admin_assets( string $hook ) : void {
		if ( $hook !== 'edit.php' ) { return; }
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( ! $screen || $screen->post_type !== 'product' ) { return; }
		add_action( 'admin_footer', [ __CLASS__, 'print_quick_edit_script' ] );
	}

	public static function print_quick_edit_script() : void {
		?>
		<script>
		jQuery(function ($) {
			// Hook into WordPress's Quick Edit "open" event. When the
			// merchant clicks "Édition rapide", WP replaces the row
			// with a form; we intercept AFTER the original edit runs,
			// look for the hidden `.p4all-age-required-flag` marker in
			// the row, and pre-check our checkbox to match the DB.
			//
			// The `setTimeout(fn, 0)` defer guarantees we run after any
			// other plugin (WooCommerce, extensions) that also wraps
			// `inlineEditPost.edit`, so our checkbox update isn't
			// overwritten by their populate logic.
			if (typeof inlineEditPost === 'undefined') return;
			var META_KEY = <?php echo wp_json_encode( self::META_KEY ); ?>;
			var origEdit = inlineEditPost.edit;
			inlineEditPost.edit = function (id) {
				var ret = origEdit.apply(this, arguments);
				var postId = 0;
				if (typeof id === 'object') {
					postId = parseInt(this.getId(id), 10);
				} else if (typeof id === 'number') {
					postId = id;
				} else if (typeof id === 'string' && id !== 'bulk') {
					postId = parseInt(id, 10);
				}
				if (!postId) return ret;
				setTimeout(function () {
					var $row     = $('#post-' + postId);
					var $editRow = $('#edit-' + postId);
					if (!$row.length || !$editRow.length) return;
					var val = $row.find('.p4all-age-required-flag').data('value');
					var $cb = $editRow.find('input[name="' + META_KEY + '"]');
					if ($cb.length) {
						$cb.prop('checked', val === 'yes');
					}
				}, 0);
				return ret;
			};
		});
		</script>
		<?php
	}
}
