<?php

namespace FKWCS\Gateway\Stripe;

class GooglePay extends CreditCard {

	use Funnelkit_Stripe_Smart_Buttons;

	private static $instance = null;
	public $id = 'fkwcs_stripe_google_pay';
	public $payment_method_types = 'card';
	public $merchant_id = '';
	public $merchant_name = '';
	public $btn_color = 'black';
	public $btn_theme = 'pay';
	private static $mini_cart_wrapper_rendered = false;

	public static function get_instance() {
		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	public function __construct() {
		/**
		 * Validate if its setup correctly
		 */
		$this->set_api_keys();

		$this->init_supports();
		$this->init();
		if ( false === $this->is_configured() ) {
			return;
		}
		add_action( 'wc_ajax_fkwcs_gpay_update_shipping_address', [ $this, 'gpay_update_shipping_address' ] );
		add_filter( 'woocommerce_update_order_review_fragments', [ $this, 'add_google_pay_data' ], 100 );
		add_filter( 'woocommerce_add_to_cart_fragments', [ $this, 'add_google_pay_data' ], 100 );
		add_filter( 'fkcart_fragments', [ $this, 'add_google_pay_data' ], 1000 );
		add_action( 'wc_ajax_fkwcs_gpay_add_to_cart', [ $this, 'ajax_add_to_cart' ] );
		add_action( 'wc_ajax_fkwcs_gpay_button_payment_request', [ $this, 'process_smart_checkout' ] );
		add_action( 'fkcart_before_checkout_button', [ $this, 'add_mini_cart_wrapper' ] );


	}

	public function is_available() {
		/**
		 * if the mode is live and merchant ID is not present mark the gateway as not available
		 */
		if ( 'test' !== $this->test_mode && empty( $this->merchant_id ) ) {
			return false;
		}


		return parent::is_available(); // TODO: Change the autogenerated stub
	}

	/**
	 * Returns all supported currencies for this payment method
	 *
	 * @return mixed|null
	 */
	public function get_supported_currency() {
		return apply_filters( 'fkwcs_stripe_google_pay_supported_currencies', [
			"USD", // United States Dollar
			"EUR", // Euro
			"GBP", // British Pound
			"AUD", // Australian Dollar
			"CAD", // Canadian Dollar
			"CHF", // Swiss Franc
			"DKK", // Danish Krone
			"HKD", // Hong Kong Dollar
			"JPY", // Japanese Yen
			"NZD", // New Zealand Dollar
			"NOK", // Norwegian Krone
			"SGD", // Singapore Dollar
			"SEK", // Swedish Krona
			"INR", // Indian Rupee
			"BRL", // Brazilian Real
			"MXN", // Mexican Peso
			"PLN", // Polish Złoty
			"ZAR", // South African Rand
			"KRW", // South Korean Won
			"THB"  // Thai Baht
		] );
	}


	/**
	 * Registers supported filters for payment gateway
	 *
	 * @return void
	 */
	public function init_supports() {
		$this->supports = apply_filters( 'fkwcs_card_payment_supports', array_merge( $this->supports, [
			'products',
			'refunds',
			'tokenization',
			'add_payment_method',
		] ) );
	}

	protected function init() {
		$this->has_fields = true;
		$this->init_form_fields();
		$this->init_settings();
		$this->maybe_init_subscriptions();
		$this->method_title         = __( 'Google Pay', 'funnelkit-stripe-woo-payment-gateway' );
		$this->method_description   = __( 'Enable Google Pay as an inline payment gateway.', 'funnelkit-stripe-woo-payment-gateway' );
		$this->subtitle             = __( 'Google Pay allows customers to make payments in your app or website using any credit or debit card saved to their Google Account, including those from Google Play, YouTube, Chrome, or an Android device.', 'funnelkit-stripe-woo-payment-gateway' );
		$this->title                = $this->get_option( 'title' );
		$this->description          = $this->get_option( 'description' );
		$this->merchant_name        = $this->get_option( 'merchant_name' );
		$this->merchant_id          = $this->get_option( 'merchant_id' );
		$this->description          = $this->get_option( 'description' );
		$this->statement_descriptor = $this->get_option( 'statement_descriptor' );
		$this->btn_color            = $this->get_option( 'button_color' );
		$this->btn_theme            = $this->get_option( 'button_theme' );

		$this->capture_method = $this->get_option( 'charge_type' );
		if ( false === $this->is_configured() ) {
			return;
		}
		add_action( 'wp_enqueue_scripts', [ $this, 'register_stripe_js' ] );
		add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_stripe_js' ], 11 );
		add_filter( 'fkwcs_localized_data', [ $this, 'localize_element_data' ], 999 );
		$this->filter_hooks();

	}


	/**
	 * Add hooks
	 *
	 * @return void
	 */
	protected function filter_hooks() {
		add_filter( 'woocommerce_payment_successful_result', [ $this, 'modify_successful_payment_result' ], 999, 2 );
		add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, [ $this, 'process_admin_options' ] );
	}

	public function get_method_description() {


		$gpay_console_url     = esc_url( 'https://pay.google.com/business/console' );
		$testing_gpay_url     = esc_url( 'https://funnelkit.com/woocommerce-google-pay/#How_to_Set_Up_WooCommerce_Enhanced_Google_Pay_Integration_Google_Merchant_ID_Creation_and_Integration_Submission_for_Approval' );
		$express_checkout_url = esc_url( admin_url( 'admin.php?page=wc-settings&tab=checkout&section=fkwcs_express_checkout' ) );
		$get_details_url      = 'https://funnelkit.com/woocommerce-google-pay/#How_to_Enable_the_WooCommerce_Google_Pay_Payment_Gateway';
		$description          = $this->method_description;
		$description          .= sprintf( __( '<p>Want to enhance the Google Pay button visibility irrespective of customer\'s device and browser? Follow these steps to integrate:</p>
        <strong>Step 1:</strong> Register for a Google Pay Business Profile Start by setting up your <a target="_blank" href="%1$s">Google Pay business account</a><br/>
        <strong>Step 2:</strong> Testing and Approval <a target="_blank" href="%2$s">Enable the test mode</a> to use Google Pay without a merchant ID. This lets you capture the necessary screenshots for Google API team approval.<br/>
        <strong>Step 3:</strong> Add Merchant Name and Merchant ID Enter your merchant details to complete the setup.<br/><br/> <a target="_blank" href="%4$s">Click here to get detailed step by step instructions</a>
        <p>Note: If you prefer <strong>not to</strong> request a Google Merchant ID, use the <a href="%3$s">Express Checkout</a> buttons. These buttons provide Google Pay integration through the Chrome browser, offering a simple alternative.</p>', 'funnelkit-stripe-woo-payment-gateway' ), $gpay_console_url, $testing_gpay_url, $express_checkout_url, $get_details_url );


		return $description;
	}


	/**
	 * Initialise gateway settings form fields
	 *
	 * @return void
	 */
	public function init_form_fields() {
		$this->form_fields = apply_filters( 'fkwcs_google_pay_payment_form_fields', [

			'enabled'       => [
				'label'   => ' ',
				'type'    => 'checkbox',
				'title'   => __( 'Enable Google Pay', 'funnelkit-stripe-woo-payment-gateway' ),
				'default' => 'no',
			],
			'title'         => [
				'title'       => __( 'Title', 'funnelkit-stripe-woo-payment-gateway' ),
				'type'        => 'text',
				'description' => __( 'Change the payment gateway title that appears on the checkout.', 'funnelkit-stripe-woo-payment-gateway' ),
				'default'     => __( 'Google Pay', 'funnelkit-stripe-woo-payment-gateway' ),
				'desc_tip'    => true,

			],
			'merchant_id'   => [
				'title'       => __( 'Google Merchant ID', 'funnelkit-stripe-woo-payment-gateway' ),
				'type'        => 'text',
				'description' => __( 'Your unique Google Merchant ID is assigned by the Google API team after you register for Google Pay services. During the testing phase in TEST mode, it is not necessary to provide this ID; Google Pay will function without it.', 'funnelkit-stripe-woo-payment-gateway' ),
				'desc_tip'    => false,
			],
			'merchant_name' => [
				'title'       => __( 'Google Merchant Name', 'funnelkit-stripe-woo-payment-gateway' ),
				'type'        => 'text',
				'description' => __( 'Google Merchant Name Assignment Upon registering for Google Pay, the Google API team will assign your Google Merchant Name. When testing in TEST mode, you may leave this field blank, and Google Pay will continue to operate smoothly.', 'funnelkit-stripe-woo-payment-gateway' ),
				'default'     => get_bloginfo( 'name' ),
				'desc_tip'    => false,
			],


			'description'          => [
				'title'       => __( 'Description', 'funnelkit-stripe-woo-payment-gateway' ),
				'type'        => 'textarea',
				'css'         => 'width:25em',
				'description' => __( 'Change the payment gateway description that appears on the checkout.', 'funnelkit-stripe-woo-payment-gateway' ),
				'default'     => __( 'Pay with your Google Pay', 'funnelkit-stripe-woo-payment-gateway' ),
				'desc_tip'    => true,
			],
			'charge_type'          => [
				'title'       => __( 'Charge Type', 'funnelkit-stripe-woo-payment-gateway' ),
				'type'        => 'select',
				'description' => __( $this->get_charge_type_recommendation_text(), 'funnelkit-stripe-woo-payment-gateway' ),
				'default'     => 'automatic',
				'options'     => [
					'automatic' => __( 'Charge', 'funnelkit-stripe-woo-payment-gateway' ),
					'manual'    => __( 'Authorize', 'funnelkit-stripe-woo-payment-gateway' ),
				],
				'desc_tip'    => false,
			],
			'icon_type'            => [
				'type'        => 'select',
				'title'       => __( 'Icon', 'funnelkit-stripe-woo-payment-gateway' ),
				'options'     => array(
					'round-border' => __( 'With Rounded Border', 'funnelkit-stripe-woo-payment-gateway' ),
					'border'       => __( 'With Border', 'funnelkit-stripe-woo-payment-gateway' ),
					'standard'     => __( 'Standard', 'funnelkit-stripe-woo-payment-gateway' ),
				),
				'default'     => 'round-border',
				'desc_tip'    => true,
				'description' => __( 'The button color of the Google Pay button.', 'funnelkit-stripe-woo-payment-gateway' ),
			],
			'button_style_section' => [
				'type'  => 'title',
				'title' => __( 'Button Theme Settings', 'funnelkit-stripe-woo-payment-gateway' ),
			],
			'button_color'         => [
				'type'        => 'select',
				'title'       => __( 'Color', 'funnelkit-stripe-woo-payment-gateway' ),
				'options'     => array(
					'black' => __( 'Black', 'funnelkit-stripe-woo-payment-gateway' ),
					'white' => __( 'White', 'funnelkit-stripe-woo-payment-gateway' ),
				),
				'default'     => 'black',
				'desc_tip'    => true,
				'description' => __( 'The button color of the Google Pay button.', 'funnelkit-stripe-woo-payment-gateway' ),
			],
			'button_theme'         => [
				'type'        => 'select',
				'title'       => __( 'Theme', 'funnelkit-stripe-woo-payment-gateway' ),
				'options'     => array(
					'book'      => __( 'Book', 'funnelkit-stripe-woo-payment-gateway' ),
					'buy'       => __( 'Buy', 'funnelkit-stripe-woo-payment-gateway' ),
					'plain'     => __( 'Plain', 'funnelkit-stripe-woo-payment-gateway' ),
					'checkout'  => __( 'Checkout', 'funnelkit-stripe-woo-payment-gateway' ),
					'donate'    => __( 'Donate', 'funnelkit-stripe-woo-payment-gateway' ),
					'order'     => __( 'Order', 'funnelkit-stripe-woo-payment-gateway' ),
					'pay'       => __( 'Pay', 'funnelkit-stripe-woo-payment-gateway' ),
					'subscribe' => __( 'Subscribe', 'funnelkit-stripe-woo-payment-gateway' ),
				),
				'default'     => 'pay',
				'desc_tip'    => true,
				'description' => __( 'The button theme of the Google Pay button', 'funnelkit-stripe-woo-payment-gateway' ),
			],
			'button_dummy_button'  => [
				'type'    => 'fkwcs_html',
				'title'   => '',
				'default' => 'black',
			],
		] );
	}

	public function enqueue_stripe_js() {

		if ( ! $this->is_available() ) {
			return;
		}

		/**
		 * Check if selected location is not the current location
		 * OR
		 * Allow devs to enqueue assets
		 */
		if ( ! ( $this->is_selected_location() || ( apply_filters( 'fkwcs_enqueue_express_button_assets', false, $this ) ) ) ) {
			return;
		}
		parent::enqueue_stripe_js();
		wp_enqueue_style( 'fkwcs-style' );
		wp_enqueue_script( 'fkwcs-stripe-external' );
		if ( $this->is_checkout() ) {
			wp_enqueue_script( 'fkwcs-stripe-js' );
		}
		wp_enqueue_script( 'fkwcs-express-checkout-js' );
		wp_enqueue_script( 'fkwcs_stripe_gpay', 'https://pay.google.com/gp/p/js/pay.js' );
		if ( 0 === did_action( 'fkwcs_core_element_js_enqueued' ) && 0 === did_action( 'fkwcs_smart_buttons_js_enqueued' ) ) {
			wp_localize_script( 'fkwcs-express-checkout-js', 'fkwcs_data', $this->localize_data() );
		}
	}

	/**
	 * Checks if current location is chosen to display express checkout button
	 *
	 * @return boolean
	 */
	private function is_selected_location() {
		if ( $this->is_product() ) {
			return true;
		}

		if ( is_cart() ) {
			return true;
		}

		if ( is_checkout() ) {
			return true;
		}

		return false;

	}


	public function localize_element_data( $data ) {
		global $wp;
		if ( ! $this->is_available() ) {
			return $data;
		}
		$data['google_pay'] = [ 'merchant_id' => $this->merchant_id, 'merchant_name' => $this->merchant_name ];

		if ( $this->is_product() ) {
			$data['gpay_single_product'] = $this->get_product_data();
		}

		if ( $this->is_cart() || $this->is_checkout() || ( $this->is_product() && WC()->cart instanceof \WC_Cart && ! WC()->cart->is_empty() ) ) {
			$data['gpay_cart_data'] = $this->ajax_get_cart_details( true );
		}

		if ( ! empty( $wp->query_vars['order-pay'] ) ) {
			$order = wc_get_order( absint( $wp->query_vars['order-pay'] ) );

			$data['gpay_cart_data'] = [
				"shipping_required"     => wc_bool_to_string( false ),
				"order_data"            => [
					'currency'     => strtolower( $order->get_currency() ),
					'country_code' => substr( get_option( 'woocommerce_default_country' ), 0, 2 ),
					"displayItems" => $this->get_display_items_from_order( $order ),
					"total"        => [
						'label'   => __( 'Total', 'funnelkit-stripe-woo-payment-gateway' ),
						'amount'  => max( 0, apply_filters( 'fkwcs_stripe_calculated_total', Helper::get_stripe_amount( $order->get_total(), '', 1 ), $order->get_total() ) ),
						'pending' => false,
					]
				],
				"is_fkwcs_need_payment" => true,
				"shipping_options"      => []
			];

		}
		if ( 'yes' === $this->enabled ) {
			$data['google_pay_as_express'] = SmartButtons::get_instance()->local_settings['enabled'];
			$data['google_pay_as_regular'] = 'yes';
		}
		$data['google_pay_btn_color'] = $this->btn_color;
		$data['google_pay_btn_theme'] = $this->btn_theme;

		return $data;
	}

	/**
	 * Print the gateway field
	 *
	 * @return void
	 */
	public function payment_fields() {
		do_action( $this->id . '_before_payment_field_checkout' );
		include __DIR__ . '/parts/google_pay.php';
		do_action( $this->id . '_after_payment_field_checkout' );
	}


	/**
	 * Updates shipping address
	 *
	 * @return void
	 */
	public function gpay_update_shipping_address() {

		check_ajax_referer( 'fkwcs_nonce', 'fkwcs_nonce' );

		if ( ! isset( $_POST['shipping_address'] ) || ! isset( $_POST['shipping_method'] ) ) {
			$data = array(
				'result' => 'fail'
			);
			wp_send_json( $data );
		}
		$shipping_address = wc_clean( $_POST['shipping_address'] );


		wc_maybe_define_constant( 'WOOCOMMERCE_CART', true );
		add_filter( 'woocommerce_cart_ready_to_calc_shipping', function () {
			return true;
		}, 1000 );
		try {
			$this->wc_stripe_update_customer_location( $shipping_address );
			$this->update_shipping_method( wc_clean( $_POST['shipping_method'] ) );

			$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods', [] );
			/** update the WC cart with the new shipping options */
			if ( ! is_null( WC()->cart ) && WC()->cart instanceof \WC_Cart ) {
				WC()->cart->calculate_totals();
			}
			$this->maybe_restore_recurring_chosen_shipping_methods( $chosen_shipping_methods );
			/** if shipping address is not serviceable, throw an error */
			if ( ! $this->wc_stripe_shipping_address_serviceable( $this->get_shipping_packages() ) ) {
				$this->reason_code = 'SHIPPING_ADDRESS_UNSERVICEABLE';
				throw new \Exception( __( 'Your shipping address is not serviceable.', 'funnelkit-stripe-woo-payment-gateway' ) );
			}


			$data = $this->get_payment_response_data( $shipping_address );
		} catch ( \Exception $e ) {
			$data = array(
				'result' => 'fail'
			);
		}

		wp_send_json( $data );
	}

	public function get_payment_response_data( $shipping_address ) {
		$shipping_options = $this->get_formatted_shipping_methods();
		$items            = $this->build_display_items()['displayItems'];

		$new_data = array(
			'newTransactionInfo'          => array(
				'currencyCode'     => get_woocommerce_currency(),
				'countryCode'      => WC()->countries->get_base_country(),
				'totalPriceStatus' => 'FINAL',
				'totalPrice'       => wc_format_decimal( WC()->cart instanceof \WC_Cart ? WC()->cart->total : 0, 2 ),
				'displayItems'     => $items,
				'totalPriceLabel'  => __( 'Total', 'funnelkit-stripe-woo-payment-gateway' ),
			),
			'newShippingOptionParameters' => array(
				'shippingOptions'         => $shipping_options,
				'defaultSelectedOptionId' => $this->get_mapped_default_shipping_method( $shipping_options ),
			),
		);

		return array(
			'shipping_methods'     => WC()->session->get( 'chosen_shipping_methods', array() ),
			'paymentRequestUpdate' => $new_data,
			'address'              => $shipping_address
		);
	}

	/**
	 * Returns a default shipping method based on the chosen shipping methods.
	 *
	 * @param array $methods
	 *
	 * @return string
	 */
	private function get_mapped_default_shipping_method( $methods ) {
		$selected_methods     = WC()->session->get( 'chosen_shipping_methods', array() );
		$method_ids           = array_column( $methods, 'id' );
		$temp_shipping_method = false;
		foreach ( $selected_methods as $idx => $method ) {
			$method_id = sprintf( '%s:%s', $idx, $method );
			if ( in_array( $method_id, $method_ids, true ) ) {
				$temp_shipping_method = $method_id;
			}
		}
		if ( ! $temp_shipping_method ) {
			return current( $method_ids );
		}
	}

	/**
	 * @param $shipping_method array
	 *
	 * @return void
	 */
	public function update_shipping_method( $shipping_method ) {
		$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
		$posted_shipping_methods = wc_clean( wp_unslash( $shipping_method ) );
		if ( is_array( $posted_shipping_methods ) ) {
			foreach ( $posted_shipping_methods as $i => $value ) {
				$chosen_shipping_methods[ $i ] = $value;
			}
		}

		WC()->session->set( 'chosen_shipping_methods', $chosen_shipping_methods );
	}

	protected function get_smart_button_line_item( $name, $amount, $type = 'LINE_ITEM' ) {

		return [
			'label' => $name,
			'type'  => $type,
			'price' => (string) Helper::get_stripe_amount( $amount, '', 1, true ),
		];
	}


	/**
	 * Fetch cart details
	 *
	 * @return array
	 */
	public function ajax_get_cart_details( $is_localized = false ) {
		if ( 'wc_ajax_fkwcs_get_cart_details' === current_action() ) {
			check_ajax_referer( 'fkwcs_nonce', 'fkwcs_nonce' );

		}
		$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods', [] );
		if ( ! is_null( WC()->cart ) && WC()->cart instanceof \WC_Cart ) {
			WC()->cart->calculate_totals();
		}
		$this->maybe_restore_recurring_chosen_shipping_methods( $chosen_shipping_methods );
		$currency = get_woocommerce_currency();
		/** Set mandatory payment details */
		$data = [
			'shipping_required' => wc_bool_to_string( $this->shipping_required() ),
			'order_data'        => [
				'currency'     => strtolower( $currency ),
				'country_code' => substr( get_option( 'woocommerce_default_country' ), 0, 2 ),
			],
		];

		/**
		 * disabled GPay button if stripe not need payments
		 */

		$data['is_fkwcs_need_payment'] = false;
		if ( ! is_null( WC()->cart ) && WC()->cart instanceof \WC_Cart && WC()->cart->needs_payment() ) {
			$data['is_fkwcs_need_payment'] = true;
		}
		$data['order_data']       += $this->build_display_items( true, $is_localized );
		$data['shipping_options'] = $this->get_formatted_shipping_methods();

		if ( 'wc_ajax_fkwcs_get_cart_details' === current_action() ) {
			wp_send_json_success( $data );
		}

		return $data;
	}

	public function get_formatted_shipping_method( $price, $rate, $i, $package, $incl_tax ) {
		$method = array(
			'id'          => $this->get_shipping_method_id( $rate->id ),
			'label'       => $this->get_formatted_shipping_label( $price, $rate, $incl_tax ),
			'description' => ''
		);

		if ( $incl_tax ) {
			if ( $rate->get_shipping_tax() > 0 && ! wc_prices_include_tax() ) {
				$method['description'] = WC()->countries->inc_tax_or_vat();
			}
		} else {
			if ( $rate->get_shipping_tax() > 0 && wc_prices_include_tax() ) {
				$method['description'] = WC()->countries->ex_tax_or_vat();
			}
		}

		return $method;
	}


	public function get_item_order( $price, $label, $order, $type = 'LINE_ITEM' ) {


		return array(
			'label' => $label,
			'type'  => $type,
			'price' => (string) max( 0, Helper::get_stripe_amount( $price, $order->get_currency(), 1, true ) ),

		);
	}

	public function get_display_items_from_order( $order ) {

		$items = array();

		foreach ( $order->get_items() as $item ) {
			$qty     = $item->get_quantity();
			$label   = $qty > 1 ? sprintf( '%s X %s', $item->get_name(), $qty ) : $item->get_name();
			$items[] = $this->get_item_order( $item->get_subtotal(), $label, $order );

		}
		if ( 0 < $order->get_shipping_total() ) {
			$items[] = $this->get_item_order( $order->get_shipping_total(), __( 'Shipping', 'funnelkit-stripe-woo-payment-gateway' ), $order );
		}
		if ( 0 < $order->get_total_discount() ) {
			$items[] = $this->get_item_order( - 1 * $order->get_total_discount(), __( 'Discount', 'funnelkit-stripe-woo-payment-gateway' ), $order );
		}
		if ( 0 < $order->get_fees() ) {
			$fee_total = 0;
			foreach ( $order->get_fees() as $fee ) {
				$fee_total += $fee->get_total();
			}
			$items[] = $this->get_item_order( $fee_total, __( 'Fees', 'funnelkit-stripe-woo-payment-gateway' ), $order, 'LINE_ITEM' );
		}
		if ( 0 < $order->get_total_tax() ) {
			$items[] = $this->get_item_order( $order->get_total_tax(), __( 'Tax', 'woocommerce' ), $order, 'TAX' );
		}


		return $items;
	}

	protected function build_display_items( $display_items = true, $is_localized = false ) {

		if ( false === $is_localized ) {
			wc_maybe_define_constant( 'WOOCOMMERCE_CART', true );
		}

		$items     = [];
		$lines     = [];
		$subtotal  = 0;
		$discounts = 0;

		if ( ! is_null( WC()->cart ) && WC()->cart instanceof \WC_Cart ) {
			foreach ( WC()->cart->get_cart() as $item ) {
				$subtotal       += $item['line_subtotal'];
				$amount         = $item['line_subtotal'];
				$quantity_label = 1 < $item['quantity'] ? ' (' . $item['quantity'] . ')' : '';
				$product_name   = $item['data']->get_name();
				$items[]        = $this->get_smart_button_line_item( $product_name . $quantity_label, $amount );
			}

			if ( $display_items ) {
				$items = array_merge( $items, $lines );
			} else {
				/** Default show only subtotal instead of itemization */
				$items[] = $this->get_smart_button_line_item( 'Subtotal', $subtotal, 'SUBTOTAL' );
			}

			$applied_coupons = array_values( WC()->cart->get_coupon_discount_totals() );
			foreach ( $applied_coupons as $amount ) {
				$discounts += (float) $amount;
			}

			$discounts   = wc_format_decimal( $discounts, WC()->cart->dp );
			$tax         = wc_format_decimal( WC()->cart->tax_total + WC()->cart->shipping_tax_total, WC()->cart->dp );
			$shipping    = wc_format_decimal( WC()->cart->shipping_total, WC()->cart->dp );
			$order_total = WC()->cart->get_total( false );

			if ( wc_tax_enabled() ) {
				$items[] = $this->get_smart_button_line_item( esc_html( __( 'Tax', 'funnelkit-stripe-woo-payment-gateway' ) ), $tax, 'TAX' );
			}

			if ( WC()->cart->needs_shipping() ) {
				$items[] = $this->get_smart_button_line_item( esc_html( __( 'Shipping', 'funnelkit-stripe-woo-payment-gateway' ) ), $shipping );
			}

			if ( WC()->cart->has_discount() ) {
				$items[] = $this->get_smart_button_line_item( esc_html( __( 'Discount', 'funnelkit-stripe-woo-payment-gateway' ) ), $discounts );
			}

			$cart_fees = WC()->cart->get_fees();

			/** Include fees and taxes as display items */
			foreach ( $cart_fees as $fee ) {
				$items[] = $this->get_smart_button_line_item( $fee->name, $fee->amount );
			}


			$totals = $this->get_smart_button_line_totals( [
				'label'   => __( 'Total', 'funnelkit-stripe-woo-payment-gateway' ),
				'amount'  => max( 0, apply_filters( 'fkwcs_stripe_calculated_total', Helper::get_stripe_amount( $order_total, '', 1, true ), $order_total, WC()->cart ) ),
				'pending' => false,
			], $order_total );

			return [
				'displayItems' => $items,
				'total'        => $totals,
			];
		}

		return [
			'displayItems' => [],
			'total'        => [
				'label'   => __( 'Total', 'funnelkit-stripe-woo-payment-gateway' ),
				'amount'  => 0,
				'pending' => false,
			],
		];
	}

	public function add_google_pay_data( $fragments ) {

		$fragments['fkwcs_google_pay_data'] = $this->ajax_get_cart_details();


		return $fragments;
	}

	public function get_icon() {
		$icon_type = $this->get_option( 'icon_type' );

		$icons = '<span class="fkwcs_stripe_gpay_icons">';
		if ( $icon_type === 'round-border' ) {
			$image_svg_path = 'standard_rounded.svg';
		} elseif ( $icon_type === 'border' ) {
			$image_svg_path = 'googlepay_outline.svg';
		} else {
			$image_svg_path = 'standard.svg';
		}
		$icons .= '<img src="' . \FKWCS_URL . 'assets/icons/google/' . $image_svg_path . '' . '" alt="Visa" title="google pay" /></span>';

		return $icons;
	}

	public function add_mini_cart_wrapper() {
		if ( self::$mini_cart_wrapper_rendered ) {
			return;
		}
		if ( class_exists( '\FKCart\Includes\Data' ) && ! \FKCart\Includes\Data::get_value( 'smart_buttons' ) ) {
			return;
		}

		?>
        <div class="fkcart-checkout-wrap fkcart-panel fkwcs_fkcart_gpay_wrapper">
            <script>
                try {
                    (function ($) {
                        $(document.body).trigger('fkwcs_generate_fkcart_mini_button');
                    })(jQuery)
                } catch (e) {

                }
            </script>
        </div>
		<?php
		self::$mini_cart_wrapper_rendered = true;
	}

}