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

namespace FKWCSQ\Includes\Modules\Payment\Gateways;

use FKWCSQ\Includes\Traits\Instance;
use FKWCSQ\Square;
use function get_option;
use function is_checkout;
use function __;

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

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

	/**
	 * Gateway ID.
	 *
	 * @var string
	 */
	public $id = 'fkwcsq_google_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;

	/**
	 * Create customer
	 *
	 * @var bool
	 */
	public $create_customer;

	/**
	 * Gateway enabled status
	 *
	 * @var string
	 */
	public $enabled;

	/**
	 * Gateway title
	 *
	 * @var string
	 */
	public $title;

	/**
	 * Gateway description
	 *
	 * @var string
	 */
	public $description;


	/**
	 * Button type
	 *
	 * @var string
	 */
	public $button_type;

	/**
	 * Button color
	 *
	 * @var string
	 */
	public $button_color;

	/**
	 * Constructor
	 */
	public function __construct() {

		$this->init();

		if ( null == self::$instance ) {
			$this->init_hooks();
			self::$instance = $this;
		}
	}

	public function init() {

		$this->setup_gateway_properties();
		$this->init_form_fields();
		$this->init_settings();
		$this->load_settings();
		$this->capture_method = 'automatic'; // Default capture method
	}

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

	/**
	 * Set up basic gateway properties
	 */
	public function setup_gateway_properties() {

		$this->has_fields         = false;
		$this->method_title       = __( 'Square Google Pay', 'funnelkit-payment-gateway-square-for-woocommerce' );
		$this->method_description = __( 'Accept payments using Google Pay as Express Checkout & regular payment method. <br/> <a href="https://funnelkit.com/docs/square-gateway-for-woocommerce/set-up-payment-gateways/google-pay/" target="_blank">Learn more about the requirements</a> to show Google Pay', 'funnelkit-payment-gateway-square-for-woocommerce' );
		// Ensure we have our own unique ID
		$this->key      = 'fkwcsq_google_pay';
		$this->supports = array(
			'products',
			'refunds',
			'custom_order_tables',
			'orders_cache',
			'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_google_pay' === $gateway->id && ! is_cart() ) {
					return false;
				}

				return $result;
			},
			10,
			3
		);

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

	/**
	 * Load settings from database
	 */
	public function load_settings() {
		// Load general settings
		$this->general_settings = get_option( 'fkwcsq_settings', array() );
		$this->logging_enabled  = isset( $this->general_settings['enable_logging'] ) && $this->general_settings['enable_logging'] === 'yes';
		$this->create_customer  = isset( $this->general_settings['create_customer'] ) && $this->general_settings['create_customer'] === 'yes';
		$this->title            = $this->get_option( 'title' );
		$this->description      = $this->get_option( 'description' );
		$this->enabled          = $this->get_option( 'enabled' );
	}


	/**
	 * 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 Square Google Pay', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'label'       => ' ',
				'type'        => 'checkbox',
				'description' => '',
				'default'     => 'no',
			),
			'title'                   => array(
				'title'       => __( 'Title', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'type'        => 'text',
				'description' => __( 'This controls the title which the user sees during checkout.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'default'     => __( 'Square Google Pay', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'desc_tip'    => true,
			),
			'description'             => array(
				'title'       => __( 'Description', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'type'        => 'textarea',
				'description' => __( 'This controls the description which the user sees during checkout.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'default'     => __( 'Pay securely using Google 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 Google 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' ),
				),
			),
			// Product Page Section
			'product_section'         => array(
				'title' => __( 'Google 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' ),
				),
				'default' => 'black',
			),
			'button_type'             => array(
				'title'       => __( 'Button Type', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'type'        => 'select',
				'description' => __( 'Choose the type of Google Pay button to display.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'default'     => 'buy',
				'desc_tip'    => true,
				'options'     => array(
					'buy'      => __( 'Buy', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'checkout' => __( 'Checkout', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'order'    => __( 'Order', 'funnelkit-payment-gateway-square-for-woocommerce' ),
					'pay'      => __( 'Pay', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				),
			),
			'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 Google 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 Google Pay from the regular payment methods list on checkout page. The Google Pay button will still be displayed separately.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'default'     => 'yes',
			),
		);
	}


	/**
	 * 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 ( $this->is_changing_payment_method_for_subscription() || $this->is_add_payment_method_page() ) {
			return false;
		}

		if ( \FKWCSQ\Square::cart_contains_subscription() ) {
			return false;
		}

		// Allow during WooCommerce Blocks REST API checkout (checkout display must be enabled)
		$display_locations = isset( $this->settings['display_location'] ) ? (array) $this->settings['display_location'] : array();

		if ( $this->is_rest_api_checkout_request() && in_array( 'checkout', $display_locations, true ) ) {
			return true;
		}

		// Check if current page matches any enabled display location
		if ( in_array( 'product', $display_locations, true ) && function_exists( 'is_product' ) && is_product() ) {
			return true;
		}

		if ( in_array( 'cart', $display_locations, true ) && function_exists( 'is_cart' ) && is_cart() ) {
			return true;
		}

		if ( in_array( 'checkout', $display_locations, true ) && is_checkout() ) {
			return true;
		}

		return false;
	}

	/**
	 * 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 current page is in available display locations
	 *
	 * @return bool
	 */
	public function is_available_display_location() {
		return $this->is_available();
	}

	/**
	 * Initialize action hooks
	 */
	public function init_hooks() {

		add_action( 'admin_notices', array( $this, 'admin_notices' ) );
		add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'payment_scripts' ) );
		add_filter( 'woocommerce_order_button_html', array( $this, 'print_gpay_wrapper' ) );
		add_filter( 'woocommerce_pay_order_button_html', array( $this, 'print_gpay_wrapper' ) );
		add_filter( 'fkwcsq_smart_button_localize_data', array( $this, 'get_localize_data' ) );
		$this->display_hooks();
	}

	/**
	 * Admin notices for Google Pay settings.
	 */
	public function admin_notices() {
		$this->maybe_show_block_checkout_notice();
	}

	/**
	 * Show notice when block checkout is used - Google 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_google_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. Google Pay is only available as an Express button above the checkout form.', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>
				</p>
			</div>
			<?php
		}
	}

	/**
	 * 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( 'Google 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();
	}

	/**
	 * Enqueue payment scripts and styles
	 */
	public function payment_scripts() {
		if ( ! is_checkout() ) {
			return;
		}

		if ( $this->enabled !== 'yes' ) {
			return;
		}

		// Add inline CSS for Google Pay button visibility toggle (blocks checkout).
		$inline_css = '
			/* Hide Place Order button when Google Pay is selected (blocks checkout) */
			body.fkwcsq-google-pay-selected .wc-block-components-checkout-place-order-button {
				display: none !important;
			}
		';

		// Register and enqueue inline CSS.
		wp_register_style( 'fkwcsq-google-pay-inline', false, array(), FKWCSQ_VERSION );
		wp_enqueue_style( 'fkwcsq-google-pay-inline' );
		wp_add_inline_style( 'fkwcsq-google-pay-inline', $inline_css );
	}

	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' ), 107 );
		}

		// 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' ), 15 );
		}

		// 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' ), 15 );
		}
	}

	public function get_pay_button_id() {
		return 'funnelkit-square-google-pay-button-container';
	}

	public function supported_product_types() {

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

		);
	}

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

		// Get current page type and separator text
		$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_theme = $this->get_option( 'button_theme', 'black' );
		// Escaping output for security
		echo '<div id="funnelkit-square-google-pay-button-container" class="fkwcsq_express_btn fkwcsq_gpay_' . esc_attr( $current_page ) . ' fkwcs_google_button_theme_' . esc_attr( $button_theme ) . '"><div class="fkwcsq_hidden_wrap"></div></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() && is_wc_endpoint_url( 'add-payment-method' ) ) {
			return true;
		}

		return false;
	}

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

		return 'checkout';
	}

	public function get_localize_data( $localize_data ) {

		return array_merge(
			$localize_data,
			array(
				'gpay_button_type'          => $this->get_option( 'button_type', 'buy' ),
				'gpay_button_theme'         => $this->get_option( 'button_theme', 'black' ),
				'gpay_button_size'          => 'fill',
				'gpay_hide_in_payment_list' => $this->get_option( 'hide_in_payment_list', 'yes' ),
			)
		);
	}


	/**
	 * 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 Google Pay specific nonce key.
	 *
	 * @return string
	 * @throws \Exception
	 */
	public function get_payment_nonce() {
		$payment_nonce = isset( $_POST['fkwcsq_google_pay_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['fkwcsq_google_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_gpay_wrapper( $html ) {
		if ( $this->enabled !== 'yes' ) {
			return $html;
		}

		if ( 'yes' === $this->get_option( 'hide_in_payment_list', 'yes' ) ) {
			return $html;
		}

		return $html . "<div class='funnelkit-regular-gateway-gpay-square-wrapper' style='position:relative'></div>";
	}

	public function get_icon() {

		$icon_url  = FKWCSQ_PLUGIN_URL . 'assets/images/google_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( 'Square Google Pay' ) ), esc_attr( 'funnelkit-payment-gateway-square-for-woocommerce' ) );

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