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

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

/**
 * Class Foodord_Product_Data_Topping_Sets
 */
class Foodord_Product_Data_Topping_Sets {

	/**
	 * Bootstrap hooks for WooCommerce product data integration.
	 */
	public function init() {
		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_topping_sets' ) );
	}

	/**
	 * Register FoodOrd Topping Sets tab under WooCommerce product data.
	 *
	 * @param array $tabs Existing product data tabs.
	 *
	 * @return array
	 */
	public function register_product_data_tab( $tabs ) {
		$tabs['foodord_topping_sets'] = array(
			'label'    => esc_html__( 'FoodOrd Topping Sets', 'foodord' ),
			'target'   => 'foodord_topping_sets_data',
			'class'    => array( 'show_if_simple', 'show_if_variable', 'show_if_grouped', 'show_if_external' ),
			'priority' => 80,
		);

		return $tabs;
	}

	/**
	 * Enqueue scripts and styles for product data panel.
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_product_data_assets( $hook ) {
		// Only load on product edit pages.
		if ( 'post.php' !== $hook && 'post-new.php' !== $hook ) {
			return;
		}

		// Check if we're on a product page.
		global $post;
		if ( ! $post || 'product' !== $post->post_type ) {
			return;
		}

		// Enqueue CSS with WooCommerce admin styles as dependency to ensure proper load order.
		wp_enqueue_style(
			'foodord-product-data-topping-sets',
			plugin_dir_url( __FILE__ ) . 'css/foodord-product-data-topping-sets.css',
			array( 'woocommerce_admin_styles' ), // Add WooCommerce admin styles as dependency.
			FOODORD_VERSION
		);

		// Enqueue JavaScript.
		wp_enqueue_script(
			'foodord-product-data-topping-sets',
			plugin_dir_url( __FILE__ ) . 'js/foodord-product-data-topping-sets.js',
			array( 'jquery', 'jquery-ui-sortable' ),
			FOODORD_VERSION,
			true
		);

		// Localize script for future AJAX operations.
		wp_localize_script(
			'foodord-product-data-topping-sets',
			'foodordProductDataToppingSets',
			array(
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'nonce'   => wp_create_nonce( 'foodord_product_topping_sets' ),
				'strings' => array(
					'saveSuccess' => __( 'Topping sets saved successfully.', 'foodord' ),
					'saveError'   => __( 'Error saving topping sets.', 'foodord' ),
				),
			)
		);
	}

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

		// Check user permissions.
		if ( ! current_user_can( 'edit_posts' ) ) {
			return;
		}

		// Get selected topping sets.
		$selected_sets = array();
		if ( isset( $_POST['foodord_topping_sets'] ) && is_array( $_POST['foodord_topping_sets'] ) ) {
			$selected_sets = array_map( 'sanitize_text_field', wp_unslash( $_POST['foodord_topping_sets'] ) );
		}

		// Get topping sets order.
		$topping_sets_order = array();
		if ( isset( $_POST['foodord_topping_sets_order'] ) && ! empty( $_POST['foodord_topping_sets_order'] ) ) {
			$order_json = sanitize_text_field( wp_unslash( $_POST['foodord_topping_sets_order'] ) );
			$order_data = json_decode( $order_json, true );
			if ( is_array( $order_data ) ) {
				$topping_sets_order = array_map( 'sanitize_text_field', $order_data );
			}
		}

		// Persist per-product exclusions for sets auto-applied by category mappings.
		$topping_sets = get_option( 'foodord_topping_sets', array() );
		$topping_sets = is_array( $topping_sets ) ? $topping_sets : array();

		$product_term_ids = wp_get_post_terms( $post_id, 'product_cat', array( 'fields' => 'ids' ) );
		$product_term_ids = is_array( $product_term_ids ) ? array_map( 'absint', $product_term_ids ) : array();

		$auto_selected_set_ids = array();
		if ( ! empty( $product_term_ids ) ) {
			foreach ( $topping_sets as $set ) {
				if ( ! is_array( $set ) ) {
					continue;
				}
				$set_id = isset( $set['id'] ) ? sanitize_text_field( (string) $set['id'] ) : '';
				$cats   = isset( $set['categories'] ) && is_array( $set['categories'] ) ? array_map( 'absint', $set['categories'] ) : array();
				if ( '' === $set_id || empty( $cats ) ) {
					continue;
				}
				if ( array_intersect( $cats, $product_term_ids ) ) {
					$auto_selected_set_ids[] = $set_id;
				}
			}
			$auto_selected_set_ids = array_values( array_unique( $auto_selected_set_ids ) );
		}

		$existing_excluded = get_post_meta( $post_id, '_foodord_topping_sets_excluded', true );
		$existing_excluded = is_array( $existing_excluded ) ? array_values( array_unique( array_map( 'sanitize_text_field', $existing_excluded ) ) ) : array();

		$excluded_now = array();
		if ( ! empty( $auto_selected_set_ids ) ) {
			$excluded_now = array_values( array_diff( $auto_selected_set_ids, $selected_sets ) );
		}

		$next_excluded = $existing_excluded;
		if ( ! empty( $auto_selected_set_ids ) ) {
			$next_excluded = array_values( array_diff( $next_excluded, $auto_selected_set_ids ) );
			$next_excluded = array_merge( $next_excluded, $excluded_now );
		}
		$next_excluded = array_values( array_unique( array_map( 'sanitize_text_field', $next_excluded ) ) );

		if ( ! empty( $next_excluded ) ) {
			update_post_meta( $post_id, '_foodord_topping_sets_excluded', $next_excluded );
		} else {
			delete_post_meta( $post_id, '_foodord_topping_sets_excluded' );
		}

		// Save selected sets to post meta.
		if ( ! empty( $selected_sets ) ) {
			update_post_meta( $post_id, '_foodord_topping_sets', $selected_sets );
		} else {
			delete_post_meta( $post_id, '_foodord_topping_sets' );
		}

		// Save order to post meta.
		if ( ! empty( $topping_sets_order ) ) {
			update_post_meta( $post_id, '_foodord_topping_sets_order', $topping_sets_order );
		} else {
			delete_post_meta( $post_id, '_foodord_topping_sets_order' );
		}
	}

	/**
	 * Output the FoodOrd Topping Sets panel markup.
	 */
	public function render_product_data_panel() {
		global $post;

		// Get all topping sets.
		$topping_sets = get_option( 'foodord_topping_sets', array() );
		$topping_sets = is_array( $topping_sets ) ? $topping_sets : array();

		// Get product's selected topping sets and order.
		$product_id    = $post->ID;
		$selected_sets = get_post_meta( $product_id, '_foodord_topping_sets', true );
		$selected_sets = is_array( $selected_sets ) ? $selected_sets : array();
		$saved_order   = get_post_meta( $product_id, '_foodord_topping_sets_order', true );
		$saved_order   = is_array( $saved_order ) ? $saved_order : array();

		// Sort topping sets by saved order.
		if ( ! empty( $saved_order ) ) {
			$ordered_sets   = array();
			$unordered_sets = array();

			// First add sets in saved order.
			foreach ( $saved_order as $ordered_id ) {
				foreach ( $topping_sets as $key => $set ) {
					if ( isset( $set['id'] ) && $set['id'] === $ordered_id ) {
						$ordered_sets[] = $set;
						unset( $topping_sets[ $key ] );
						break;
					}
				}
			}

			// Add any remaining sets (new ones not in saved order).
			foreach ( $topping_sets as $set ) {
				$unordered_sets[] = $set;
			}

			$topping_sets = array_merge( $ordered_sets, $unordered_sets );
		}

		// Compute auto-selected sets by product's categories (global mappings).
		$product_term_ids      = wp_get_post_terms( $product_id, 'product_cat', array( 'fields' => 'ids' ) );
		$product_term_ids      = is_array( $product_term_ids ) ? array_map( 'absint', $product_term_ids ) : array();
		$auto_selected_set_ids = array();
		if ( ! empty( $product_term_ids ) ) {
			foreach ( $topping_sets as $set ) {
				if ( ! is_array( $set ) ) {
					continue;
				}
				$set_id = isset( $set['id'] ) ? sanitize_text_field( (string) $set['id'] ) : '';
				$cats   = isset( $set['categories'] ) && is_array( $set['categories'] ) ? array_map( 'absint', $set['categories'] ) : array();
				if ( '' !== $set_id && ! empty( $cats ) && array_intersect( $cats, $product_term_ids ) ) {
					$auto_selected_set_ids[] = $set_id;
				}
			}
			$auto_selected_set_ids = array_values( array_unique( $auto_selected_set_ids ) );
		}

		$excluded_set_ids = get_post_meta( $product_id, '_foodord_topping_sets_excluded', true );
		$excluded_set_ids = is_array( $excluded_set_ids ) ? array_values( array_unique( array_map( 'sanitize_text_field', $excluded_set_ids ) ) ) : array();
		?>
		<div id="foodord_topping_sets_data" class="panel woocommerce_options_panel hidden">
			<div class="foodord-topping-panel">
				<div class="foodord-topping-panel__header">
					<h3 class="foodord-topping-panel__title"><?php esc_html_e( 'Available Topping Sets', 'foodord' ); ?></h3>
					<p class="foodord-topping-panel__description">
						<?php esc_html_e( 'Select and arrange topping sets for this product. Drag to reorder, toggle to enable/disable.', 'foodord' ); ?>
					</p>
				</div>
				
				<?php if ( empty( $topping_sets ) ) : ?>
					<?php
					$page_url = function_exists( 'foodord_get_admin_page_url' )
						? foodord_get_admin_page_url( 'topping_sets' )
						: admin_url( 'admin.php?page=foodord-topping-sets' );
					?>
					<div class="foodord-topping-panel__empty">
						<p class="foodord-topping-panel__empty-message"><?php esc_html_e( 'No topping sets available. Please create topping sets from FoodOrd → Topping Sets.', 'foodord' ); ?></p>
						<a href="<?php echo esc_url( $page_url ); ?>" class="button button-primary">
							<?php esc_html_e( 'Create Topping Sets', 'foodord' ); ?>
						</a>
					</div>
				<?php else : ?>
					<div class="foodord-topping-panel__sets" data-product-id="<?php echo esc_attr( $product_id ); ?>">
						<?php
						foreach ( $topping_sets as $index => $set ) :
							$set_id      = isset( $set['id'] ) ? sanitize_text_field( (string) $set['id'] ) : 'set_' . $index;
							$name        = isset( $set['name'] ) ? $set['name'] : '';
							$label       = isset( $set['label'] ) ? $set['label'] : '';
							$group_type  = isset( $set['group_type'] ) ? $set['group_type'] : 'dropdown';
							$items       = isset( $set['items'] ) && is_array( $set['items'] ) ? $set['items'] : array();
							$categories  = isset( $set['categories'] ) && is_array( $set['categories'] ) ? $set['categories'] : array();
							$is_auto     = in_array( $set_id, $auto_selected_set_ids, true );
							$is_excluded = in_array( $set_id, $excluded_set_ids, true );
							$is_selected = in_array( $set_id, $selected_sets, true ) || ( $is_auto && ! $is_excluded );

							// Get category names.
							$category_names = array();
							foreach ( $categories as $cat_id ) {
								$term = get_term( $cat_id, 'product_cat' );
								if ( $term && ! is_wp_error( $term ) ) {
									$category_names[] = $term->name;
								}
							}

							// Determine group type icon.
							$type_icon = '';
							if ( 'dropdown' === $group_type ) {
								$type_icon = 'dashicons-arrow-down-alt2';
							} elseif ( 'radio' === $group_type ) {
								$type_icon = 'dashicons-marker';
							} else {
								$type_icon = 'dashicons-yes';
							}
							?>
			<div class="foodord-topping-card<?php echo esc_html( $is_selected ? ' is-selected' : '' ); ?>"
				data-set-id="<?php echo esc_attr( $set_id ); ?>"
				data-set-name="<?php echo esc_attr( $name ); ?>">
							 
							<div class="foodord-topping-card__header">
								<div class="foodord-topping-card__drag-handle">
									<span class="dashicons dashicons-move" title="<?php esc_attr_e( 'Drag to reorder', 'foodord' ); ?>"></span>
								</div>
								
								<div class="foodord-topping-card__info">
									<h4 class="foodord-topping-card__title">
										<?php echo esc_html( $name ? $name : __( 'Untitled Set', 'foodord' ) ); ?>
									</h4>
									<?php if ( $label ) : ?>
										<span class="foodord-topping-card__label"><?php echo esc_html( $label ); ?></span>
									<?php endif; ?>
								</div>
								
								<div class="foodord-topping-card__toggle">
									<label class="foodord-toggle-switch">
										<input type="checkbox" 
											class="foodord-topping-card__enable" 
											name="foodord_topping_sets[]" 
											value="<?php echo esc_attr( $set_id ); ?>"
											<?php checked( $is_selected ); ?> />
										<span class="foodord-toggle-switch__slider"></span>
									</label>
								</div>
							</div>
							
							<div class="foodord-topping-card__body">
								<div class="foodord-topping-card__meta">
									<span class="foodord-topping-card__meta-item">
										<span class="dashicons <?php echo esc_attr( $type_icon ); ?>"></span>
										<?php
										if ( 'dropdown' === $group_type ) {
											esc_html_e( 'Dropdown', 'foodord' );
										} elseif ( 'radio' === $group_type ) {
											esc_html_e( 'Radio', 'foodord' );
										} else {
											esc_html_e( 'Checkbox', 'foodord' );
										}
										?>
									</span>

									<span class="foodord-topping-card__meta-item">
										<span class="dashicons dashicons-menu-alt"></span>
										<?php
										// translators: %d is the number of items in the topping set.
										printf( esc_html( _n( '%d item', '%d items', count( $items ), 'foodord' ) ), count( $items ) );
										?>
									</span>
									
									<?php if ( ! empty( $category_names ) ) : ?>
										<span class="foodord-topping-card__meta-item">
											<span class="dashicons dashicons-category"></span>
											<?php echo esc_html( implode( ', ', array_slice( $category_names, 0, 2 ) ) ); ?>
											<?php if ( count( $category_names ) > 2 ) : ?>
					<span class="foodord-topping-card__more">+<?php echo esc_html( count( $category_names ) - 2 ); ?></span>
											<?php endif; ?>
										</span>
									<?php endif; ?>
								</div>
							</div>
						</div>
						<?php endforeach; ?>
					</div>
					
				<?php endif; ?>
			</div>
		</div>
		<?php
	}
}
