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

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

/**
 * Class Foodord_Toppings
 */
class Foodord_Toppings {
	/**
	 * Possible hook slugs for the toppings admin page.
	 *
	 * @return string[]
	 */
	private function get_page_slugs(): array {
		return function_exists( 'foodord_get_settings_page_slugs' )
			? foodord_get_settings_page_slugs( 'toppings' )
			: array( 'foodord-theme-settings-toppings', 'foodord-toppings' );
	}

	/**
	 * URL to the Topping Sets page.
	 */
	private function get_topping_sets_url(): string {
		return function_exists( 'foodord_get_admin_page_url' )
			? foodord_get_admin_page_url( 'topping_sets' )
			: admin_url( 'admin.php?page=foodord-topping-sets' );
	}

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
	}

	/**
	 * Enqueue admin scripts.
	 *
	 * @param string $hook Hook suffix.
	 */
	public function enqueue_scripts( $hook ) {
		$match = false;
		foreach ( $this->get_page_slugs() as $slug ) {
			if ( '' !== $slug && false !== strpos( (string) $hook, $slug ) ) {
				$match = true;
				break;
			}
		}

		if ( ! $match ) {
			return;
		}

		// Check if we're editing an existing set.
		$edit_set_id_raw = filter_input( INPUT_GET, 'set_id', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$edit_set_id     = is_string( $edit_set_id_raw ) ? sanitize_text_field( $edit_set_id_raw ) : '';

		$action_raw   = filter_input( INPUT_GET, 'action', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$action       = is_string( $action_raw ) ? sanitize_key( $action_raw ) : '';
		$is_edit_mode = ( 'edit' === $action ) && ( '' !== $edit_set_id );
		// Get existing data if editing.
		$existing_set = null;
		if ( $is_edit_mode ) {
			$sets = get_option( 'foodord_topping_sets', array() );
			if ( is_array( $sets ) ) {
				foreach ( $sets as $set ) {
					if ( isset( $set['id'] ) && $set['id'] === $edit_set_id ) {
						$existing_set = $set;
						break;
					}
				}
			}
		}

		// Enqueue CSS.
		wp_enqueue_style(
			'wrc-admin',
			plugin_dir_url( __DIR__ ) . 'admin/css/wrc-admin.css',
			array(),
			FOODORD_VERSION
		);

		// Enqueue JavaScript.
		wp_enqueue_script(
			'foodord-toppings',
			plugin_dir_url( __DIR__ ) . 'admin/js/foodord-toppings.js',
			array( 'jquery' ),
			FOODORD_VERSION,
			true
		);

		wp_enqueue_script(
			'foodord-topping-groups',
			plugin_dir_url( __DIR__ ) . 'admin/js/foodord-topping-groups.js',
			array( 'jquery' ),
			FOODORD_VERSION,
			true
		);

		wp_enqueue_script(
			'foodord-topping-items',
			plugin_dir_url( __DIR__ ) . 'admin/js/foodord-topping-items.js',
			array( 'jquery' ),
			FOODORD_VERSION,
			true
		);

		// Localize script for topping items.
		wp_localize_script(
			'foodord-topping-items',
			'foodordTopping',
			array(
				'labelText'    => esc_html__( 'Label', 'foodord' ),
				'priceText'    => esc_html__( 'Price', 'foodord' ),
				'taxClassText' => esc_html__( 'Tax class', 'foodord' ),
				'optionalText' => esc_html__( '(optional)', 'foodord' ),
				'taxClasses'   => Foodord_Topping_Items::get_tax_class_options(),
				'taxEnabled'   => function_exists( 'wc_tax_enabled' ) && wc_tax_enabled() ? '1' : '0',
				'defaultText'  => esc_html__( 'Mark topping as default', 'foodord' ),
				'currencyCode' => sanitize_text_field( (string) get_option( 'woocommerce_currency', '' ) ),
				'isEditMode'   => $is_edit_mode,
				'existingSet'  => $existing_set,
			)
		);
	}

	/**
	 * Render the Toppings settings page.
	 */
	public function render_toppings_page() {
		// Check if we're editing an existing set.
		$edit_set_id_raw = filter_input( INPUT_GET, 'set_id', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$edit_set_id     = is_string( $edit_set_id_raw ) ? sanitize_text_field( $edit_set_id_raw ) : '';

		$action_raw   = filter_input( INPUT_GET, 'action', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$action       = is_string( $action_raw ) ? sanitize_key( $action_raw ) : '';
		$is_edit_mode = ( 'edit' === $action ) && ( '' !== $edit_set_id );
		// Get existing data if editing.
		$existing_set = null;
		if ( $is_edit_mode ) {
			$sets = get_option( 'foodord_topping_sets', array() );
			if ( is_array( $sets ) ) {
				foreach ( $sets as $set ) {
					if ( isset( $set['id'] ) && $set['id'] === $edit_set_id ) {
						$existing_set = $set;
						break;
					}
				}
			}
			if ( ! $existing_set ) {
				// Set not found, redirect back to topping sets.
				wp_safe_redirect( $this->get_topping_sets_url() );
				exit;
			}
		}

		// Get current step from URL parameter (admin-only, no nonce needed for display).
		$step_raw     = filter_input( INPUT_GET, 'step', FILTER_SANITIZE_NUMBER_INT );
		$current_step = is_string( $step_raw ) ? absint( $step_raw ) : 0;
		if ( $current_step <= 0 ) {
			$current_step = $is_edit_mode ? 2 : 1;
		}
		$current_step = ( 1 <= $current_step && 2 >= $current_step ) ? $current_step : ( $is_edit_mode ? 2 : 1 );
		?>
		<div class="wrap foodord-toppings-wrap">
			<h1 class="page-title">
				<?php
				if ( $is_edit_mode ) {
					echo esc_html__( 'Edit Topping Group', 'foodord' );
				} else {
					echo esc_html__( 'Toppings Management', 'foodord' );
				}
				?>
			</h1>
			<?php
			if ( function_exists( 'foodord_admin_render_horizontal_menu' ) ) {
				foodord_admin_render_horizontal_menu();
			}
			?>
			<form class="foodord-toppings-form" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
				<?php wp_nonce_field( $is_edit_mode ? 'foodord_update_topping_group' : 'foodord_save_topping_group', '_foodord_nonce' ); ?>
				<input class="foodord-hidden-action" type="hidden" name="action" value="<?php echo esc_attr( $is_edit_mode ? 'foodord_update_topping_group' : 'foodord_save_topping_group' ); ?>" />
				<?php if ( $is_edit_mode ) : ?>
					<input type="hidden" name="edit_set_id" value="<?php echo esc_attr( $edit_set_id ); ?>" />
				<?php endif; ?>
				<!-- Step Indicator Container -->
				<div class="foodord-toppings-container">
					<div class="foodord-steps-indicator">
						<div class="step <?php echo esc_attr( ( 1 === $current_step ) ? 'active' : 'completed' ); ?>" data-step="1">
							<span class="step-number">1</span>
							<span class="step-title"><?php echo esc_html__( 'Select Group Type', 'foodord' ); ?></span>
						</div>
						<div class="step-divider"></div>
						<div class="step <?php echo esc_attr( ( 2 === $current_step ) ? 'active' : '' ); ?>" data-step="2">
							<span class="step-number">2</span>
							<span class="step-title"><?php echo esc_html__( 'Add Topping Items', 'foodord' ); ?></span>
						</div>
					</div>
				</div>

				<!-- Step 1: Topping Groups Container -->
				<div class="foodord-step-container <?php echo esc_attr( ( 1 !== $current_step ) ? 'step-content--hidden' : '' ); ?>" id="step-1-container">
					<div class="step-content" id="step-1-content">
						<?php
						// Render topping groups section.
						$topping_groups = new Foodord_Topping_Groups();
						$topping_groups->render_topping_groups_section( $existing_set );
						?>
					</div>
				</div>

				<!-- Step 2: Topping Items Container -->
				<div class="foodord-step-container <?php echo esc_attr( ( 2 !== $current_step ) ? 'step-content--hidden' : '' ); ?>" id="step-2-container">
					<div class="step-content" id="step-2-content">
						<?php
						// Render topping items section.
						$topping_items = new Foodord_Topping_Items();
						$topping_items->render_topping_items_section( $existing_set );
						?>
					</div>
				</div>

				<?php
				// Always render save button, JavaScript will control visibility.
				$topping_items = new Foodord_Topping_Items();
				$topping_items->render_save_button();
				?>
			</form>
		</div>
		<?php
	}
}
