<?php
/**
 * Cart Topping Group Label toggle handler for Tweaks page.
 *
 * Note: Nonce verification is handled by the parent Tweaks class (class-foodord-tweaks.php)
 * via check_admin_referer() before calling handle_form_submission().
 *
 * @package FoodOrd
 */

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

/**
 * Handles the cart topping group label visibility toggle.
 */
class Foodord_Topping_Label_Toggle {
	/**
	 * Process form submissions for the toggle.
	 *
	 * @return bool Whether the option was updated.
	 */
	public function handle_form_submission() {
		if ( ! isset( $_POST['foodord_tweaks_submit'], $_POST['foodord_tweaks_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['foodord_tweaks_nonce'] ) ), 'foodord_tweaks_save' ) ) {
			return false;
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			return false;
		}

		$show_labels = isset( $_POST['foodord_show_topping_group_label'] ) ? 'yes' : 'no';
		$old_value   = get_option( 'foodord_show_topping_group_label', 'yes' );

		if ( $old_value !== $show_labels ) {
			update_option( 'foodord_show_topping_group_label', $show_labels );
			return true;
		}

		return false;
	}

	/**
	 * Render the Tweaks section for cart topping group labels.
	 */
	public function render_section() {
		$show_labels = get_option( 'foodord_show_topping_group_label', 'yes' );
		$checked     = ( 'yes' === $show_labels ) ? 'checked' : '';
		?>
		<div class="wrc-topping-labels-container">
			<div class="wrc-topping-labels-header">
				<h2 class="wrc-section-title"><?php echo esc_html__( 'Cart Topping Group Labels', 'foodord' ); ?></h2>
				<p class="wrc-card-sub"><?php echo esc_html__( 'Control whether topping group labels appear under cart items.', 'foodord' ); ?></p>
			</div>
			<div class="wrc-topping-labels-content">
				<div class="wrc-form" role="group" aria-label="<?php echo esc_attr__( 'Cart topping group label visibility', 'foodord' ); ?>">
					<div class="wrc-field wrc-field--toggle">
						<label class="wrc-label" for="foodord_show_topping_group_label"><?php echo esc_html__( 'Show topping group labels in cart sidebar', 'foodord' ); ?></label>
						<div class="wrc-control">
							<div class="foodord-toggle-row">
								<label class="foodord-toggle-switch" for="foodord_show_topping_group_label">
									<input type="checkbox" id="foodord_show_topping_group_label" name="foodord_show_topping_group_label" value="yes" <?php echo esc_attr( $checked ); ?> />
									<span class="foodord-toggle-slider"></span>
								</label>
								<span class="foodord-toggle-label"><?php echo esc_html__( 'Display topping group labels below cart item extras', 'foodord' ); ?></span>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<?php
	}
}
