<?php
/**
 * Apple Pay Gateway Class
 *
 * @package FunnelKit_Square
 * @subpackage Payment
 */

namespace FKWCSQ\Includes\Modules\Payment\Gateways;

use FKWCSQ\Includes\Logger;
use FKWCSQ\Includes\Traits\Instance;
use FKWCSQ\Includes\Modules\Payment\SmartButtons\SmartButtons;
use WC_Order;
use Exception;
use WP_Error;
use function get_option;
use function admin_url;
use function wp_create_nonce;
use function get_woocommerce_currency;
use function is_checkout;
use function wp_enqueue_script;
use function wp_enqueue_style;
use function wp_localize_script;
use function __;

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

/**
 * Apple Pay Class
 */
#[\AllowDynamicProperties]
class Apple_Pay extends Card {
	use Instance;

	/**
	 * Gateway ID.
	 *
	 * @var string
	 */
	public $id = 'fkwcsq_apple_pay';

	/**
	 * Has fields
	 *
	 * @var bool
	 */
	public $has_fields;

	/**
	 * Method title
	 *
	 * @var string
	 */
	public $method_title;

	/**
	 * Method description
	 *
	 * @var string
	 */
	public $method_description;

	/**
	 * Supported features
	 *
	 * @var array
	 */
	public $supports;

	/**
	 * API instance
	 *
	 * @var object
	 */
	public $api;

	/**
	 * Gateway settings
	 *
	 * @var array
	 */
	public $settings;

	/**
	 * General settings
	 *
	 * @var array
	 */
	public $general_settings;

	/**
	 * Logging enabled
	 *
	 * @var bool
	 */
	public $logging_enabled;

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->has_fields         = false;
		$this->method_title       = __( 'Square Apple Pay ', 'funnelkit-payment-gateway-square-for-woocommerce' );
		$this->method_description = __( 'Accept payments using Square Apple Pay. <br/> <a href="https://funnelkit.com/docs/square-gateway-for-woocommerce/set-up-payment-gateways/apple-pay/" target="_blank">Learn more about the requirements</a> to show Apple Pay', 'funnelkit-payment-gateway-square-for-woocommerce' );
		$this->supports           = array(
			'products',
			'refunds',
			'pay_button',
		);

		// Only support pay_button on cart page (not checkout/AeroCheckout)
		add_filter(
			'woocommerce_payment_gateway_supports',
			function ( $result, $feature, $gateway ) {
				if ( 'pay_button' === $feature && 'fkwcsq_apple_pay' === $gateway->id && ! is_cart() ) {
					return false;
				}

				return $result;
			},
			10,
			3
		);

		$this->api = \FKWCSQ\Includes\API::get_instance();

		$this->init();
	}

	/**
	 * Initialize the gateway
	 */
	public function init() {
		$this->setup_gateway_properties();
		$this->init_form_fields();
		$this->init_settings();
		if ( null == self::$instance ) {
			$this->init_hooks();
			self::$instance = $this;
		}
		$this->load_settings();
		$this->capture_method = 'automatic'; // Default capture method
	}

	/**
	 * Setup gateway properties
	 */
	public function setup_gateway_properties() {
		$this->api              = \FKWCSQ\Includes\API::get_instance();
		$this->general_settings = get_option( 'fkwcsq_square_general_settings', array() );
		$this->logging_enabled  = isset( $this->general_settings['logging'] ) ? $this->general_settings['logging'] : 'no';
	}

	/**
	 * Init settings for gateways.
	 */
	public function init_settings() {
		parent::init_settings();
		$this->enabled = ! empty( $this->settings['enabled'] ) && 'yes' === $this->settings['enabled'] ? 'yes' : 'no';
	}

	/**
	 * Initialize hooks
	 */
	public function init_hooks() {
		add_action( 'admin_notices', array( $this, 'admin_notices' ) );
		// No AJAX handlers here - they're moved to SmartButtons class
		add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
		add_filter( 'woocommerce_order_button_html', array( $this, 'print_apay_wrapper' ) );
		add_filter( 'woocommerce_pay_order_button_html', array( $this, 'print_apay_wrapper' ) );
		add_filter( 'fkwcsq_smart_button_localize_data', array( $this, 'get_localize_data' ), 11 );
		add_filter( 'body_class', array( $this, 'add_body_class_hide_in_list' ) );
		add_action( 'wp_footer', array( $this, 'print_css' ) );
		add_action( 'wp_ajax_fkwcsq_reverify_apple_pay_domain', array( $this, 'ajax_reverify_apple_pay_domain' ) );
		$this->display_hooks();
	}

	/**
	 * Load gateway settings
	 */
	public function load_settings() {
		$this->title       = $this->get_option( 'title' );
		$this->description = $this->get_option( 'description' );
		$this->enabled     = $this->get_option( 'enabled' );
	}

	/**
	 * Add body class when Apple Pay is hidden from payment list.
	 * Used by CSS to keep payment list item hidden while express button stays visible.
	 *
	 * @param array $classes Body classes.
	 * @return array
	 */
	public function add_body_class_hide_in_list( $classes ) {
		if ( 'yes' === $this->get_option( 'hide_in_payment_list' ) ) {
			$classes[] = 'fkwcsq_apple_pay_hide_in_list';
		}
		return $classes;
	}

	/**
	 * Initialize form fields
	 */
	public function init_form_fields() {
		$is_block_checkout = false;
		if ( class_exists( '\Automattic\WooCommerce\Blocks\Utils\CartCheckoutUtils' ) ) {
			$is_block_checkout = \Automattic\WooCommerce\Blocks\Utils\CartCheckoutUtils::is_checkout_block_default();
		}

		$this->form_fields = array(
			'enabled'                     => array(
				'title'       => __( 'Enable/Disable', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'type'        => 'checkbox',
				'label'       => __( 'Enable Square Apple Pay ', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'default'     => 'no',
				'desc_tip'    => true,
				'description' => __( 'Enable Apple Pay payment method.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
			),
			'title'                       => array(
				'title'       => __( 'Title', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'type'        => 'text',
				'description' => __( 'Payment method title that the customer sees during checkout.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'default'     => __( 'Square Apple Pay', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'desc_tip'    => true,
			),
			'description'                 => array(
				'title'       => __( 'Description', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'type'        => 'textarea',
				'description' => __( 'Payment method description that the customer sees during checkout.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'default'     => __( 'Pay securely using Square Apple Pay .', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'desc_tip'    => true,
			),
			'display_location'            => array(
				'title'       => __( 'Display Location', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'type'        => 'multiselect',
				'description' => __( 'Choose where to display the Apple Pay button.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'default'     => array( 'product', 'cart', 'checkout' ),
				'options'     => array(
					'product'  => __( 'Product Page', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'cart'     => __( 'Cart Page', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'checkout' => __( 'Checkout Page', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				),
				'desc_tip'    => true,
			),
			'apple_pay_domain_registered' => array(
				'title'       => __( 'Apple Pay Domain Status', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'type'        => 'apple_pay_domain_verification',
				'description' => $this->get_apple_pay_domain_status_description(),
			),
			// Button Settings
			'button_section'              => array(
				'title' => __( 'Apple Pay Button Settings', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'type'  => 'title',
			),
			'button_theme'                => array(
				'title'   => __( 'Button Theme', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'type'    => 'select',
				'options' => array(
					'black'         => __( 'Black', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'white'         => __( 'White', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'white-outline' => __( 'White Outline', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				),
				'default' => 'black',
			),
			'button_type'                 => array(
				'title'       => __( 'Button Type', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'type'        => 'select',
				'description' => __( 'Select the type of Apple Pay button to display on all pages.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'default'     => 'buy',
				'options'     => $this->get_apple_pay_button_type_options(),
				'desc_tip'    => true,
			),
			'product_button_position'     => array(
				'title'   => __( 'Product Button Position', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'type'    => 'select',
				'options' => array(
					'woocommerce_before_add_to_cart_button' => __( 'Before Add to Cart Button', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'woocommerce_after_add_to_cart_button' => __( 'After Add to Cart Button', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				),
				'default' => 'woocommerce_after_add_to_cart_button',
			),
			'separator_text'              => array(
				'title'       => __( 'Separator Text', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'type'        => 'text',
				'description' => __( 'Text to display between Apple Pay button and other elements.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'default'     => 'OR',
			),
			// General Settings Section
			'general_section'             => array(
				'title' => __( 'General Settings', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'type'  => 'title',
			),
			'hide_in_payment_list'        => array(
				'title'       => __( 'Hide in Regular Payment Gateway List', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'type'        => $is_block_checkout ? 'hide_in_payment_list_block' : 'checkbox',
				'label'       => __( 'Hide in Regular Payment Gateway List', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'description' => __( 'Check this to hide Apple Pay from the regular payment methods list on checkout page. The Apple Pay button will still be displayed separately.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'default'     => 'yes',
			),
		);
	}

	/**
	 * Get Apple Pay button type options
	 */
	private function get_apple_pay_button_type_options() {
		return array(
			'plain'     => __( 'Plain', 'funnelkit-payment-gateway-square-for-woocommerce' ),
			'buy'       => __( 'Buy', 'funnelkit-payment-gateway-square-for-woocommerce' ),
			'check-out' => __( 'Checkout', 'funnelkit-payment-gateway-square-for-woocommerce' ),
			'book'      => __( 'Book', 'funnelkit-payment-gateway-square-for-woocommerce' ),
			'order'     => __( 'Order', 'funnelkit-payment-gateway-square-for-woocommerce' ),
			'rent'      => __( 'Rent', 'funnelkit-payment-gateway-square-for-woocommerce' ),
			'setup'     => __( 'Setup', 'funnelkit-payment-gateway-square-for-woocommerce' ),
			'subscribe' => __( 'Subscribe', 'funnelkit-payment-gateway-square-for-woocommerce' ),
			'support'   => __( 'Support', 'funnelkit-payment-gateway-square-for-woocommerce' ),
			'tip'       => __( 'Tip', 'funnelkit-payment-gateway-square-for-woocommerce' ),
			'topup'     => __( 'Top Up', 'funnelkit-payment-gateway-square-for-woocommerce' ),
		);
	}

	/**
	 * Get Apple Pay domain status description
	 */
	private function get_apple_pay_domain_status_description() {
		if ( ! is_admin() ) {
			return;
		}
		$domain_status = get_option( 'fkwcsq_apple_pay_domain_registered', 'no' );

		if ( 'yes' === $domain_status ) {
			return '<span style="color: #28a745;">✅ Domain verified with Apple Pay</span>';
		} else {
			$verification_file_location = $this->apple_pay_verification_file_location();

			$file_exists = ! empty( $verification_file_location ) && file_exists( $verification_file_location );

			if ( ! $file_exists ) {
				return '<span style="color: #dc3545;">❌ Domain verification file missing</span><br><small>Expected location: <code>' . esc_html( $verification_file_location ) . '</code></small>';
			} else {
				return '<span style="color: #ffc107;">⚠️ Domain not yet verified with Square/Apple Pay</span><br><small>Click "Save changes" to attempt domain registration</small>';
			}
		}
	}

	/**
	 * Get Apple Pay verification file location
	 */
	public function apple_pay_verification_file_location() {
		return $this->get_well_known_file_path();
	}

	/**
	 * Check for Apple Pay verification domain file
	 */
	public function check_apple_pay_verification_file() {
		if ( empty( $_SERVER['DOCUMENT_ROOT'] ) ) {
			return false;
		}

		$path              = untrailingslashit( sanitize_text_field( wp_unslash( $_SERVER['DOCUMENT_ROOT'] ) ) );
		$dir               = '.well-known';
		$file              = 'apple-developer-merchantid-domain-association';
		$fullpath          = $path . '/' . $dir . '/' . $file;
		$plugin_path       = plugin_dir_path( __FILE__ );
		$source_file       = $plugin_path . '/apple-pay/apple-developer-merchantid-domain-association';
		$existing_contents = @file_get_contents( $fullpath );
		$new_contents      = @file_get_contents( $source_file );

		if ( $existing_contents && $new_contents && $existing_contents === $new_contents ) {
			return true;
		}

		return false;
	}

	/**
	 * Move domain association file to .well-known folder
	 */
	private function move_domain_association_file() {
		if ( empty( $_SERVER['DOCUMENT_ROOT'] ) ) {

			return false;
		}

		// Resolve and validate DOCUMENT_ROOT BEFORE any filesystem write. On shared or
		// misconfigured hosting DOCUMENT_ROOT could be unexpected, so require it to
		// resolve (realpath) to a real, existing directory and fail closed otherwise.
		// The path segments appended below are fixed literals with no user input, so
		// once the root is a verified real directory the target cannot traverse out of it.
		$server_root = realpath( untrailingslashit( sanitize_text_field( wp_unslash( $_SERVER['DOCUMENT_ROOT'] ) ) ) );
		if ( false === $server_root || ! is_dir( $server_root ) ) {
			Logger::error( 'Apple Pay: DOCUMENT_ROOT did not resolve to a valid directory; aborting domain association file write.' );
			return false;
		}

		$well_known_dir = $server_root . '/.well-known';
		$target_file    = $well_known_dir . '/apple-developer-merchantid-domain-association';

		// Get plugin root path
		$plugin_path = plugin_dir_path( __FILE__ );
		$source_file = $plugin_path . '/apple-pay/apple-developer-merchantid-domain-association';

		// Check if source file exists
		if ( ! file_exists( $source_file ) ) {

			return false;
		}

		// Create .well-known directory if it doesn't exist
		if ( ! is_dir( $well_known_dir ) ) {
			if ( ! mkdir( $well_known_dir, 0755, true ) ) { //phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_mkdir -- Creating .well-known directory for Apple Pay domain verification, standard web directory
				Logger::error( 'Apple Pay: failed to create .well-known directory: ' . $well_known_dir );
				return false;
			}
		}

		// Defense in depth: after the directory exists, ensure its fully-resolved path is
		// still contained within DOCUMENT_ROOT (guards against a symlink planted at
		// /.well-known). Compare with a trailing separator so a sibling like
		// "<root>-evil" cannot satisfy a bare prefix match. Fail closed if it does not
		// resolve.
		$real_well_known = realpath( $well_known_dir );
		if ( false === $real_well_known || 0 !== strpos( $real_well_known . DIRECTORY_SEPARATOR, $server_root . DIRECTORY_SEPARATOR ) ) {
			Logger::error( 'Apple Pay: .well-known directory resolved outside DOCUMENT_ROOT; aborting domain association file write.' );
			return false;
		}

		// Check if target file already exists and has same content
		if ( file_exists( $target_file ) ) {
			$source_content = file_get_contents( $source_file ); //phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Reading local plugin file for comparison
			$target_content = file_get_contents( $target_file ); //phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Reading local web-root file for comparison

			if ( false !== $source_content && false !== $target_content && $source_content === $target_content ) {

				return true;
			}
		}

		// Copy the file
		if ( ! copy( $source_file, $target_file ) ) { //phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_copy -- Copying domain association file for Apple Pay
			Logger::error( 'Apple Pay: failed to copy domain association file to ' . $target_file );
			return false;
		}

		// Set proper permissions
		if ( ! chmod( $target_file, 0644 ) ) { //phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod -- Setting permissions for Apple Pay domain verification file
			Logger::error( 'Apple Pay: failed to set permissions on domain association file.' );
		}

		// Verify the file was copied successfully
		if ( ! file_exists( $target_file ) ) {

			return false;
		}

		return true;
	}

	/**
	 * Get the path to the domain association file in .well-known folder
	 */
	public function get_well_known_file_path() {
		if ( empty( $_SERVER['DOCUMENT_ROOT'] ) ) {
			return '';
		}

		$server_root = untrailingslashit( sanitize_text_field( wp_unslash( $_SERVER['DOCUMENT_ROOT'] ) ) );

		return $server_root . '/.well-known/apple-developer-merchantid-domain-association';
	}


	/**
	 * Register Apple Pay domain with Square
	 */
	private function register_apple_pay_domain() {

		$is_sandbox = \FKWCSQ\Square::is_sandbox_mode();
		$token      = \FKWCSQ\Square::get_tokens();

		$access_token = ! empty( $token['access_token'] ) ? $token['access_token'] : '';
		$domain_name  = ! empty( $_SERVER['HTTP_HOST'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : '';

		$this->update_option( 'apple_pay_domain_registration_attempted', 'yes' );

		if ( empty( $domain_name ) ) {
			throw new Exception( 'Unable to verify domain with Apple Pay - no domain found in $_SERVER[\'HTTP_HOST\'].' );
		}

		if ( empty( $access_token ) ) {
			throw new Exception( esc_html__( 'Unable to verify domain with Apple Pay - missing access token.', 'funnelkit-payment-gateway-square-for-woocommerce' ) );
		}

		$response = wp_remote_post(
			'https://connect.squareup' . ( $is_sandbox ? 'sandbox' : '' ) . '.com/v2/apple-pay/domains',
			array(
				'headers' => array(
					'Square-Version' => '2020-10-28',
					'Authorization'  => 'Bearer ' . $access_token,
					'Content-Type'   => 'application/json',
				),
				'body'    => wp_json_encode(
					array(
						'domain_name' => $domain_name,
					)
				),
			)
		);

		if ( is_wp_error( $response ) ) {
			throw new Exception( sprintf( 'Unable to verify domain %s - %s', esc_html( $domain_name ), esc_html( $response->get_error_message() ) ) );
		}

		$parsed_response = json_decode( $response['body'], true );

		if ( 200 !== $response['response']['code'] || empty( $parsed_response['status'] ) || 'VERIFIED' !== $parsed_response['status'] ) {
			Logger::error( sprintf( 'Apple Pay domain verification failed for %s — response: %s', $domain_name, wp_json_encode( $parsed_response ) ) );
			throw new Exception( sprintf( 'Unable to verify domain %s with Apple Pay.', esc_html( $domain_name ) ) );
		}
		\update_option( 'fkwcsq_apple_pay_domain_registered', 'yes' );
	}

	/**
	 * Process admin options and attempt domain registration
	 */
	public function process_admin_options() {
		parent::process_admin_options();
		// Attempt Apple Pay domain registration if enabled
		if ( 'yes' === $this->get_option( 'enabled', 'no' ) ) {
			try {
				$is_registered = \get_option( 'fkwcsq_apple_pay_domain_registered', 'no' );
				$this->move_domain_association_file();
				if ( $this->check_apple_pay_verification_file() ) {

					if ( ( 'no' === $is_registered || empty( $is_registered ) ) ) {
						$this->register_apple_pay_domain();
					}

					return;
				}
			} catch ( Exception $e ) {
				update_option( 'fkwcsq_apple_pay_domain_registered', 'no' );
			}
		}
	}

	/**
	 * Add admin notices for Apple Pay domain verification
	 */
	public function admin_notices() {
		$this->maybe_show_block_checkout_notice();

		if ( 'yes' === $this->get_option( 'enabled', 'no' ) ) {
			$apple_pay_verification_file_location = $this->apple_pay_verification_file_location();

			// Verification file is missing
			if ( ! empty( $apple_pay_verification_file_location ) && ! file_exists( $apple_pay_verification_file_location ) ) {
				?>
				<div class="notice notice-warning is-dismissible">
					<p>
						<strong>Apple Pay Domain Verification Required:</strong>
						We cannot confirm the Apple Pay domain verification file is at the expected location:
						<code><?php echo esc_html( $apple_pay_verification_file_location ); ?></code>
					</p>
					<p>
						<strong>Solution:</strong> Click "Save changes" in the Apple Pay gateway settings to automatically create the verification file.
					</p>
				</div>
				<?php
			} elseif ( 'no' === get_option( 'fkwcsq_apple_pay_domain_registered', '' ) && 'yes' === $this->get_option( 'apple_pay_domain_registration_attempted', 'no' ) ) {
				// Domain failed to register
				?>
				<div class="notice notice-warning is-dismissible">
					<p>
						<strong>Apple Pay Domain Registration Failed:</strong>
						There was a problem registering your store domain with Square/Apple Pay.
					</p>
					<p>
						<strong>Check:</strong> Ensure your Square access token is valid and you have the necessary permissions.
					</p>
				</div>
				<?php
			}
		}
	}

	/**
	 * Show notice when block checkout is used - Apple Pay is Express only.
	 */
	protected function maybe_show_block_checkout_notice() {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading page context for notice display
		$current_section = isset( $_GET['section'] ) ? sanitize_text_field( wp_unslash( $_GET['section'] ) ) : '';
		if ( 'fkwcsq_apple_pay' !== $current_section ) {
			return;
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading page context for notice display
		$current_tab = isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : '';
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading page context for notice display
		$current_page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
		if ( 'checkout' !== $current_tab || 'wc-settings' !== $current_page ) {
			return;
		}

		$is_block_checkout = false;
		if ( class_exists( '\Automattic\WooCommerce\Blocks\Utils\CartCheckoutUtils' ) ) {
			$is_block_checkout = \Automattic\WooCommerce\Blocks\Utils\CartCheckoutUtils::is_checkout_block_default();
		}

		if ( $is_block_checkout ) {
			?>
			<div class="notice notice-info">
				<p>
					<strong><?php esc_html_e( 'Block Checkout Detected:', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?></strong>
					<?php esc_html_e( 'Your store uses the WooCommerce Block Checkout. Apple Pay is only available as an Express button above the checkout form.', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>
				</p>
			</div>
			<?php
		}
	}

	/**
	 * Check if gateway is available for payment
	 *
	 * @return bool
	 */
	public function is_available() {
		// First check if gateway is enabled
		if ( $this->enabled !== 'yes' ) {
			return false;
		}

		// Check if Square connection is established
		if ( ! \FKWCSQ\Square::is_configured() ) {
			return false;
		}

		// Exclude pay for order page and add payment method page
		if ( isset( $_GET['change_payment_method'] ) || $this->is_add_payment_method_page() ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading page context, not processing form data
			return false;
		}
		if ( \FKWCSQ\Square::cart_contains_subscription() ) {
			return false;
		}
		// Check if current page matches any enabled display location
		if ( ! isset( $this->settings['display_location'] ) ) {
			return false;
		}

		$display_locations = $this->settings['display_location'];

		if ( ! is_array( $display_locations ) ) {
			$display_locations = array( $display_locations );
		}

		// Allow during WooCommerce Blocks REST API checkout (checkout display must be enabled)
		if ( $this->is_rest_api_checkout_request() && in_array( 'checkout', $display_locations, true ) ) {
			return true;
		}

		$current_page = $this->get_current_page_type();

		return in_array( $current_page, $display_locations, true );
	}

	/**
	 * Check if this is a WooCommerce Blocks REST API checkout request
	 *
	 * @return bool
	 */
	private function is_rest_api_checkout_request() {
		// Check if this is a REST request
		if ( ! defined( 'REST_REQUEST' ) || ! REST_REQUEST ) {
			return false;
		}

		// Check if it's a WooCommerce Store API checkout request
		if ( isset( $_SERVER['REQUEST_URI'] ) ) {
			$request_uri = sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) );
			if ( strpos( $request_uri, '/wc/store/v1/checkout' ) !== false ||
				strpos( $request_uri, '/wc/store/checkout' ) !== false ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Check if gateway should be available for current display location
	 */
	public function is_available_display_location() {
		return $this->is_available();
	}


	/**
	 * Display hooks
	 */
	function display_hooks() {

		// Product page button rendering based on settings
		if ( isset( $this->settings['display_location'] ) && in_array( 'product', (array) $this->settings['display_location'], true ) ) {
			$position = isset( $this->settings['product_button_position'] ) ? $this->settings['product_button_position'] : 'woocommerce_after_add_to_cart_button';
			add_action( $position, array( $this, 'render_button' ), 106 );
		}

		// Cart page button rendering based on settings
		if ( isset( $this->settings['display_location'] ) && in_array( 'cart', (array) $this->settings['display_location'], true ) ) {
			add_action( 'fkwcsq_smart_button_cart_wrapper', array( $this, 'render_button' ), 14 );
		}

		// Checkout page button rendering based on settings
		if ( isset( $this->settings['display_location'] ) && in_array( 'checkout', (array) $this->settings['display_location'], true ) ) {
			$position = 'fkwcsq_smart_button_wrapper';
			add_action( $position, array( $this, 'render_button' ), 14 );
		}
	}


	/**
	 * Get pay button ID
	 */
	public function get_pay_button_id() {
		return 'funnelkit-square-apple-pay-button-container';
	}
	public function supported_product_types() {

		return array(
			'simple',
			'variable',
			'variation',
			'booking',
			'bundle',
			'composite',

		);
	}
	/**
	 * Render Apple Pay button
	 */
	public function render_button() {
		// Don't render if gateway is not enabled
		if ( $this->enabled !== 'yes' ) {
			return;
		}

		$current_page = $this->get_current_page_type();

		if ( 'product' === $current_page ) {
			global $product;
			if ( ! in_array( $product->get_type(), $this->supported_product_types(), true ) || \FKWCSQ\Square::product_has_sublium_plan( $product ) ) {
				return false;
			}
		} elseif ( \FKWCSQ\Square::cart_contains_subscription() ) {
			return;
		}
		$button_id = $this->get_pay_button_id();
		$class_name        = 'fkwcsq_apay_' . $current_page;

		echo '<div id="' . esc_attr( $button_id ) . '" class="fkwcsq_express_btn fkwcsq_apply_pay_parent ' . esc_attr( $class_name ) . '" style="display:none">';
		echo '<div class="fkwcsq_apple_button"></div>';
		echo '</div>';
	}

	/**
	 * Check if current page is add payment method page
	 *
	 * @return bool
	 */
	private function is_add_payment_method_page() {
		global $wp;

		// Check if we're on the add payment method page
		if ( isset( $wp->query_vars['add-payment-method'] ) ) {
			return true;
		}

		// Alternative check for add payment method page
		if ( function_exists( 'is_account_page' ) && is_account_page() && isset( $_GET['add-payment-method'] ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading page context, not processing form data
			return true;
		}

		return false;
	}

	/**
	 * Get current page type
	 */
	private function get_current_page_type() {
		if ( is_product() ) {
			return 'product';
		} elseif ( is_cart() ) {
			return 'cart';
		} elseif ( is_checkout() ) {
			return 'checkout';
		}

		return 'checkout';
	}

	/**
	 * Generate dynamic CSS for Apple Pay buttons based on gateway settings
	 */
	private function generate_apple_pay_dynamic_css() {
		if ( ! $this->is_available_display_location() ) {
			return '';
		}
		$css = '';

		// Unified button settings for all pages — whitelist to prevent CSS injection.
		// Derive the allowed values from the settings option lists themselves so the
		// whitelist can never drift from the selectable options (which silently
		// coerced valid choices like "rent"/"setup"/"tip" to "buy" when the lists
		// diverged). All option keys are fixed [a-z-] literals, so they are safe to
		// interpolate into CSS.
		$allowed_themes = array( 'black', 'white', 'white-outline' );
		$allowed_types  = array_keys( $this->get_apple_pay_button_type_options() );

		$button_theme = $this->get_option( 'button_theme' );
		$button_theme = in_array( $button_theme, $allowed_themes, true ) ? $button_theme : 'black';

		$button_type = $this->get_option( 'button_type' );
		$button_type = in_array( $button_type, $allowed_types, true ) ? $button_type : 'buy';

		// Apply same styling to all page types
		$css .= "
		.woocommerce-checkout-payment .funnelkit-apple-pay-wrapper{
		display:none;
		}
		.fkwcsq_apply_pay_parent .fkwcsq_apple_button,.funnelkit-apple-pay-wrapper{
			height: 40px;
			width: 100%;
			display: inline-block;
			-webkit-appearance: -apple-pay-button;
			-apple-pay-button-type: {$button_type};
			-apple-pay-button-style: {$button_theme};
	}";

		return $css;
	}




	/**
	 * Get localized data for JavaScript
	 */
	public function get_localize_data( $localize_data = array() ) {
		WC()->cart->calculate_totals();

		return array_merge(
			$localize_data,
			array(
				'apple_hide_in_payment_list' => $this->get_option( 'hide_in_payment_list' ),
				'product_data'               => $this->get_product_data(),
			)
		);
	}

	public function get_product_data() {

		if ( ! is_product() ) {
			return array();
		}

		global $product;
		$product = wc_get_product( get_the_ID() );
		if ( ! $product instanceof \WC_Product ) {
			return array();
		}

		$data = array(
			'requestShippingContact' => $product->needs_shipping() ? 'yes' : 'no',
			'amount'                 => $product->get_price(),
		);
		if ( $data['requestShippingContact'] ) {
			$data['shippingOptions'] = array(
				array(
					'id'      => '0',
					'label'   => __( 'Pending', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'amount'  => '0.00',
					'pending' => false,
				),
			);
		}

		return $data;
	}


	/**
	 * Payment fields
	 */
	public function payment_fields() {
		if ( $this->description ) {
			echo wp_kses_post( wpautop( $this->description ) );
		}
	}

	/**
	 * Get payment nonce from POST data
	 *
	 * Override parent method to use Apple Pay specific nonce key.
	 *
	 * @return string
	 * @throws \Exception
	 */
	public function get_payment_nonce() {
		$payment_nonce = isset( $_POST['fkwcsq_apple_pay_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['fkwcsq_apple_pay_nonce'] ) ) : ''; //phpcs:ignore WordPress.Security.NonceVerification.Missing, FKWCS.CodeAnalysis.FKWCSSpecific.MissingCapabilityCheck -- WooCommerce handles nonce verification for checkout, guest users allowed

		if ( empty( $payment_nonce ) ) {
			throw new \Exception( esc_html__( 'Payment nonce is missing. Please try again.', 'funnelkit-payment-gateway-square-for-woocommerce' ) );
		}

		return $payment_nonce;
	}

	public function print_css() {
		echo '<style>' . wp_kses_post( $this->generate_apple_pay_dynamic_css() ) . '</style>';
	}

	/**
	 * Print Apple Pay wrapper
	 */
	public function print_apay_wrapper( $html ) {
		if ( $this->enabled !== 'yes' ) {
			return $html;
		}

		return $html . '<div class="funnelkit-apple-pay-wrapper"></div>';
	}

	public function get_icon() {

		$icon_url  = FKWCSQ_PLUGIN_URL . 'assets/images/apple_pay.svg';
		$icon_html = sprintf( '<img src="%s" alt="%s" class="sv-wc-payment-gateway-icon wc-%s-payment-gateway-icon"  />', esc_url( $icon_url ), esc_attr( ucfirst( 'Apply Pay' ) ), esc_attr( 'funnelkit-payment-gateway-square-for-woocommerce' ) );

		return apply_filters( 'woocommerce_gateway_icon', $icon_html, $this->id );
	}

	/**
	 * Generate hide_in_payment_list_block field - disabled checkbox (always yes) + red notice.
	 *
	 * @param string $key Field key.
	 * @param array  $data Field data.
	 * @return string
	 */
	public function generate_hide_in_payment_list_block_html( $key, $data ) {
		$field_key = $this->get_field_key( $key );
		$defaults  = array(
			'title'       => '',
			'label'       => '',
			'description' => '',
		);
		$data      = wp_parse_args( $data, $defaults );
		$label     = $data['label'] ? $data['label'] : $data['title'];

		ob_start();
		?>
		<tr valign="top">
			<th scope="row" class="titledesc">
				<label for="<?php echo esc_attr( $field_key ); ?>"><?php echo wp_kses_post( $data['title'] ); ?></label>
			</th>
			<td class="forminp">
				<fieldset>
					<legend class="screen-reader-text"><span><?php echo wp_kses_post( $data['title'] ); ?></span></legend>
					<input type="hidden" name="<?php echo esc_attr( $field_key ); ?>" value="yes" />
					<label for="<?php echo esc_attr( $field_key ); ?>">
						<input class="" type="checkbox" name="<?php echo esc_attr( $field_key ); ?>_display" id="<?php echo esc_attr( $field_key ); ?>" value="1" checked="checked" disabled="disabled" />
						<?php echo wp_kses_post( $label ); ?>
					</label>
					<p class="description"><?php echo wp_kses_post( $data['description'] ); ?></p>
					<div class="notice notice-error inline" style="margin: 10px 0 0 0; padding: 10px; border-left-color: #d63638;">
						<p style="margin: 0; color: #d63638;">
							<strong><?php esc_html_e( 'Block Checkout:', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?></strong>
							<?php esc_html_e( 'Apple Pay is only available as an Express button above the checkout form. This setting cannot be changed.', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>
						</p>
					</div>
				</fieldset>
			</td>
		</tr>
		<?php
		return ob_get_clean();
	}

	/**
	 * Generate custom field for Apple Pay domain verification
	 */
	public function generate_apple_pay_domain_verification_html( $key, $data ) {
		$field_key = $this->get_field_key( $key );
		$status    = $this->get_apple_pay_domain_status_description();

		ob_start();
		?>
		<tr valign="top">
			<th scope="row" class="titledesc">
				<label for="<?php echo esc_attr( $field_key ); ?>"><?php echo esc_html( $data['title'] ); ?></label>
			</th>
			<td class="forminp forminp-<?php echo esc_attr( sanitize_title( $data['type'] ) ); ?>">
				<button type="button" id="fkwcsq-reverify-apple-pay-domain" class="button button-secondary">
					<?php esc_html_e( 'Reverify Domain', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>
				</button>
				<div id="fkwcsq-apple-pay-domain-status" class="fkwcsq-domain-status">
					<?php echo wp_kses_post( $status ); ?>
				</div>
			</td>
		</tr>
		<?php
		return ob_get_clean();
	}

	/**
	 * AJAX handler for reverifying Apple Pay domain
	 */
	public function ajax_reverify_apple_pay_domain() {
		// Check user permissions first
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'You do not have permission to perform this action.', 'funnelkit-payment-gateway-square-for-woocommerce' ) );
		}

		// Verify nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'fkwcsq_reverify_apple_pay_domain' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'funnelkit-payment-gateway-square-for-woocommerce' ) );
		}

		try {
			// Move verification file first
			$this->move_domain_association_file();

			// Check if verification file exists
			if ( ! $this->check_apple_pay_verification_file() ) {
				wp_send_json_error( array( 'message' => esc_html__( 'Domain verification file is missing. Please check file permissions.', 'funnelkit-payment-gateway-square-for-woocommerce' ) ) );
				return;
			}

			// Attempt domain registration
			$this->register_apple_pay_domain();

			wp_send_json_success( array( 'message' => esc_html__( 'Domain verified with Apple Pay successfully!', 'funnelkit-payment-gateway-square-for-woocommerce' ) ) );

		} catch ( Exception $e ) {
			update_option( 'fkwcsq_apple_pay_domain_registered', 'no' );
			wp_send_json_error( array( 'message' => esc_html__( 'Apple Pay domain verification Failed', 'funnelkit-payment-gateway-square-for-woocommerce' ) ) );
		}
	}
}
