<?php
/**
 * Frontend: Checkout Country/Region field visibility via WC filters.
 *
 * @package FoodOrd
 */

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

/**
 * Class Foodord_Checkout_Country_Toggle
 *
 * Controls visibility of the Country/Region fields on Checkout based on admin setting.
 */
class Foodord_Checkout_Country_Toggle {
	/**
	 * Bootstrap hooks (frontend only).
	 */
	public function init(): void {
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ), 20 );
		add_filter( 'woocommerce_checkout_fields', array( $this, 'filter_checkout_fields' ), 10, 1 );
		// WooCommerce Blocks checkout fields (React-based checkout).
		add_filter( 'woocommerce_blocks_checkout_fields', array( $this, 'filter_blocks_checkout_fields' ), 10, 1 );
	}

	/**
	 * Enqueue debug/hide helper for Blocks checkout when field is disabled.
	 */
	public function enqueue_scripts(): void {
		if ( is_admin() ) {
			return;
		}
		if ( ! function_exists( 'is_checkout' ) || ! is_checkout() ) {
			return;
		}
		$show_country = 'yes' === get_option( 'foodord_checkout_country_toggle_show', 'no' );
		if ( $show_country ) {
			return; // Nothing to do when visible.
		}
		wp_enqueue_script(
			'foodord-checkout-country-blocks-debug',
			defined( 'FOODORD_URL' ) ? FOODORD_URL . 'public/js/foodord-checkout-country-blocks.js' : plugin_dir_url( __FILE__ ) . 'js/foodord-checkout-country-blocks.js',
			array(),
			FOODORD_VERSION,
			true
		);
	}

	/**
	 * Filter WooCommerce checkout fields to show/hide Country/Region.
	 *
	 * @param array $fields Checkout fields.
	 * @return array
	 */
	public function filter_checkout_fields( array $fields ): array {
		if ( is_admin() ) {
			return $fields;
		}
		// Default: do not show country unless explicitly enabled.
		$show_country = 'yes' === get_option( 'foodord_checkout_country_toggle_show', 'no' );
		if ( ! $show_country ) {
			if ( isset( $fields['billing']['billing_country'] ) ) {
				unset( $fields['billing']['billing_country'] );
			}
			if ( isset( $fields['shipping']['shipping_country'] ) ) {
				unset( $fields['shipping']['shipping_country'] );
			}
		}
		return $fields;
	}

	/**
	 * Filter WooCommerce Blocks checkout fields to hide Country when disabled.
	 *
	 * @param array $fields Blocks checkout fields schema.
	 * @return array
	 */
	public function filter_blocks_checkout_fields( array $fields ): array {
		// Default: hide unless explicitly enabled via option.
		$show_country = 'yes' === get_option( 'foodord_checkout_country_toggle_show', 'no' );
		if ( $show_country ) {
			return $fields;
		}

		// Billing/Shipping country keys in Blocks are 'country'.
		if ( isset( $fields['billing']['country'] ) ) {
			unset( $fields['billing']['country'] );
		}
		if ( isset( $fields['shipping']['country'] ) ) {
			unset( $fields['shipping']['country'] );
		}

		return $fields;
	}
}
