<?php
/**
 * ConvesioPay Unified Blocks Support Class
 *
 * @package PeachPay
 */

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

/**
 * ConvesioPay Unified Blocks Support Class
 */
class ConvesioPay_Unified_Blocks_Support extends \Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType {

	/**
	 * Payment method name
	 */
	protected $name = 'peachpay_convesiopay_unified';

	/**
	 * Initialize the payment method type
	 */
	public function initialize() {
		$this->settings = get_option( 'woocommerce_peachpay_convesiopay_unified_settings', [] );
	}

	/**
	 * Returns if this payment method should be active.
	 * Uses payment_gateways() only to avoid get_available_payment_gateways() (which triggers is_available() for all gateways).
	 */
	public function is_active() {
		if ( ! PeachPay_ConvesioPay_Integration::connected() ) {
			return false;
		}
		$active_methods = $this->get_active_payment_methods();
		if ( empty( $active_methods ) ) {
			return false;
		}
		$gateways = WC()->payment_gateways()->payment_gateways();
		if ( ! isset( $gateways['peachpay_convesiopay_unified'] ) ) {
			return false;
		}
		$gateway = $gateways['peachpay_convesiopay_unified'];
		return 'yes' === $gateway->enabled;
	}

	/**
	 * Returns an array of scripts/handles to be registered for this payment method
	 */
	public function get_payment_method_script_handles() {
		// First register the ConvesioPay SDK
		wp_register_script(
			'convesiopay-sdk',
			'https://js.convesiopay.com/v1/',
			array(),
			'1.0.0',
			true
		);

		$script_path = '/core/payments/convesiopay/assets/js/convesiopay-unified-blocks-v2.js';
		$script_asset_path = PEACHPAY_ABSPATH . 'core/payments/convesiopay/assets/js/convesiopay-unified-blocks.asset.php';
		$script_asset = file_exists( $script_asset_path )
			? require( $script_asset_path )
			: array(
				'dependencies' => array(
					'convesiopay-sdk',  // Add ConvesioPay SDK as dependency
					'wc-blocks-registry',
					'wc-settings',
					'wp-element',
					'wp-html-entities',
					'wp-i18n',
				),
				'version' => '2.6.20003' // Use WC Blocks classes only, no inline styles
			);

		wp_register_script(
			'wc-convesiopay-unified-blocks-integration',
			plugins_url( 'peachpay-for-woocommerce' . $script_path ),
			$script_asset['dependencies'],
			$script_asset['version'],
			true
		);

		return [ 'wc-convesiopay-unified-blocks-integration' ];
	}

	/**
	 * Returns an array of key=>value pairs of data made available to the payment methods script.
	 * Uses payment_gateways() only to avoid get_available_payment_gateways() (which triggers is_available() for all gateways).
	 */
	public function get_payment_method_data() {
		$gateways = WC()->payment_gateways()->payment_gateways();
		if ( ! isset( $gateways['peachpay_convesiopay_unified'] ) || 'yes' !== $gateways['peachpay_convesiopay_unified']->enabled ) {
			return array();
		}
		$gateway = $gateways['peachpay_convesiopay_unified'];

		// Get ConvesioPay configuration
		$config = PeachPay_ConvesioPay_Integration::config();
		$integration_name = $config['integration_name'] ?? '';
		
		// Debug: Log the client key status
		$client_key = $config['client_key'] ?? '';
		$apiKey = $config['api_key'] ?? '';

		// CRITICAL: Get theme from separate option (not from gateway settings)
		// WooCommerce gateways only save keys defined in form_fields during settings save,
		// so we store the theme in a dedicated option to avoid it being stripped out
		$checkout_theme = get_option( 'peachpay_convesiopay_checkout_theme', 'light' );

		// Get active payment methods and determine label
		$active_methods = $this->get_active_payment_methods();
		$label = get_option( 'peachpay_convesiopay_unified_gateway_label', 'Credit Card' );

		// Get fee configuration from individual gateways
		$gateways = WC()->payment_gateways->payment_gateways();
		$card_gateway = $gateways['peachpay_convesiopay_card'] ?? null;
		$applepay_gateway = $gateways['peachpay_convesiopay_applepay'] ?? null;
		$googlepay_gateway = $gateways['peachpay_convesiopay_googlepay'] ?? null;
		$btcpay_gateway = $gateways['peachpay_convesiopay_btcpay'] ?? null;

		$fee_config = array(
			'card' => array(
				'enabled' => $card_gateway ? $card_gateway->get_option( 'fees_enabled' ) === 'yes' : false,
				'type' => $card_gateway ? $card_gateway->get_option( 'fee_type' ) : 'fixed',
				'amount' => $card_gateway ? floatval( $card_gateway->get_option( 'fee_amount' ) ) : 0,
				'label' => $card_gateway ? $card_gateway->get_option( 'fee_reason' ) : '',
			),
			'applepay' => array(
				'enabled' => $applepay_gateway ? $applepay_gateway->get_option( 'fees_enabled' ) === 'yes' : false,
				'type' => $applepay_gateway ? $applepay_gateway->get_option( 'fee_type' ) : 'fixed',
				'amount' => $applepay_gateway ? floatval( $applepay_gateway->get_option( 'fee_amount' ) ) : 0,
				'label' => $applepay_gateway ? $applepay_gateway->get_option( 'fee_reason' ) : '',
			),
			'googlepay' => array(
				'enabled' => $googlepay_gateway ? $googlepay_gateway->get_option( 'fees_enabled' ) === 'yes' : false,
				'type' => $googlepay_gateway ? $googlepay_gateway->get_option( 'fee_type' ) : 'fixed',
				'amount' => $googlepay_gateway ? floatval( $googlepay_gateway->get_option( 'fee_amount' ) ) : 0,
				'label' => $googlepay_gateway ? $googlepay_gateway->get_option( 'fee_reason' ) : '',
			),
			'btcpay' => array(
				'enabled' => $btcpay_gateway ? $btcpay_gateway->get_option( 'fees_enabled' ) === 'yes' : false,
				'type' => $btcpay_gateway ? $btcpay_gateway->get_option( 'fee_type' ) : 'fixed',
				'amount' => $btcpay_gateway ? floatval( $btcpay_gateway->get_option( 'fee_amount' ) ) : 0,
				'label' => $btcpay_gateway ? $btcpay_gateway->get_option( 'fee_reason' ) : '',
			),
		);

		// Get cart total for percentage calculations (subtotal - discount to include coupon discounts)
		$cart_total = WC()->cart ? WC()->cart->get_subtotal() - WC()->cart->get_discount_total() : 0;

		// Get card icons settings (individual card selections)
		$card_icons_settings = get_option( 'peachpay_convesiopay_card_icons', array(
			'visa'       => 'no',
			'mastercard' => 'no',
			'amex'       => 'no',
			'discover'   => 'no',
		) );
		
		// Check if any card icons should be shown
		$show_card_icons = in_array( 'yes', $card_icons_settings, true );
		
		// Define all available card icons with their URLs
		$all_card_icons = array(
			'visa'       => PeachPay::get_asset_url( '/img/marks/visa.svg' ),
			'mastercard' => PeachPay::get_asset_url( '/img/marks/mastercard.svg' ),
			'amex'       => PeachPay::get_asset_url( '/img/marks/amex.svg' ),
			'discover'   => PeachPay::get_asset_url( '/img/marks/discover.svg' ),
		);
		
		// Build card icons data for blocks - only include enabled cards
		$card_icons = array();
		foreach ( $all_card_icons as $card_name => $icon_url ) {
			if ( isset( $card_icons_settings[ $card_name ] ) && $card_icons_settings[ $card_name ] === 'yes' ) {
				$card_icons[ $card_name ] = $icon_url;
			}
		}

		$icon_url = $gateway->get_icon_url( 'full', 'color' );
		$icon     = $icon_url ? '<span style="gap:0.2rem;margin-left:0.4rem;align-items:center"><img style="max-height:25px;" data-gateway="' . esc_attr( $gateway->id ) . '" src="' . esc_url( $icon_url ) . '" alt="' . esc_attr( $gateway->get_title() ) . '" /></span>' : '';

		return array(
			'title'            => $label,
			'description'      => 'Pay with card, crypto, or digital wallets via ConvesioPay.',
			'supports'         => $gateway->supports,
			'icon'             => $icon,
			'ajax_url'         => admin_url( 'admin-ajax.php' ),
			'nonce'            => wp_create_nonce( 'peachpay_convesiopay_nonce' ),
			'integration_name' => $integration_name,
			'checkout_theme'   => $checkout_theme,
			'active_methods'   => $active_methods,
			'disabled_payment_methods' => $this->get_disabled_payment_methods(),
			'label'            => $label,
			'show_card_icons'  => $show_card_icons,
			'card_icons'       => $card_icons,
			'convesiopay_config' => array(
				'apiKey' => $apiKey,  // Should be decrypted by PeachPay_ConvesioPay_Integration::config()
				'clientKey' => $client_key,  // Should be decrypted by PeachPay_ConvesioPay_Integration::config()
				'api_url'   => peachpay_is_test_mode() ? 'https://api-qa.convesiopay.com' : 'https://api.convesiopay.com',
			),
			'fee_config'       => $fee_config,
			'cart_total'       => floatval( $cart_total ),
		);
	}

	/**
	 * Get an individual ConvesioPay gateway instance.
	 *
	 * @param string $method Payment method type.
	 * @return WC_Payment_Gateway|null Gateway instance or null.
	 */
	private function get_individual_gateway( $method ) {
		$gateway_ids = array(
			'card'      => 'peachpay_convesiopay_card',
			'applepay'  => 'peachpay_convesiopay_applepay',
			'googlepay' => 'peachpay_convesiopay_googlepay',
			'btcpay'    => 'peachpay_convesiopay_btcpay',
		);

		$gateway_id = isset( $gateway_ids[ $method ] ) ? $gateway_ids[ $method ] : null;
		if ( ! $gateway_id ) {
			return null;
		}

		return peachpay_get_payment_gateway( $gateway_id );
	}

	/**
	 * Check whether an individual ConvesioPay gateway is enabled.
	 *
	 * @param WC_Payment_Gateway|null $gateway Gateway instance.
	 * @return bool
	 */
	private function is_individual_gateway_enabled( $gateway ) {
		if ( ! $gateway ) {
			return false;
		}

		$enabled_option   = $gateway->get_option( 'enabled', 'no' );
		$enabled_property = $gateway->enabled ?? 'no';

		return 'yes' === $enabled_option || 'yes' === $enabled_property;
	}

	/**
	 * Check whether an individual ConvesioPay gateway should show in native checkout.
	 *
	 * @param WC_Payment_Gateway|null $gateway Gateway instance.
	 * @return bool
	 */
	private function is_individual_gateway_visible_in_native_checkout( $gateway ) {
		if ( ! $gateway ) {
			return false;
		}

		return 'express_checkout_only' !== $gateway->get_option( 'active_locations', 'default' );
	}

	/**
	 * Check whether an individual ConvesioPay gateway is active for native checkout.
	 *
	 * @param WC_Payment_Gateway|null $gateway Gateway instance.
	 * @return bool
	 */
	private function is_individual_gateway_active_for_native_checkout( $gateway ) {
		return $this->is_individual_gateway_enabled( $gateway ) && $this->is_individual_gateway_visible_in_native_checkout( $gateway );
	}

	/**
	 * Get ConvesioPay SDK disabled payment method flags for native checkout.
	 *
	 * @return array
	 */
	private function get_disabled_payment_methods() {
		return array(
			'cards'     => ! $this->is_individual_gateway_active_for_native_checkout( $this->get_individual_gateway( 'card' ) ),
			'applePay'  => ! $this->is_individual_gateway_active_for_native_checkout( $this->get_individual_gateway( 'applepay' ) ),
			'googlePay' => ! $this->is_individual_gateway_active_for_native_checkout( $this->get_individual_gateway( 'googlepay' ) ),
		);
	}

	/**
	 * Get list of active payment methods
	 * 
	 * @return array Array of active payment method keys ('card', 'applepay', 'googlepay', 'crypto')
	 */
	private function get_active_payment_methods() {
		$active_methods = array();
		
		// Check Card
		if ( PeachPay_ConvesioPay_Integration::is_capable( 'card' ) ) {
			$card_gateway = $this->get_individual_gateway( 'card' );
			if ( $this->is_individual_gateway_active_for_native_checkout( $card_gateway ) ) {
				$active_methods[] = 'card';
			}
		}
		
		// Check ApplePay
		if ( PeachPay_ConvesioPay_Integration::is_capable( 'applepay' ) ) {
			$applepay_gateway = $this->get_individual_gateway( 'applepay' );
			if ( $this->is_individual_gateway_active_for_native_checkout( $applepay_gateway ) ) {
				$active_methods[] = 'applepay';
			}
		}

		// Check Google Pay
		if ( PeachPay_ConvesioPay_Integration::is_capable( 'googlepay' ) ) {
			$googlepay_gateway = $this->get_individual_gateway( 'googlepay' );
			if ( $this->is_individual_gateway_active_for_native_checkout( $googlepay_gateway ) ) {
				$active_methods[] = 'googlepay';
			}
		}
		
		// Check Crypto/BTCPay
		if ( PeachPay_ConvesioPay_Integration::is_capable( 'btcpay' ) ) {
			$btcpay_gateway = $this->get_individual_gateway( 'btcpay' );
			if ( $this->is_individual_gateway_active_for_native_checkout( $btcpay_gateway ) ) {
				$active_methods[] = 'crypto';
			}
		}
		
		return $active_methods;
	}
}