<?php
/**
 * WooCommerce product data tab integration for FoodOrd product labels.
 *
 * @package FoodOrd
 */

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

/**
 * Handles the FoodOrd Labels tab in WooCommerce product edit pages.
 */
class Foodord_Product_Data_Labels {

	/**
	 * Bootstrap hooks for WooCommerce product data integration.
	 */
	public function init(): void {
		if ( ! is_admin() ) {
			return;
		}

		add_filter( 'woocommerce_product_data_tabs', array( $this, 'register_product_data_tab' ), 99, 1 );
		add_action( 'woocommerce_product_data_panels', array( $this, 'render_product_data_panel' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_product_data_assets' ), 999 );
		add_action( 'woocommerce_process_product_meta', array( $this, 'save_product_labels' ) );
	}

	/**
	 * Register Product Labels tab under WooCommerce product data.
	 *
	 * @param array<string,array<string,mixed>> $tabs Existing product data tabs.
	 * @return array<string,array<string,mixed>>
	 */
	public function register_product_data_tab( array $tabs ): array {
		$tabs['foodord_product_labels'] = array(
			'label'    => esc_html__( 'FoodOrd Labels', 'foodord' ),
			'target'   => 'foodord_product_labels_data',
			'class'    => array( 'show_if_simple', 'show_if_variable', 'show_if_grouped', 'show_if_external' ),
			'priority' => 84,
		);

		return $tabs;
	}

	/**
	 * Enqueue product labels admin styles.
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_product_data_assets( string $hook ): void {
		if ( 'post.php' !== $hook && 'post-new.php' !== $hook ) {
			return;
		}

		global $post;
		if ( ! $post || 'product' !== $post->post_type ) {
			return;
		}

		wp_enqueue_style(
			'foodord-product-data-labels',
			plugin_dir_url( __FILE__ ) . 'css/foodord-product-data-labels.css',
			array( 'woocommerce_admin_styles' ),
			FOODORD_VERSION
		);
	}

	/**
	 * Save product labels when product is saved.
	 *
	 * @param int $post_id Product ID.
	 */
	public function save_product_labels( int $post_id ): void {
		if ( ! isset( $_POST['woocommerce_meta_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['woocommerce_meta_nonce'] ) ), 'woocommerce_save_data' ) ) {
			return;
		}

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

		$raw_labels      = isset( $_POST['foodord_product_labels'] ) ? array_map( 'sanitize_key', (array) wp_unslash( $_POST['foodord_product_labels'] ) ) : array();
		$selected_labels = Foodord_Product_Labels::sanitize_labels( $raw_labels );

		if ( ! empty( $selected_labels ) ) {
			update_post_meta( $post_id, Foodord_Product_Labels::META_KEY, $selected_labels );
		} else {
			delete_post_meta( $post_id, Foodord_Product_Labels::META_KEY );
		}
	}

	/**
	 * Output the Product Labels panel markup.
	 */
	public function render_product_data_panel(): void {
		global $post;

		if ( ! $post instanceof WP_Post ) {
			return;
		}

		$product_id      = (int) $post->ID;
		$selected_labels = Foodord_Product_Labels::get_product_labels( $product_id );
		$definitions     = Foodord_Product_Labels::get_definitions();
		?>
		<div id="foodord_product_labels_data" class="panel woocommerce_options_panel hidden">
			<div class="options_group foodord-product-labels-panel">
				<p class="form-field foodord-product-labels-panel__intro">
					<span class="description foodord-product-labels-panel__description">
						<?php esc_html_e( 'Choose the labels that should appear on this product card and product modal.', 'foodord' ); ?>
					</span>
				</p>
				<div class="foodord-product-labels-panel__grid">
					<?php foreach ( $definitions as $slug => $definition ) : ?>
						<?php
						$field_id     = 'foodord-product-label-' . sanitize_html_class( $slug );
						$option_class = 'foodord-product-labels-panel__option foodord-product-labels-panel__option--' . sanitize_html_class( $slug );
						$label        = isset( $definition['label'] ) ? (string) $definition['label'] : '';
						$checked_attr = in_array( $slug, $selected_labels, true ) ? ' checked="checked"' : '';

						echo wp_kses(
							sprintf(
								'<label class="%1$s" for="%2$s"><input type="checkbox" id="%2$s" class="foodord-product-labels-panel__checkbox" name="foodord_product_labels[]" value="%3$s"%4$s><span class="foodord-product-labels-panel__label">%5$s</span></label>',
								esc_attr( $option_class ),
								esc_attr( $field_id ),
								esc_attr( $slug ),
								$checked_attr,
								esc_html( $label )
							),
							array(
								'label' => array(
									'class' => true,
									'for'   => true,
								),
								'input' => array(
									'class'   => true,
									'checked' => true,
									'id'      => true,
									'name'    => true,
									'type'    => true,
									'value'   => true,
								),
								'span'  => array(
									'class' => true,
								),
							)
						);
						?>
					<?php endforeach; ?>
				</div>
			</div>
		</div>
		<?php
	}
}
