<?php
/**
 * Topping Sets admin functionality for FoodOrd.
 *
 * @package FoodOrd
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class Foodord_Topping_Sets
 */
class Foodord_Topping_Sets {
	/**
	 * Sanitize an optional topping tax class against WooCommerce settings.
	 *
	 * @param mixed $value Submitted tax class.
	 */
	private function sanitize_topping_tax_class( $value ): string {
		$value = sanitize_title( (string) $value );
		if ( '' === $value || 'standard' === $value ) {
			return $value;
		}

		$allowed = class_exists( 'WC_Tax' ) ? array_map( 'sanitize_title', WC_Tax::get_tax_class_slugs() ) : array();
		return in_array( $value, $allowed, true ) ? $value : '';
	}

	/**
	 * Get the slug for the Topping Sets admin page.
	 */
	private function get_page_slug(): string {
		return function_exists( 'foodord_get_settings_page_slug' )
			? foodord_get_settings_page_slug( 'topping_sets' )
			: 'foodord-topping-sets';
	}

	/**
	 * Retrieve possible slugs (theme/plugin) for Topping Sets page.
	 *
	 * @return string[]
	 */
	private function get_page_slugs(): array {
		return function_exists( 'foodord_get_settings_page_slugs' )
			? foodord_get_settings_page_slugs( 'topping_sets' )
			: array( 'foodord-theme-settings-topping-sets', 'foodord-topping-sets' );
	}

	/**
	 * Build the admin URL for the Topping Sets page.
	 *
	 * @param array $args Optional query args.
	 */
	private function get_page_url( array $args = array() ): string {
		$base = function_exists( 'foodord_get_admin_page_url' )
			? foodord_get_admin_page_url( 'topping_sets' )
			: admin_url( 'admin.php?page=foodord-topping-sets' );

		return empty( $args ) ? $base : add_query_arg( $args, $base );
	}

	/**
	 * Bootstrap admin hooks.
	 */
	public function init() {
		add_action( 'admin_menu', array( $this, 'register_topping_sets_submenu' ), 17 );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_topping_sets_assets' ) );
		// Handle saving topping group submissions from the Toppings page.
		add_action( 'admin_post_foodord_save_topping_group', array( $this, 'handle_save_topping_group' ) );
		add_action( 'admin_post_foodord_update_topping_group', array( $this, 'handle_update_topping_group' ) );
		add_action( 'admin_init', array( $this, 'handle_delete_topping_set' ) );
		add_action( 'admin_init', array( $this, 'handle_duplicate_topping_set' ) );
	}

	/**
	 * Handle duplicating an existing topping set.
	 */
	public function handle_duplicate_topping_set() {
		// Check if duplicate action is triggered.
		if ( ! isset( $_GET['action'] ) || 'duplicate_topping_set' !== $_GET['action'] ) {
			return;
		}

		// Check if we're on the right page.
		$page_raw = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$page     = is_string( $page_raw ) ? sanitize_text_field( $page_raw ) : '';
		if ( ! in_array( $page, $this->get_page_slugs(), true ) ) {
			return;
		}

		// Check permissions.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Insufficient permissions.', 'foodord' ) );
		}

		// Verify nonce.
		if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'duplicate_topping_set' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'foodord' ) );
		}

		// Get set ID.
		$set_id = isset( $_GET['set_id'] ) ? sanitize_text_field( wp_unslash( $_GET['set_id'] ) ) : '';
		if ( empty( $set_id ) ) {
			wp_safe_redirect( $this->get_page_url() );
			exit;
		}

		$sets = get_option( 'foodord_topping_sets', array() );
		if ( ! is_array( $sets ) ) {
			$sets = array();
		}

		$source_set = null;
		foreach ( $sets as $set ) {
			if ( isset( $set['id'] ) && $set['id'] === $set_id ) {
				$source_set = $set;
				break;
			}
		}

		if ( ! is_array( $source_set ) ) {
			wp_safe_redirect( $this->get_page_url( array( 'status' => 'not_found' ) ) );
			exit;
		}

		$copy_suffix           = __( '(Copy)', 'foodord' );
		$new_set               = $source_set;
		$new_set['id']         = 'wrc_set_' . wp_generate_uuid4();
		$new_set['created_at'] = current_time( 'mysql', true );
		$new_set['updated_at'] = current_time( 'mysql', true );
		if ( isset( $new_set['name'] ) && '' !== (string) $new_set['name'] ) {
			$new_set['name'] = (string) $new_set['name'] . ' ' . $copy_suffix;
		}
		if ( isset( $new_set['label'] ) && '' !== (string) $new_set['label'] ) {
			$new_set['label'] = (string) $new_set['label'] . ' ' . $copy_suffix;
		}

		$sets[] = $new_set;
		update_option( 'foodord_topping_sets', $sets, false );

		wp_safe_redirect( $this->get_page_url( array( 'duplicated' => '1' ) ) );
		exit;
	}

	/**
	 * Register Topping Sets submenu to existing Theme Settings menu.
	 */
	public function register_topping_sets_submenu() {
		if ( current_user_can( 'manage_options' ) ) {
			$parent_slug = function_exists( 'foodord_get_admin_parent_slug' )
				? foodord_get_admin_parent_slug()
				: 'foodord-settings';

			add_submenu_page(
				$parent_slug,
				__( 'Topping Sets', 'foodord' ),
				__( 'Topping Sets', 'foodord' ),
				'manage_options',
				$this->get_page_slug(),
				array( $this, 'render_topping_sets_page' )
			);
		}
	}

	/**
	 * Enqueue admin scripts and styles for Topping Sets page.
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_topping_sets_assets( $hook ) {
		$should_enqueue = false;
		foreach ( $this->get_page_slugs() as $slug ) {
			if ( '' !== $slug && false !== strpos( (string) $hook, $slug ) ) {
				$should_enqueue = true;
				break;
			}
		}

		if ( ! $should_enqueue ) {
			return;
		}

		// Enqueue CSS.
		wp_enqueue_style(
			'foodord-topping-sets',
			plugin_dir_url( __FILE__ ) . 'css/foodord-topping-sets.css',
			array(),
			FOODORD_VERSION
		);

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

		wp_localize_script(
			'foodord-topping-sets',
			'foodordToppingSetsAdmin',
			array(
				'adminUrl'     => admin_url( 'admin.php' ),
				'toppingsPage' => function_exists( 'foodord_get_settings_page_slug' )
					? foodord_get_settings_page_slug( 'toppings' )
					: 'foodord-toppings',
			)
		);
	}

	/**
	 * Handle saving topping group data from the Toppings page.
	 */
	public function handle_save_topping_group() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Insufficient permissions.', 'foodord' ) );
		}

		check_admin_referer( 'foodord_save_topping_group', '_foodord_nonce' );

		$limit_trimmed = false;

		$allowed_types = array( 'dropdown', 'radio', 'checkbox' );
		$group_type    = isset( $_POST['selected_group_type'] ) ? sanitize_key( wp_unslash( $_POST['selected_group_type'] ) ) : 'dropdown';
		$group_type    = in_array( $group_type, $allowed_types, true ) ? $group_type : 'dropdown';

		$name  = isset( $_POST['topping_group_name'] ) ? sanitize_text_field( wp_unslash( $_POST['topping_group_name'] ) ) : '';
		$label = isset( $_POST['topping_group_label'] ) ? sanitize_text_field( wp_unslash( $_POST['topping_group_label'] ) ) : '';

		$hide_price = 0;
		if ( isset( $_POST['topping_hide_price'] ) && is_array( $_POST['topping_hide_price'] ) ) {
			$hide_price = ! empty( $_POST['topping_hide_price'][ $group_type ] ) ? 1 : 0;
		}

		$is_required = 0;
		if ( isset( $_POST['topping_required_state'] ) && is_array( $_POST['topping_required_state'] ) ) {
			$required_state = array_map( 'sanitize_text_field', (array) wp_unslash( $_POST['topping_required_state'] ) );
			if ( isset( $required_state[ $group_type ] ) ) {
				$is_required = '1' === $required_state[ $group_type ] ? 1 : 0;
			}
		}

		$checkbox_min = null;
		$checkbox_max = null;
		if ( 'checkbox' === $group_type ) {
			$checkbox_min = isset( $_POST['topping_checkbox_minimum'] ) ? absint( $_POST['topping_checkbox_minimum'] ) : null;
			$checkbox_max = isset( $_POST['topping_checkbox_maximum'] ) ? absint( $_POST['topping_checkbox_maximum'] ) : null;
		}

		$labels = array();
		if ( isset( $_POST['topping_item_label'] ) && is_array( $_POST['topping_item_label'] ) ) {
			$labels = array_map( 'sanitize_text_field', (array) wp_unslash( $_POST['topping_item_label'] ) );
		}
		$prices = array();
		if ( isset( $_POST['topping_item_price'] ) && is_array( $_POST['topping_item_price'] ) ) {
			$price_strings = array_map( 'sanitize_text_field', (array) wp_unslash( $_POST['topping_item_price'] ) );
			foreach ( $price_strings as $raw_price ) {
				$prices[] = (float) $raw_price;
			}
		}
		$tax_classes     = array();
		$raw_tax_classes = filter_input( INPUT_POST, 'topping_item_tax_class', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY );
		if ( is_array( $raw_tax_classes ) ) {
			foreach ( $raw_tax_classes as $raw_tax_class ) {
				$tax_classes[] = $this->sanitize_topping_tax_class( sanitize_text_field( $raw_tax_class ) );
			}
		}
		$defaults = array();
		if ( isset( $_POST['topping_item_default'] ) && is_array( $_POST['topping_item_default'] ) && isset( $_POST['topping_item_default'][ $group_type ] ) && is_array( $_POST['topping_item_default'][ $group_type ] ) ) {
			$defaults = array_map( 'absint', (array) wp_unslash( $_POST['topping_item_default'][ $group_type ] ) );
		}

		$items = array();
		$max   = max( count( $labels ), count( $prices ), count( $tax_classes ) );
		for ( $i = 0; $i < $max; $i++ ) {
			$label_i = isset( $labels[ $i ] ) ? (string) $labels[ $i ] : '';
			if ( '' === $label_i ) {
				continue;
			}
			$price_i = isset( $prices[ $i ] ) ? (float) $prices[ $i ] : 0.0;
			$items[] = array(
				'label'     => $label_i,
				'price'     => $price_i,
				'default'   => in_array( $i, $defaults, true ) ? 1 : 0,
				'tax_class' => isset( $tax_classes[ $i ] ) ? $tax_classes[ $i ] : '',
			);
		}

		$categories = array();
		if ( isset( $_POST['topping_categories'] ) && is_array( $_POST['topping_categories'] ) && isset( $_POST['topping_categories'][ $group_type ] ) && is_array( $_POST['topping_categories'][ $group_type ] ) ) {
			$cat_ids_sanitized = array_map( 'absint', (array) wp_unslash( $_POST['topping_categories'][ $group_type ] ) );
			foreach ( $cat_ids_sanitized as $tid ) {
				if ( $tid > 0 ) {
					$categories[ $tid ] = $tid;
				}
			}
		}
		$categories = array_values( $categories );

		$record = array(
			'id'           => 'wrc_set_' . wp_generate_uuid4(),
			'group_type'   => $group_type,
			'name'         => $name,
			'label'        => $label,
			'hide_price'   => $hide_price,
			'is_required'  => $is_required,
			'checkbox_min' => $checkbox_min,
			'checkbox_max' => $checkbox_max,
			'items'        => $items,
			'categories'   => $categories,
			'created_at'   => current_time( 'mysql', true ),
			'updated_at'   => current_time( 'mysql', true ),
		);

		$sets = get_option( 'foodord_topping_sets', array() );
		if ( ! is_array( $sets ) ) {
			$sets = array();
		}
		$sets[] = $record;
		update_option( 'foodord_topping_sets', $sets, false );

		wp_safe_redirect( $this->get_page_url( array( 'saved' => '1' ) ) );
		exit;
	}

	/**
	 * Handle updating existing topping group data.
	 */
	public function handle_update_topping_group() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Insufficient permissions.', 'foodord' ) );
		}

		check_admin_referer( 'foodord_update_topping_group', '_foodord_nonce' );

		$edit_set_id = isset( $_POST['edit_set_id'] ) ? sanitize_text_field( wp_unslash( $_POST['edit_set_id'] ) ) : '';
		if ( empty( $edit_set_id ) ) {
			wp_die( esc_html__( 'Invalid set ID.', 'foodord' ) );
		}

		$allowed_types = array( 'dropdown', 'radio', 'checkbox' );
		$group_type    = isset( $_POST['selected_group_type'] ) ? sanitize_key( wp_unslash( $_POST['selected_group_type'] ) ) : 'dropdown';
		$group_type    = in_array( $group_type, $allowed_types, true ) ? $group_type : 'dropdown';

		$name  = isset( $_POST['topping_group_name'] ) ? sanitize_text_field( wp_unslash( $_POST['topping_group_name'] ) ) : '';
		$label = isset( $_POST['topping_group_label'] ) ? sanitize_text_field( wp_unslash( $_POST['topping_group_label'] ) ) : '';

		$hide_price = 0;
		if ( isset( $_POST['topping_hide_price'] ) && is_array( $_POST['topping_hide_price'] ) ) {
			$hide_price = ! empty( $_POST['topping_hide_price'][ $group_type ] ) ? 1 : 0;
		}

		$is_required = 0;
		if ( isset( $_POST['topping_required_state'] ) && is_array( $_POST['topping_required_state'] ) ) {
			$required_state = array_map( 'sanitize_text_field', (array) wp_unslash( $_POST['topping_required_state'] ) );
			if ( isset( $required_state[ $group_type ] ) ) {
				$is_required = '1' === $required_state[ $group_type ] ? 1 : 0;
			}
		}

		$checkbox_min = null;
		$checkbox_max = null;
		if ( 'checkbox' === $group_type ) {
			$checkbox_min = isset( $_POST['topping_checkbox_minimum'] ) ? absint( $_POST['topping_checkbox_minimum'] ) : null;
			$checkbox_max = isset( $_POST['topping_checkbox_maximum'] ) ? absint( $_POST['topping_checkbox_maximum'] ) : null;
		}

		$labels = array();
		if ( isset( $_POST['topping_item_label'] ) && is_array( $_POST['topping_item_label'] ) ) {
			$labels = array_map( 'sanitize_text_field', (array) wp_unslash( $_POST['topping_item_label'] ) );
		}
		$prices = array();
		if ( isset( $_POST['topping_item_price'] ) && is_array( $_POST['topping_item_price'] ) ) {
			$price_strings = array_map( 'sanitize_text_field', (array) wp_unslash( $_POST['topping_item_price'] ) );
			foreach ( $price_strings as $raw_price ) {
				$prices[] = (float) $raw_price;
			}
		}
		$tax_classes     = array();
		$raw_tax_classes = filter_input( INPUT_POST, 'topping_item_tax_class', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY );
		if ( is_array( $raw_tax_classes ) ) {
			foreach ( $raw_tax_classes as $raw_tax_class ) {
				$tax_classes[] = $this->sanitize_topping_tax_class( sanitize_text_field( $raw_tax_class ) );
			}
		}
		$defaults = array();
		if ( isset( $_POST['topping_item_default'] ) && is_array( $_POST['topping_item_default'] ) && isset( $_POST['topping_item_default'][ $group_type ] ) && is_array( $_POST['topping_item_default'][ $group_type ] ) ) {
			$defaults = array_map( 'absint', (array) wp_unslash( $_POST['topping_item_default'][ $group_type ] ) );
		}

		$items = array();
		$max   = max( count( $labels ), count( $prices ), count( $tax_classes ) );
		for ( $i = 0; $i < $max; $i++ ) {
			$label_i = isset( $labels[ $i ] ) ? (string) $labels[ $i ] : '';
			if ( '' === $label_i ) {
				continue;
			}
			$price_i = isset( $prices[ $i ] ) ? (float) $prices[ $i ] : 0.0;
			$items[] = array(
				'label'     => $label_i,
				'price'     => $price_i,
				'default'   => in_array( $i, $defaults, true ) ? 1 : 0,
				'tax_class' => isset( $tax_classes[ $i ] ) ? $tax_classes[ $i ] : '',
			);
		}

		$categories = array();
		if ( isset( $_POST['topping_categories'] ) && is_array( $_POST['topping_categories'] ) && isset( $_POST['topping_categories'][ $group_type ] ) && is_array( $_POST['topping_categories'][ $group_type ] ) ) {
			$cat_ids_sanitized = array_map( 'absint', (array) wp_unslash( $_POST['topping_categories'][ $group_type ] ) );
			foreach ( $cat_ids_sanitized as $tid ) {
				if ( $tid > 0 ) {
					$categories[ $tid ] = $tid;
				}
			}
		}
		$categories = array_values( $categories );

		// Get existing sets.
		$sets = get_option( 'foodord_topping_sets', array() );
		if ( ! is_array( $sets ) ) {
			$sets = array();
		}

		// Find and update the existing set.
		$updated = false;
		foreach ( $sets as $index => $set ) {
			if ( isset( $set['id'] ) && $set['id'] === $edit_set_id ) {
				$sets[ $index ] = array(
					'id'           => $edit_set_id,
					'group_type'   => $group_type,
					'name'         => $name,
					'label'        => $label,
					'hide_price'   => $hide_price,
					'is_required'  => $is_required,
					'checkbox_min' => $checkbox_min,
					'checkbox_max' => $checkbox_max,
					'items'        => $items,
					'categories'   => $categories,
					'created_at'   => isset( $set['created_at'] ) ? $set['created_at'] : current_time( 'mysql', true ),
					'updated_at'   => current_time( 'mysql', true ),
				);
				$updated        = true;
				break;
			}
		}

		if ( $updated ) {
			update_option( 'foodord_topping_sets', $sets, false );
			$status = 'updated';
		} else {
			$status = 'not_found';
		}

		wp_safe_redirect( $this->get_page_url( array( 'status' => $status ) ) );
		exit;
	}

	/**
	 * Handle deleting an existing topping set.
	 */
	public function handle_delete_topping_set() {
		// Check if delete action is triggered.
		if ( ! isset( $_GET['action'] ) || 'delete_topping_set' !== $_GET['action'] ) {
			return;
		}

		// Check if we're on the right page.
		$page_raw = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$page     = is_string( $page_raw ) ? sanitize_text_field( $page_raw ) : '';
		if ( ! in_array( $page, $this->get_page_slugs(), true ) ) {
			return;
		}

		// Check permissions.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Insufficient permissions.', 'foodord' ) );
		}

		// Verify nonce.
		if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'delete_topping_set' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'foodord' ) );
		}

		// Get set ID.
		$set_id = isset( $_GET['set_id'] ) ? sanitize_text_field( wp_unslash( $_GET['set_id'] ) ) : '';

		// If no set ID, redirect back.
		if ( empty( $set_id ) ) {
			wp_safe_redirect( $this->get_page_url() );
			exit;
		}

		// Get existing sets.
		$sets = get_option( 'foodord_topping_sets', array() );
		if ( ! is_array( $sets ) ) {
			$sets = array();
		}

		// Filter out the set to delete.
		$original_count = count( $sets );
		$filtered_sets  = array();

		foreach ( $sets as $set ) {
			if ( ! isset( $set['id'] ) || $set['id'] !== $set_id ) {
				$filtered_sets[] = $set;
			}
		}

		// Update option if something was deleted.
		if ( count( $filtered_sets ) !== $original_count ) {
			update_option( 'foodord_topping_sets', $filtered_sets, false );
			$deleted = '1';
		} else {
			$deleted = '0';
		}

		// Redirect back to the settings page without the action parameters.
		wp_safe_redirect( $this->get_page_url( array( 'deleted' => $deleted ) ) );
		exit;
	}

	/**
	 * Render the Topping Sets settings page.
	 */
	public function render_topping_sets_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'foodord' ) );
		}

		echo wp_kses_post( '<div class="wrap foodord-topping-sets-admin">' );
		echo wp_kses_post( '<div class="foodord-topping-sets-admin__header">' );
		echo wp_kses_post( '<h1 class="wp-heading-inline foodord-topping-sets-admin__title">' . esc_html__( 'Topping Sets', 'foodord' ) . '</h1>' );

		$saved_raw      = filter_input( INPUT_GET, 'saved', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$status_raw     = filter_input( INPUT_GET, 'status', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$deleted_raw    = filter_input( INPUT_GET, 'deleted', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$duplicated_raw = filter_input( INPUT_GET, 'duplicated', FILTER_SANITIZE_FULL_SPECIAL_CHARS );

		$has_saved   = ( null !== $saved_raw && false !== $saved_raw );
		$has_deleted = ( null !== $deleted_raw && false !== $deleted_raw );
		$status      = is_string( $status_raw ) ? sanitize_key( $status_raw ) : '';
		$duplicated  = is_string( $duplicated_raw ) ? sanitize_text_field( $duplicated_raw ) : '';

		if ( $has_saved ) {
			echo wp_kses_post( '<div class="notice notice-success is-dismissible"><p class="notice-text">' . esc_html__( 'Topping group saved successfully.', 'foodord' ) . '</p></div>' );
		}
		if ( 'updated' === $status ) {
			echo wp_kses_post( '<div class="notice notice-success is-dismissible"><p class="notice-text">' . esc_html__( 'Topping group updated successfully.', 'foodord' ) . '</p></div>' );
		}
		if ( 'not_found' === $status ) {
			echo wp_kses_post( '<div class="notice notice-error is-dismissible"><p class="notice-text">' . esc_html__( 'Topping set not found.', 'foodord' ) . '</p></div>' );
		}
		if ( $has_deleted ) {
			echo wp_kses_post( '<div class="notice notice-success is-dismissible"><p class="notice-text">' . esc_html__( 'Topping set removed.', 'foodord' ) . '</p></div>' );
		}
		if ( '1' === $duplicated ) {
			echo wp_kses_post( '<div class="notice notice-success is-dismissible"><p class="notice-text">' . esc_html__( 'Topping set duplicated.', 'foodord' ) . '</p></div>' );
		}
		echo wp_kses_post( '<p class="foodord-topping-sets-admin__subtitle">' . esc_html__( 'Review the topping sets you have created and quickly edit or delete if needed.', 'foodord' ) . '</p>' );
		echo wp_kses_post( '</div>' );
		if ( function_exists( 'foodord_admin_render_horizontal_menu' ) ) {
			foodord_admin_render_horizontal_menu();
		}

		$sets = get_option( 'foodord_topping_sets', array() );
		$sets = is_array( $sets ) ? $sets : array();

		if ( empty( $sets ) ) {
			echo wp_kses_post( '<div class="foodord-topping-sets-empty">' );
			echo wp_kses_post( '<div class="foodord-topping-sets-empty__icon">' );
			$icon_html = '<span class="dashicons dashicons-plus-alt2"></span>';
			echo wp_kses_post( $icon_html );
			echo wp_kses_post( '</div>' );
			echo wp_kses_post( '<h2 class="foodord-topping-sets-empty__title">' . esc_html__( 'Start creating your first topping set', 'foodord' ) . '</h2>' );
			echo wp_kses_post( '<p class="foodord-topping-sets-empty__description">' . esc_html__( 'Topping sets help organize your product customization options. Create dropdown, radio button, or checkbox groups for your customers to choose from.', 'foodord' ) . '</p>' );
			echo wp_kses_post( '<div class="foodord-topping-sets-empty__actions">' );
			$button_start = '<button type="button" class="button button-primary foodord-topping-sets-empty__cta" id="foodord-create-topping-set">';
			$button_icon  = '<span class="dashicons dashicons-plus-alt"></span>';
			$button_end   = '</button>';
			echo wp_kses_post( $button_start );
			echo wp_kses_post( $button_icon );
			echo esc_html__( 'Create New Topping Set', 'foodord' );
			echo wp_kses_post( $button_end );
			echo wp_kses_post( '<p class="foodord-topping-sets-empty__help">' . esc_html__( 'Need help? Check out our documentation to learn more about topping sets.', 'foodord' ) . '</p>' );
			echo wp_kses_post( '</div>' );
			echo wp_kses_post( '</div>' );
			echo wp_kses_post( '</div>' );
			return;
		}

		echo wp_kses_post( '<div class="foodord-topping-sets-list" role="table">' );
		$category_markup_allowed = array(
			'span'   => array(
				'class' => array(),
			),
			'button' => array(
				'class'           => array(),
				'type'            => array(),
				'aria-expanded'   => array(),
				'data-more-label' => array(),
				'data-less-label' => array(),
			),
		);
		echo wp_kses_post( '<div class="foodord-topping-sets-list__head" role="row">' );
		echo wp_kses_post( '<span class="foodord-topping-sets-list__heading foodord-topping-sets-list__heading--info" role="columnheader">' . esc_html__( 'Group Name', 'foodord' ) . '</span>' );
		echo wp_kses_post( '<span class="foodord-topping-sets-list__heading foodord-topping-sets-list__heading--label" role="columnheader">' . esc_html__( 'Group Label', 'foodord' ) . '</span>' );
		echo wp_kses_post( '<span class="foodord-topping-sets-list__heading foodord-topping-sets-list__heading--type" role="columnheader">' . esc_html__( 'Group type', 'foodord' ) . '</span>' );
		echo wp_kses_post( '<span class="foodord-topping-sets-list__heading foodord-topping-sets-list__heading--items" role="columnheader">' . esc_html__( 'Items', 'foodord' ) . '</span>' );
		echo wp_kses_post( '<span class="foodord-topping-sets-list__heading foodord-topping-sets-list__heading--categories" role="columnheader">' . esc_html__( 'Categories', 'foodord' ) . '</span>' );
		echo wp_kses_post( '<span class="foodord-topping-sets-list__heading foodord-topping-sets-list__heading--actions" role="columnheader">' . esc_html__( 'Actions', 'foodord' ) . '</span>' );
		echo wp_kses_post( '</div>' );
		foreach ( $sets as $set ) {
			$label      = isset( $set['label'] ) ? $set['label'] : '';
			$name       = isset( $set['name'] ) ? $set['name'] : '';
			$group_type = isset( $set['group_type'] ) ? $set['group_type'] : '';
			$items      = isset( $set['items'] ) && is_array( $set['items'] ) ? $set['items'] : array();
			$cat_ids    = isset( $set['categories'] ) && is_array( $set['categories'] ) ? $set['categories'] : array();
			$set_id     = isset( $set['id'] ) ? $set['id'] : '';

			$group_type_label = 'dropdown' === $group_type ? esc_html__( 'Dropdown', 'foodord' ) : ( 'radio' === $group_type ? esc_html__( 'Radio Buttons', 'foodord' ) : esc_html__( 'Checkboxes', 'foodord' ) );

			$cat_names = array();
			if ( ! empty( $cat_ids ) ) {
				foreach ( $cat_ids as $tid ) {
					$term = get_term( (int) $tid, 'product_cat' );
					if ( $term && ! is_wp_error( $term ) ) {
						$cat_names[] = $term->name;
					}
				}
			}

			$visible_label = $label ? $label : __( 'Untitled set', 'foodord' );
			$display_name  = $name ? $name : $visible_label;
			$display_label = $label ? $label : __( 'No group label', 'foodord' );
			$label_classes = array( 'foodord-topping-set-row__label-text' );
			if ( '' === $label ) {
				$label_classes[] = 'is-muted';
			}
			$item_count = count( $items );
			// translators: %d is the number of items in the topping set.
			$item_text_template = _n( '%d item', '%d items', $item_count, 'foodord' );
			$item_label         = esc_html( str_replace( '%d', intval( $item_count ), $item_text_template ) );
			$category_markup    = '';
			if ( ! empty( $cat_names ) ) {
				$chip_elements = array();
				foreach ( $cat_names as $index => $name ) {
					$chip_classes = array( 'foodord-topping-set-row__chip' );
					if ( $index >= 2 ) {
						$chip_classes[] = 'is-hidden';
					}
					$chip_elements[] = '<span class="' . esc_attr( implode( ' ', $chip_classes ) ) . '">' . esc_html( $name ) . '</span>';
				}

				if ( count( $chip_elements ) > 2 ) {
					$extra_count = count( $chip_elements ) - 2;
					// translators: %d is the number of additional categories not shown.
					$more_label_text  = esc_html( sprintf( _n( '+%d category', '+%d categories', $extra_count, 'foodord' ), $extra_count ) );
					$less_label_text  = esc_html__( 'Show less', 'foodord' );
					$category_markup  = implode( '', $chip_elements );
					$category_markup .= '<button type="button" class="foodord-topping-set-row__more" data-more-label="' . esc_attr( $more_label_text ) . '" data-less-label="' . esc_attr( $less_label_text ) . '" aria-expanded="false">' . $more_label_text . '</button>';
				} else {
					$category_markup = implode( '', $chip_elements );
				}
			} else {
				$category_markup = '<span class="foodord-topping-set-row__chip is-muted">' . esc_html__( 'No categories linked', 'foodord' ) . '</span>';
			}

			echo wp_kses_post( '<div class="foodord-topping-set-row" role="row">' );
				echo wp_kses_post( '<div class="foodord-topping-set-row__cell foodord-topping-set-row__cell--info" role="cell">' );
				echo wp_kses_post( '<span class="foodord-topping-set-row__title">' . esc_html( (string) $display_name ) . '</span>' );
				echo wp_kses_post( '</div>' );
				echo wp_kses_post( '<div class="foodord-topping-set-row__cell foodord-topping-set-row__cell--label" role="cell">' );
				echo wp_kses_post( '<span class="' . esc_attr( implode( ' ', $label_classes ) ) . '">' . esc_html( (string) $display_label ) . '</span>' );
				echo wp_kses_post( '</div>' );
			echo wp_kses_post( '<div class="foodord-topping-set-row__cell foodord-topping-set-row__cell--type" role="cell">' );
			echo wp_kses_post( '<span class="foodord-topping-set-row__badge">' . esc_html( $group_type_label ) . '</span>' );
			echo wp_kses_post( '</div>' );
			echo wp_kses_post( '<div class="foodord-topping-set-row__cell foodord-topping-set-row__cell--items" role="cell">' );
			echo wp_kses_post( '<span class="foodord-topping-set-row__count-label">' . esc_html( $item_label ) . '</span>' );
			if ( 'checkbox' === $group_type ) {
				$checkbox_min = isset( $set['checkbox_min'] ) ? absint( $set['checkbox_min'] ) : null;
				$checkbox_max = isset( $set['checkbox_max'] ) ? absint( $set['checkbox_max'] ) : null;
				if ( null !== $checkbox_min || null !== $checkbox_max ) {
					$range_parts = array();
					if ( null !== $checkbox_min ) {
						// translators: %d is the minimum number of checkboxes that can be selected.
						$range_parts[] = sprintf( esc_html__( 'Min %d', 'foodord' ), $checkbox_min );
					}
					if ( null !== $checkbox_max ) {
						// translators: %d is the maximum number of checkboxes that can be selected.
						$range_parts[] = sprintf( esc_html__( 'Max %d', 'foodord' ), $checkbox_max );
					}
					echo wp_kses_post( '<span class="foodord-topping-set-row__meta">' . esc_html( implode( ' · ', $range_parts ) ) . '</span>' );
				}
			}
			if ( ! empty( $set['is_required'] ) ) {
				echo wp_kses_post( '<span class="foodord-topping-set-row__meta">' . esc_html__( 'Required', 'foodord' ) . '</span>' );
			}
			if ( ! empty( $set['hide_price'] ) ) {
				echo wp_kses_post( '<span class="foodord-topping-set-row__meta is-muted">' . esc_html__( 'Pricing hidden', 'foodord' ) . '</span>' );
			}
			echo wp_kses_post( '</div>' );
			echo wp_kses_post( '<div class="foodord-topping-set-row__cell foodord-topping-set-row__cell--categories" role="cell">' );
			echo wp_kses_post( '<div class="foodord-topping-set-row__chips">' ) . wp_kses( $category_markup, $category_markup_allowed ) . wp_kses_post( '</div>' );
			echo wp_kses_post( '</div>' );
			echo wp_kses_post( '<div class="foodord-topping-set-row__cell foodord-topping-set-row__cell--actions" role="cell">' );
			echo wp_kses_post( '<div class="foodord-topping-set-row__actions">' );
			if ( '' !== $set_id ) {
				$edit_button = '<button type="button" class="button button-small foodord-edit-topping-set" data-set-id="' . esc_attr( $set_id ) . '">' . esc_html__( 'Edit', 'foodord' ) . '</button>';
				echo wp_kses_post( $edit_button );
			} else {
				$disabled_button = '<button type="button" class="button button-small" disabled="disabled">' . esc_html__( 'Edit', 'foodord' ) . '</button>';
				echo wp_kses_post( $disabled_button );
			}
			if ( '' !== $set_id ) {
				$duplicate_url  = wp_nonce_url(
					add_query_arg(
						array(
							'action' => 'duplicate_topping_set',
							'set_id' => $set_id,
						),
						$this->get_page_url()
					),
					'duplicate_topping_set'
				);
				$duplicate_link = '<a href="' . esc_url( $duplicate_url ) . '" class="button button-small foodord-duplicate-topping-set">' . esc_html__( 'Duplicate', 'foodord' ) . '</a>';
				echo wp_kses_post( $duplicate_link );
			}
			if ( '' !== $set_id ) {
				$delete_url      = wp_nonce_url(
					add_query_arg(
						array(
							'action' => 'delete_topping_set',
							'set_id' => $set_id,
						),
						$this->get_page_url()
					),
					'delete_topping_set'
				);
				$confirm_message = esc_html__( 'Are you sure you want to remove this topping set?', 'foodord' );
				$delete_link     = '<a href="' . esc_url( $delete_url ) . '" class="button button-small button-danger foodord-delete-topping-set" data-confirm="' . esc_attr( $confirm_message ) . '">' . esc_html__( 'Remove', 'foodord' ) . '</a>';
				echo wp_kses_post( $delete_link );
			}
			echo wp_kses_post( '</div>' );
			echo wp_kses_post( '</div>' );
			echo wp_kses_post( '</div>' );
		}
		echo wp_kses_post( '</div>' );

		echo wp_kses_post( '</div>' );
	}
}
