<?php
/**
 * Wayl Payment Gateway
 *
 * WooCommerce payment gateway integration for Wayl Checkout.
 *
 * @package Wayl_Checkout
 * @since 1.2.0
 */

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

/**
 * Class WaylCHP_Checkout_Gateway
 */
class WaylCHP_Checkout_Gateway extends WC_Payment_Gateway {

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->id                 = 'wayl';
		$this->method_title       = __( 'Wayl Checkout', 'wayl-checkout' );
		$this->method_description = __( 'Enable payments via Wayl Checkout.', 'wayl-checkout' );
		$this->has_fields         = true;
		$this->supports           = array( 'products', 'refunds' );

		$this->init_form_fields();
		$this->init_settings();

		$this->title         = $this->get_option( 'title', $this->get_default_title() );
		$this->description   = $this->get_option( 'description', __( 'Pay securely with Wayl Checkout', 'wayl-checkout' ) );
		$this->api_key       = $this->get_option( 'api_key' );
		$this->lang          = $this->get_option( 'lang', 'ar' );
		$this->currency      = $this->get_option( 'currency', 'iqd' );
		$this->exchange_rate = floatval( $this->get_option( 'exchange_rate', '1320' ) );
		$this->log_enabled   = 'yes' === $this->get_option( 'logging', 'no' );

		// Set the payment method logo (use app logo for checkout)
		$this->icon = $this->get_wayl_app_logo_url();

		// Initialize logger
		WaylCHP_Logger::init();

		$this->webhook_secret = get_option( 'waylchp_webhook_secret' );
		if ( ! $this->webhook_secret ) {
			$this->webhook_secret = wp_generate_password( 32, true, true );
			update_option( 'waylchp_webhook_secret', $this->webhook_secret );
		}

		add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );

		// Enqueue checkout styles (only on checkout page)
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_checkout_scripts' ) );

		// Display Wayl logo in order details
		add_action( 'woocommerce_order_details_after_payment_method', array( $this, 'display_wayl_logo_in_order' ), 10, 1 );
		add_action( 'woocommerce_admin_order_data_after_billing_address', array( $this, 'display_wayl_logo_in_admin' ), 10, 1 );

		// Add admin scripts for refund UI modifications
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_refund_scripts' ) );

		// Enqueue admin styles
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_styles' ) );
	}

	/**
	 * Enqueue admin styles
	 *
	 * @return void
	 */
	public function enqueue_admin_styles() {
		// Only on WooCommerce settings pages
		$screen = get_current_screen();
		if ( ! $screen || ( strpos( $screen->id, 'woocommerce' ) === false && strpos( $screen->id, 'wc-settings' ) === false ) ) {
			return;
		}

		// Check if we're on the Wayl settings page
		if ( isset( $_GET['section'] ) && sanitize_text_field( wp_unslash( $_GET['section'] ) ) === 'wayl' ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			wp_enqueue_style(
				'wayl-checkout-admin',
				WAYLCHP_PLUGIN_URL . 'assets/css/wayl-checkout-admin.css',
				array(),
				WAYLCHP_PLUGIN_VERSION
			);
		}
	}

	/**
	 * Get Wayl logo URL (main plugin logo)
	 *
	 * @return string Logo URL
	 */
	private function get_wayl_logo_url() {
		// Main Wayl logo for plugin settings page - can be customized via filter
		$logo_url = apply_filters( 'waylchp_logo_url', WAYLCHP_PLUGIN_URL . 'assets/images/wayl-logo.png' );
		return esc_url( $logo_url );
	}

	/**
	 * Get Wayl checkout logo URL (small logo for checkout page)
	 *
	 * @return string Logo URL
	 */
	private function get_wayl_checkout_logo_url() {
		// Small logo for checkout page - can be customized via filter
		$logo_url = apply_filters( 'waylchp_checkout_logo_url', WAYLCHP_PLUGIN_URL . 'assets/images/wayl-checkout-logo.png' );
		return esc_url( $logo_url );
	}

	/**
	 * Get Wayl app logo URL (small app-like logo)
	 *
	 * @return string Logo URL
	 */
	private function get_wayl_app_logo_url() {
		// Small app-like logo - can be customized via filter
		$logo_url = apply_filters( 'waylchp_app_logo_url', WAYLCHP_PLUGIN_URL . 'assets/images/wayl-app-logo.png' );
		return esc_url( $logo_url );
	}

	/**
	 * Enqueue checkout scripts and styles
	 *
	 * @return void
	 */
	public function enqueue_checkout_scripts() {
		// Only enqueue on checkout page to avoid affecting other pages
		if ( ! is_checkout() ) {
			return;
		}
		wp_enqueue_style(
			'wayl-checkout',
			WAYLCHP_PLUGIN_URL . 'assets/css/wayl-checkout.css',
			array(),
			WAYLCHP_PLUGIN_VERSION
		);
	}

	/**
	 * Enqueue admin scripts for refund UI modifications
	 *
	 * @return void
	 */
	public function enqueue_admin_refund_scripts() {
		// Only on order edit pages
		$screen = get_current_screen();
		if ( ! $screen || 'shop_order' !== $screen->id ) {
			return;
		}

		// Check if this order uses Wayl payment method
		$order_id = isset( $_GET['post'] ) ? absint( $_GET['post'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( ! $order_id ) {
			return;
		}

		$order = wc_get_order( $order_id );
		if ( ! $order || $order->get_payment_method() !== $this->id ) {
			return;
		}

		// Enqueue admin script
		wp_enqueue_script(
			'wayl-checkout-admin',
			WAYLCHP_PLUGIN_URL . 'assets/js/wayl-checkout-admin.js',
			array( 'jquery' ),
			WAYLCHP_PLUGIN_VERSION,
			true
		);

		// Localize script with translatable strings
		wp_localize_script(
			'wayl-checkout-admin',
			'waylCheckoutAdmin',
			array(
				'refundLabel'            => esc_js( __( 'Wayl Refund:', 'wayl-checkout' ) ),
				'refundMessage'          => esc_js( __( 'Full order amount will be refunded. Amount field is locked.', 'wayl-checkout' ) ),
				'charactersLabel'        => esc_js( __( 'characters', 'wayl-checkout' ) ),
				'refundReasonMaxLength'  => esc_js( __( 'Refund reason must be 100 characters or less.', 'wayl-checkout' ) ),
				'refundReasonPlaceholder' => esc_js( __( 'Refund reason (required, max 100 characters)', 'wayl-checkout' ) ),
			)
		);
	}


	/**
	 * Get payment channels from API with caching
	 *
	 * @return array Array of payment channels
	 */
	private function get_payment_channels() {
		// Channels API is not used; always fall back to static defaults.
		return array();
	}

	/**
	 * Output payment fields on checkout
	 *
	 * @return void
	 */
	public function payment_fields() {
		// Get payment channels from API
		$channels = $this->get_payment_channels();

		// If no channels from API, show default payment methods
		if ( empty( $channels ) ) {
			$channels = array(
				array(
					'id'   => 'visa_mastercard',
					'name' => __( 'Visa/MasterCard', 'wayl-checkout' ),
					'icon' => WAYLCHP_PLUGIN_URL . 'assets/images/visa-mastercard.png',
				),
				array(
					'id'   => 'zaincash',
					'name' => __( 'ZainCash', 'wayl-checkout' ),
					'icon' => WAYLCHP_PLUGIN_URL . 'assets/images/zaincash.png',
				),
				array(
					'id'   => 'fib',
					'name' => __( 'FIB', 'wayl-checkout' ),
					'icon' => WAYLCHP_PLUGIN_URL . 'assets/images/fib.png',
				),
				array(
					'id'   => 'fastpay',
					'name' => __( 'FastPay', 'wayl-checkout' ),
					'icon' => WAYLCHP_PLUGIN_URL . 'assets/images/fastpay.png',
				),
			);
		}

		echo '<div class="wayl-checkout-wrapper">';

		// Display payment channels
		if ( ! empty( $channels ) ) {
			echo '<ul class="wayl-channels-list">';

			foreach ( $channels as $channel ) {
				$channel_id   = isset( $channel['id'] ) ? esc_attr( $channel['id'] ) : '';
				$channel_name = isset( $channel['name'] ) ? esc_html( $channel['name'] ) : '';
				$channel_icon = isset( $channel['icon'] ) ? esc_url( $channel['icon'] ) : '';

				if ( $channel_icon ) {
					echo '<li class="wayl-channel-item">';
					echo '<img src="' . esc_url( $channel_icon ) . '" alt="' . esc_attr( $channel_name ) . '" class="wayl-channel-icon" />';
					echo '</li>';
				}
			}

			echo '</ul>';
		}

		echo '</div>';
	}

	/**
	 * Filter gateway icon to add class and wrap in container
	 *
	 * @param string $icon Icon HTML
	 * @param string $id Gateway ID
	 * @return string Filtered icon HTML
	 */
	public function filter_gateway_icon( $icon, $id ) {
		if ( $id === $this->id ) {
			$icon = str_replace( '<img ', '<img class="wayl-logo" ', $icon );
			$icon = '<span class="wayl-logo-wrapper">' . $icon . '</span>';
		}
		return $icon;
	}

	/**
	 * Filter gateway title - show the title
	 *
	 * @param string $title Gateway title
	 * @param string $id Gateway ID
	 * @return string Filtered title
	 */
	public function filter_gateway_title( $title, $id ) {
		if ( $id === $this->id ) {
			// Return the title so it's displayed
			return $title;
		}
		return $title;
	}

	/**
	 * Admin options page output with enhanced design
	 *
	 * @return void
	 */
	public function admin_options() {
		// Check if plugin is configured
		$is_configured = ! empty( $this->api_key );
		?>
		<div class="waylchp-admin-settings-wrapper">
			<div class="waylchp-header-section" style="background: linear-gradient(135deg, #343433 0%, #142327 100%) !important;">
				<div class="waylchp-logo-container">
					<img src="<?php echo esc_url( $this->get_wayl_logo_url() ); ?>" alt="Wayl" class="waylchp-logo" />
				</div>
				<div class="waylchp-header-content">
					<h2><?php esc_html_e( 'Wayl Checkout', 'wayl-checkout' ); ?></h2>
					<p class="waylchp-subtitle">
						<strong><?php esc_html_e( 'Payment facilitator', 'wayl-checkout' ); ?></strong> <span class="waylchp-iraq-flag">🇮🇶</span>
						<?php esc_html_e( '- Accept payments securely through Wayl\'s Checkout, accept local and international cards, ZainCash, FIB, FastPay and more payment methods', 'wayl-checkout' ); ?>
					</p>
				</div>
			</div>

			<?php if ( ! $is_configured ) : ?>
			<div class="waylchp-stats-section">
				<div class="waylchp-stat-item">
					<div class="waylchp-stat-number">3000+</div>
					<div class="waylchp-stat-label"><?php esc_html_e( 'Iraqi Merchants', 'wayl-checkout' ); ?></div>
				</div>
				<div class="waylchp-stat-item">
					<div class="waylchp-stat-number">3B+</div>
					<div class="waylchp-stat-label"><?php esc_html_e( 'Billion IQD Processed', 'wayl-checkout' ); ?></div>
				</div>
				<div class="waylchp-stat-item">
					<div class="waylchp-stat-number">30K+</div>
					<div class="waylchp-stat-label"><?php esc_html_e( 'Transactions/Year', 'wayl-checkout' ); ?></div>
				</div>
			</div>

			<div class="waylchp-info-cards">
				<div class="waylchp-info-card">
					<h3 style="border-bottom-color: #343433 !important;"><?php esc_html_e( 'About Wayl', 'wayl-checkout' ); ?></h3>
					<p><strong><?php esc_html_e( 'Wayl is a payment facilitator.', 'wayl-checkout' ); ?></strong> <?php esc_html_e( 'We enable online merchants to accept online payments via Local and International payment methods.', 'wayl-checkout' ); ?></p>
					<p><?php esc_html_e( 'Wayl Checkout aggregates all payment methods in one solution, making it easy for your customers to pay using their preferred method.', 'wayl-checkout' ); ?></p>
					<ul class="waylchp-features-list">
						<li><?php esc_html_e( 'Payment facilitator for the Iraqi market', 'wayl-checkout' ); ?></li>
						<li><?php esc_html_e( 'Iraqi local and international Visa/MasterCard acceptance', 'wayl-checkout' ); ?></li>
						<li><?php esc_html_e( 'All payment methods in one solution', 'wayl-checkout' ); ?></li>
						<li><?php esc_html_e( 'Secure payment processing', 'wayl-checkout' ); ?></li>
						<li><?php esc_html_e( 'Real-time payment notifications', 'wayl-checkout' ); ?></li>
						<li><?php esc_html_e( 'Support for IQD and USD', 'wayl-checkout' ); ?></li>
						<li><?php esc_html_e( 'Arabic and English language support', 'wayl-checkout' ); ?></li>
					</ul>
				</div>

				<div class="waylchp-info-card waylchp-payment-methods-card">
					<h3 style="border-bottom-color: #343433 !important;"><?php esc_html_e( 'Accepted Payment Methods', 'wayl-checkout' ); ?></h3>
					<p><?php esc_html_e( 'Wayl enables your customers to pay using:', 'wayl-checkout' ); ?></p>
					<div class="waylchp-payment-methods-image">
						<img src="<?php echo esc_url( WAYLCHP_PLUGIN_URL . 'assets/images/payment-methods.png' ); ?>" alt="<?php esc_attr_e( 'Wayl Payment Methods', 'wayl-checkout' ); ?>" />
					</div>
					<ul class="waylchp-payment-methods-list">
						<li><?php esc_html_e( 'Iraqi Local & International Visa/MasterCard', 'wayl-checkout' ); ?></li>
						<li><?php esc_html_e( 'ZainCash', 'wayl-checkout' ); ?></li>
						<li><?php esc_html_e( 'FIB (First Iraqi Bank)', 'wayl-checkout' ); ?></li>
						<li><?php esc_html_e( 'FastPay', 'wayl-checkout' ); ?></li>
					</ul>
				</div>

				<div class="waylchp-info-card waylchp-contact-card">
					<h3 style="border-bottom-color: #343433 !important;"><?php esc_html_e( 'Need Help?', 'wayl-checkout' ); ?></h3>
					<p><?php esc_html_e( 'Our support team is here to assist you with setup and any questions you may have.', 'wayl-checkout' ); ?></p>
					<div class="waylchp-contact-info">
						<p><strong><?php esc_html_e( 'Email:', 'wayl-checkout' ); ?></strong> <a href="mailto:support@wayl.io" style="color: #343433 !important;">support@wayl.io</a></p>
						<p><strong><?php esc_html_e( 'WhatsApp:', 'wayl-checkout' ); ?></strong> <a href="https://wa.me/9647752277781" target="_blank" rel="noopener noreferrer" style="color: #343433 !important;">+964 775 227 7781</a></p>
						<p><strong><?php esc_html_e( 'Website:', 'wayl-checkout' ); ?></strong> <a href="https://www.wayl.io" target="_blank" rel="noopener noreferrer" style="color: #343433 !important;">www.wayl.io</a></p>
					</div>
				</div>
			</div>

			<div class="waylchp-setup-section">
				<h3 style="border-bottom-color: #343433 !important;"><?php esc_html_e( 'Setup Steps for Merchants', 'wayl-checkout' ); ?></h3>
				<ol class="waylchp-setup-steps">
					<li><strong><?php esc_html_e( 'Register your account:', 'wayl-checkout' ); ?></strong> <?php esc_html_e( 'Sign up and submit your information via', 'wayl-checkout' ); ?> <a href="https://dashboard.thewayl.com" target="_blank" rel="noopener noreferrer">dashboard.thewayl.com</a></li>
					<li><strong><?php esc_html_e( 'Get your API Key:', 'wayl-checkout' ); ?></strong> <?php esc_html_e( 'Contact Wayl Support to obtain your Merchant Token API Key', 'wayl-checkout' ); ?>
						<ul style="margin-top: 8px; margin-left: 20px;">
							<li><?php esc_html_e( 'Email:', 'wayl-checkout' ); ?> <a href="mailto:support@wayl.io">support@wayl.io</a></li>
							<li><?php esc_html_e( 'WhatsApp:', 'wayl-checkout' ); ?> <a href="https://wa.me/9647752277781" target="_blank" rel="noopener noreferrer">+964 775 227 7781</a></li>
						</ul>
					</li>
					<li><strong><?php esc_html_e( 'Add your API key:', 'wayl-checkout' ); ?></strong> <?php esc_html_e( 'Enter your API key in the field below', 'wayl-checkout' ); ?></li>
					<li><strong><?php esc_html_e( 'Configure settings:', 'wayl-checkout' ); ?></strong> <?php esc_html_e( 'Set your preferred language and currency settings', 'wayl-checkout' ); ?></li>
					<li><strong><?php esc_html_e( 'Go live:', 'wayl-checkout' ); ?></strong> <?php esc_html_e( 'Save settings and monitor your received payments via Wayl dashboard', 'wayl-checkout' ); ?></li>
				</ol>
			</div>
			<?php else : ?>
			<div class="waylchp-info-cards">
				<div class="waylchp-info-card waylchp-payment-methods-card">
					<h3 style="border-bottom-color: #343433 !important;"><?php esc_html_e( 'Accepted Payment Methods', 'wayl-checkout' ); ?></h3>
					<p><?php esc_html_e( 'Wayl enables your customers to pay using:', 'wayl-checkout' ); ?></p>
					<div class="waylchp-payment-methods-image">
						<img src="<?php echo esc_url( WAYLCHP_PLUGIN_URL . 'assets/images/payment-methods.png' ); ?>" alt="<?php esc_attr_e( 'Wayl Payment Methods', 'wayl-checkout' ); ?>" />
					</div>
					<ul class="waylchp-payment-methods-list">
						<li><?php esc_html_e( 'Iraqi Local & International Visa/MasterCard', 'wayl-checkout' ); ?></li>
						<li><?php esc_html_e( 'ZainCash', 'wayl-checkout' ); ?></li>
						<li><?php esc_html_e( 'FIB (First Iraqi Bank)', 'wayl-checkout' ); ?></li>
						<li><?php esc_html_e( 'FastPay', 'wayl-checkout' ); ?></li>
					</ul>
				</div>

				<div class="waylchp-info-card waylchp-contact-card">
					<h3 style="border-bottom-color: #343433 !important;"><?php esc_html_e( 'Need Help?', 'wayl-checkout' ); ?></h3>
					<p><?php esc_html_e( 'Our support team is here to assist you with any questions you may have.', 'wayl-checkout' ); ?></p>
					<div class="waylchp-contact-info">
						<p><strong><?php esc_html_e( 'Email:', 'wayl-checkout' ); ?></strong> <a href="mailto:support@wayl.io" style="color: #343433 !important;">support@wayl.io</a></p>
						<p><strong><?php esc_html_e( 'WhatsApp:', 'wayl-checkout' ); ?></strong> <a href="https://wa.me/9647752277781" target="_blank" rel="noopener noreferrer" style="color: #343433 !important;">+964 775 227 7781</a></p>
						<p><strong><?php esc_html_e( 'Website:', 'wayl-checkout' ); ?></strong> <a href="https://www.wayl.io" target="_blank" rel="noopener noreferrer" style="color: #343433 !important;">www.wayl.io</a></p>
					</div>
				</div>
			</div>
			<?php endif; ?>
		</div>
		<?php
		// Call parent admin_options to render the form
		parent::admin_options();
	}

	/**
	 * Initialize form fields
	 *
	 * @return void
	 */
	public function init_form_fields() {
		$this->form_fields = array(
			'enabled'       => array(
				'title'   => __( 'Enable/Disable', 'wayl-checkout' ),
				'type'    => 'checkbox',
				'label'   => __( 'Enable Wayl Checkout', 'wayl-checkout' ),
				'default' => 'yes',
			),
			'title'         => array(
				'title'       => __( 'Title', 'wayl-checkout' ),
				'type'        => 'text',
				'description' => __( 'This controls the title which the user sees during checkout.', 'wayl-checkout' ),
				'default'     => $this->get_default_title(),
				'desc_tip'    => true,
			),
			'description'   => array(
				'title'       => __( 'Description', 'wayl-checkout' ),
				'type'        => 'textarea',
				'description' => __( 'Payment method description that the customer will see on your checkout.', 'wayl-checkout' ),
				'default'     => __( 'Pay securely with Wayl Checkout', 'wayl-checkout' ),
				'desc_tip'    => true,
			),
			'api_key'       => array(
				'title'       => __( 'API Key', 'wayl-checkout' ),
				'type'        => 'password',
				'description' => sprintf(
					/* translators: 1: Support email, 2: Support WhatsApp */
					__( 'Get your Wayl API key by contacting %1$s or via WhatsApp %2$s. This key is required to process payments.', 'wayl-checkout' ),
					'<a href="mailto:support@wayl.io">support@wayl.io</a>',
					'<a href="https://wa.me/9647752277781" target="_blank" rel="noopener noreferrer">+964 775 227 7781</a>'
				),
				'desc_tip'    => false,
			),
			'lang'          => array(
				'title'       => __( 'Payment Page Language', 'wayl-checkout' ),
				'type'        => 'select',
				'options'     => array(
					'store' => __( 'Store Language', 'wayl-checkout' ),
					'ar'    => __( 'Arabic', 'wayl-checkout' ),
					'en'    => __( 'English', 'wayl-checkout' ),
				),
				'default'     => 'store',
				'description' => __( 'Choose the language for the Wayl payment page. Default uses your site language.', 'wayl-checkout' ),
				'desc_tip'    => true,
			),
			'currency'      => array(
				'title'       => __( 'Payment Page Currency', 'wayl-checkout' ),
				'type'        => 'select',
				'options'     => array(
					'store' => __( 'Store Currency', 'wayl-checkout' ),
					'iqd'   => __( 'IQD', 'wayl-checkout' ),
					'usd'   => __( 'USD', 'wayl-checkout' ),
				),
				'default'     => 'store',
				'description' => __( 'Choose the currency for the Wayl payment page. Default uses your store currency.', 'wayl-checkout' ),
				'desc_tip'    => true,
			),
			'exchange_rate' => array(
				'title'       => __( 'USD to IQD Exchange Rate', 'wayl-checkout' ),
				'type'        => 'number',
				'description' => __( 'Exchange rate for converting USD to IQD. All payments will be converted to IQD.', 'wayl-checkout' ),
				'default'     => '1320',
				'desc_tip'    => true,
				'custom_attributes' => array(
					'step' => '0.01',
					'min'  => '0.01',
				),
			),
			'logging'       => array(
				'title'       => __( 'Enable Logging', 'wayl-checkout' ),
				'type'        => 'checkbox',
				'label'       => __( 'Log API requests and responses', 'wayl-checkout' ),
				'default'     => 'no',
				'description' => __( 'Log Wayl API requests and responses for debugging purposes. Logging is disabled by default.', 'wayl-checkout' ),
				'desc_tip'    => true,
			),
		);
	}

	/**
	 * Debug method to check current settings
	 *
	 * @return void
	 */
	public function debug_settings() {
		if ( $this->log_enabled ) {
			WaylCHP_Logger::info( '=== Wayl Plugin Debug Info ===' );
			WaylCHP_Logger::info( 'API Key: ' . ( empty( $this->api_key ) ? 'NOT SET' : 'SET' ) );
			// Webhook secret is not logged for security reasons
			WaylCHP_Logger::info( 'Language Setting: ' . $this->lang );
			WaylCHP_Logger::info( 'Currency Setting: ' . $this->currency );
			WaylCHP_Logger::info( 'Exchange Rate: ' . $this->exchange_rate );
			WaylCHP_Logger::info( 'Logging Enabled: ' . ( $this->log_enabled ? 'YES' : 'NO' ) );
			WaylCHP_Logger::info( 'Site Currency: ' . get_woocommerce_currency() );
			WaylCHP_Logger::info( 'Site Language: ' . get_locale() );
			WaylCHP_Logger::info( 'Final Payment Language: ' . $this->get_payment_language() );
			WaylCHP_Logger::info( 'Final Payment Currency: ' . $this->get_payment_currency() );
			WaylCHP_Logger::info( '=== End Debug Info ===' );
		}
	}

	/**
	 * Get the final language value for the payment URL
	 *
	 * @return string Language code
	 */
	private function get_payment_language() {
		if ( $this->lang === 'store' ) {
			// Get WordPress site language
			$site_language = get_locale();
			// Convert to language code (e.g., 'ar' for Arabic, 'en' for English)
			if ( strpos( $site_language, 'ar' ) === 0 ) {
				return 'ar';
			} else {
				return 'en';
			}
		}
		return $this->lang;
	}

	/**
	 * Get the final currency value for the payment URL
	 *
	 * @return string Currency code
	 */
	private function get_payment_currency() {
		if ( $this->currency === 'store' ) {
			// Get WooCommerce site currency
			$site_currency = get_woocommerce_currency();
			// Convert to lowercase for consistency
			return strtolower( $site_currency );
		}
		return $this->currency;
	}

	/**
	 * Get the default title based on site language
	 *
	 * @return string Default title
	 */
	private function get_default_title() {
		// Get WordPress site language
		$site_language = get_locale();
		
		// Check if site language is Arabic
		if ( strpos( $site_language, 'ar' ) === 0 ) {
			return 'Wayl - إدفع الكترونياً';
		}
		
		// Default to English
		return 'Wayl - Pay Online';
	}

	/**
	 * Process the payment and return the result
	 *
	 * @param int $order_id Order ID
	 * @return array Payment result
	 */
	public function process_payment( $order_id ) {
		$order = wc_get_order( $order_id );

		if ( ! $order || ! is_a( $order, 'WC_Order' ) ) {
			if ( $this->log_enabled ) {
				WaylCHP_Logger::error( 'Invalid order ID: ' . $order_id );
			}
			wc_add_notice( __( 'Invalid order. Please try again.', 'wayl-checkout' ), 'error' );
			return array( 'result' => 'failure' );
		}

		if ( $order->get_status() !== 'pending' ) {
			return array( 'result' => 'success', 'redirect' => $order->get_checkout_payment_url() );
		}

		// Debug settings
		$this->debug_settings();

		// Log the start of payment processing
		if ( $this->log_enabled ) {
			WaylCHP_Logger::info( 'Starting Wayl payment process for order: ' . $order_id );

			// Log original WooCommerce order breakdown
			WaylCHP_Logger::debug( '=== Original WooCommerce Order Breakdown ===' );
			WaylCHP_Logger::debug( 'Order ID: ' . $order_id );
			WaylCHP_Logger::debug( 'Order Status: ' . $order->get_status() );
			WaylCHP_Logger::debug( 'Order Total: ' . $order->get_total() . ' ' . get_woocommerce_currency() );
			WaylCHP_Logger::debug( 'Order Subtotal: ' . $order->get_subtotal() . ' ' . get_woocommerce_currency() );
			WaylCHP_Logger::debug( 'Shipping Total: ' . $order->get_shipping_total() . ' ' . get_woocommerce_currency() );
			WaylCHP_Logger::debug( 'Tax Total: ' . $order->get_total_tax() . ' ' . get_woocommerce_currency() );
			WaylCHP_Logger::debug( 'Discount Total: ' . $order->get_total_discount() . ' ' . get_woocommerce_currency() );
			WaylCHP_Logger::debug( 'Fees Total: ' . $order->get_total_fees() . ' ' . get_woocommerce_currency() );

			// Log original product items
			WaylCHP_Logger::debug( '=== Original Product Items ===' );
			foreach ( $order->get_items() as $item ) {
				$product = $item->get_product();
				WaylCHP_Logger::debug( 'Product: ' . $item->get_name() );
				WaylCHP_Logger::debug( '  - Quantity: ' . $item->get_quantity() );
				WaylCHP_Logger::debug( '  - Unit Price: ' . $item->get_subtotal() / $item->get_quantity() . ' ' . get_woocommerce_currency() );
				WaylCHP_Logger::debug( '  - Subtotal: ' . $item->get_subtotal() . ' ' . get_woocommerce_currency() );
				WaylCHP_Logger::debug( '  - Total (after discount): ' . $item->get_total() . ' ' . get_woocommerce_currency() );
				WaylCHP_Logger::debug( '  - Discount: ' . ( $item->get_subtotal() - $item->get_total() ) . ' ' . get_woocommerce_currency() );
			}

			// Log original fees
			$fees = $order->get_fees();
			if ( ! empty( $fees ) ) {
				WaylCHP_Logger::debug( '=== Original Fees ===' );
				foreach ( $fees as $fee ) {
					WaylCHP_Logger::debug( 'Fee: ' . $fee->get_name() . ' - Amount: ' . $fee->get_total() . ' ' . get_woocommerce_currency() );
				}
			}

			WaylCHP_Logger::debug( '=== End Original Order Breakdown ===' );
		}

		$items          = array();
		$site_currency  = get_woocommerce_currency();
		$exchange_rate  = floatval( $this->exchange_rate );
		$total_amount   = 0; // Track the total from line items
		$currency       = 'IQD'; // Always use IQD

		// Validate currency - only USD and IQD are supported
		if ( $site_currency !== 'USD' && $site_currency !== 'IQD' ) {
			wc_add_notice( __( 'Wayl only supports USD or IQD as site currency.', 'wayl-checkout' ), 'error' );
			if ( $this->log_enabled ) {
				WaylCHP_Logger::error( 'Currency error: Site currency is ' . $site_currency . ' but Wayl only supports USD or IQD' );
			}
			return array( 'result' => 'failure' );
		}

		// Validate exchange rate
		if ( $exchange_rate <= 0 ) {
			wc_add_notice( __( 'Invalid exchange rate configured. Please check your settings.', 'wayl-checkout' ), 'error' );
			if ( $this->log_enabled ) {
				WaylCHP_Logger::error( 'Exchange rate error: Rate is ' . $exchange_rate );
			}
			return array( 'result' => 'failure' );
		}

		// Add product line items (using original prices before discount)
		foreach ( $order->get_items() as $item ) {
			$product = $item->get_product();
			// Use subtotal (original price) instead of total (discounted price)
			$price = $item->get_subtotal();

			// Convert to IQD if site currency is USD
			if ( $site_currency === 'USD' ) {
				$price *= $exchange_rate;
			}

			$item_amount  = intval( round( $price ) );
			$total_amount += $item_amount;

			$items[] = array(
				'label'  => sanitize_text_field( $item->get_name() ),
				'amount' => $item_amount,
				'type'   => 'increase',
				'image'  => $product && $product->get_image_id() ? esc_url_raw( wp_get_attachment_url( $product->get_image_id() ) ) : '',
			);
		}

		// Add shipping costs
		$shipping_total = $order->get_shipping_total();
		if ( $shipping_total > 0 ) {
			// Convert to IQD if site currency is USD
			if ( $site_currency === 'USD' ) {
				$shipping_total *= $exchange_rate;
			}

			$shipping_amount = intval( round( $shipping_total ) );
			$total_amount   += $shipping_amount;

			$items[] = array(
				'label'  => 'Shipping',
				'amount' => $shipping_amount,
				'type'   => 'increase',
				'image'  => '',
			);
		}

		// Add tax costs
		$tax_total = $order->get_total_tax();
		if ( $tax_total > 0 ) {
			// Convert to IQD if site currency is USD
			if ( $site_currency === 'USD' ) {
				$tax_total *= $exchange_rate;
			}

			$tax_amount   = intval( round( $tax_total ) );
			$total_amount += $tax_amount;

			$items[] = array(
				'label'  => 'Tax',
				'amount' => $tax_amount,
				'type'   => 'increase',
				'image'  => '',
			);
		}

		// Add fees
		$fees = $order->get_fees();
		if ( ! empty( $fees ) ) {
			foreach ( $fees as $fee ) {
				$fee_total = $fee->get_total();
				if ( $fee_total != 0 ) {
					// Convert to IQD if site currency is USD
					if ( $site_currency === 'USD' ) {
						$fee_total *= $exchange_rate;
					}

					$fee_amount   = intval( round( $fee_total ) );
					$total_amount += $fee_amount;

					$items[] = array(
						'label'  => sanitize_text_field( $fee->get_name() ),
						'amount' => $fee_amount,
						'type'   => $fee_total > 0 ? 'increase' : 'decrease',
						'image'  => '',
					);
				}
			}
		}

		// Add discounts (as a separate line item)
		$discount_total = $order->get_total_discount();
		if ( $discount_total > 0 ) {
			// Convert to IQD if site currency is USD
			if ( $site_currency === 'USD' ) {
				$discount_total *= $exchange_rate;
			}

			$discount_amount = intval( round( $discount_total ) );
			$total_amount   -= $discount_amount; // Subtract discount

			$items[] = array(
				'label'  => 'Discount',
				'amount' => $discount_amount,
				'type'   => 'decrease',
				'image'  => '',
			);
		}

		// Use the calculated total from line items instead of order total
		$total = $total_amount;

		// Log the calculation for debugging
		if ( $this->log_enabled ) {
			WaylCHP_Logger::debug( '=== Wayl API Order Components Breakdown ===' );
			WaylCHP_Logger::debug( 'Original Order Total: ' . $order->get_total() . ' ' . get_woocommerce_currency() );
			WaylCHP_Logger::debug( 'Subtotal: ' . $order->get_subtotal() . ' ' . get_woocommerce_currency() );
			WaylCHP_Logger::debug( 'Shipping: ' . $order->get_shipping_total() . ' ' . get_woocommerce_currency() );
			WaylCHP_Logger::debug( 'Tax: ' . $order->get_total_tax() . ' ' . get_woocommerce_currency() );
			WaylCHP_Logger::debug( 'Discount: ' . $order->get_total_discount() . ' ' . get_woocommerce_currency() );
			WaylCHP_Logger::debug( 'Fees: ' . $order->get_total_fees() . ' ' . get_woocommerce_currency() );
			WaylCHP_Logger::debug( 'Calculated Total: ' . $total_amount . ' IQD' );
			WaylCHP_Logger::debug( 'Final Total: ' . $total . ' IQD' );
			WaylCHP_Logger::debug( '=== End Wayl API Breakdown ===' );
		}

		$ref_id   = 'waylchp_' . $order->get_id() . '_' . time();
		$callback = add_query_arg( 'wc-api', 'waylchp_webhook', home_url() );

		// Store reference ID in order meta for refunds
		$order->update_meta_data( 'waylchp_reference_id', sanitize_text_field( $ref_id ) );
		$order->save_meta_data();

		// Validate that we have items
		if ( empty( $items ) ) {
			if ( $this->log_enabled ) {
				WaylCHP_Logger::error( 'No items found for order: ' . $order_id );
			}
			wc_add_notice( __( 'No items found in order.', 'wayl-checkout' ), 'error' );
			return array( 'result' => 'failure' );
		}

		// Log items for debugging
		if ( $this->log_enabled ) {
			WaylCHP_Logger::debug( 'Order items structure: ' . wp_json_encode( $items ) );
		}

		// Validate total amount
		if ( $total <= 0 ) {
			if ( $this->log_enabled ) {
				WaylCHP_Logger::error( 'Invalid total amount for order: ' . $order_id . ' - Total: ' . $total );
			}
			wc_add_notice( __( 'Invalid order total.', 'wayl-checkout' ), 'error' );
			return array( 'result' => 'failure' );
		}

		$body = array(
			'referenceId'    => sanitize_text_field( $ref_id ),
			'total'          => intval( round( $total ) ),
			'currency'       => 'IQD',
			'lineItem'        => $items,
			'webhookUrl'      => esc_url_raw( $callback ),
			'webhookSecret'   => sanitize_text_field( $this->webhook_secret ),
			'redirectionUrl'  => esc_url_raw( $order->get_checkout_order_received_url() ),
		);

		if ( $this->lang ) {
			$body['lang'] = sanitize_text_field( $this->lang );
		}

		// Use the Wayl API class
		$api = new WaylCHP_API( $this->api_key );

		// Log the request payload for debugging
		if ( $this->log_enabled ) {
			WaylCHP_Logger::debug( 'Wayl API Request Payload: ' . wp_json_encode( $body ) );
		}

		$response = $api->create_checkout_link( $body );

		if ( ! $response ) {
			if ( $this->log_enabled ) {
				WaylCHP_Logger::error( 'Failed to create Wayl checkout link for order: ' . $order_id );
			}
			wc_add_notice( __( 'Could not connect to Wayl. Please try again later.', 'wayl-checkout' ), 'error' );
			return array( 'result' => 'failure' );
		}

		// Check for payment URL in the response
		$payment_url = null;
		if ( isset( $response['data']['url'] ) ) {
			$payment_url = esc_url_raw( $response['data']['url'] );
		} elseif ( isset( $response['paymentLink'] ) ) {
			$payment_url = esc_url_raw( $response['paymentLink'] );
		}

		if ( $payment_url ) {
			if ( $this->log_enabled ) {
				WaylCHP_Logger::info( 'Wayl payment session created successfully for order: ' . $order_id . ' - URL: ' . $payment_url );
			}

			// Add query parameters to the payment URL
			$final_lang     = sanitize_text_field( $this->get_payment_language() );
			$final_currency = sanitize_text_field( $this->get_payment_currency() );

			$payment_url = add_query_arg(
				array(
					'lang'     => $final_lang,
					'currency' => $final_currency,
				),
				$payment_url
			);

			if ( $this->log_enabled ) {
				WaylCHP_Logger::debug( 'Payment URL with parameters: ' . $payment_url );
				WaylCHP_Logger::debug( 'Language: ' . $final_lang . ', Currency: ' . $final_currency );
			}

			$order->add_order_note( esc_html__( 'Wayl payment session started at', 'wayl-checkout' ) . ' ' . current_time( 'mysql' ) );
			return array( 'result' => 'success', 'redirect' => esc_url_raw( $payment_url ) );
		} else {
			if ( $this->log_enabled ) {
				WaylCHP_Logger::error( 'Wayl API did not return payment URL. Response: ' . wp_json_encode( $response ) );
			}
			wc_add_notice( __( 'Failed to initiate payment session with Wayl.', 'wayl-checkout' ), 'error' );
			return array( 'result' => 'failure' );
		}
	}

	/**
	 * Process refund
	 *
	 * @param int    $order_id Order ID
	 * @param float  $amount Refund amount (ignored - always uses full order amount)
	 * @param string $reason Refund reason
	 * @return bool|WP_Error True on success, WP_Error on failure
	 */
	public function process_refund( $order_id, $amount = null, $reason = '' ) {
		$order = wc_get_order( $order_id );

		if ( ! $order || ! is_a( $order, 'WC_Order' ) ) {
			if ( $this->log_enabled ) {
				WaylCHP_Logger::error( 'Invalid order ID for refund: ' . $order_id );
			}
			return new WP_Error( 'invalid_order', __( 'Invalid order.', 'wayl-checkout' ) );
		}

		// Check if order was paid with Wayl
		if ( $order->get_payment_method() !== $this->id ) {
			if ( $this->log_enabled ) {
				WaylCHP_Logger::error( 'Order ' . $order_id . ' was not paid with Wayl payment method' );
			}
			return new WP_Error( 'invalid_payment_method', __( 'Order was not paid with Wayl.', 'wayl-checkout' ) );
		}

		// Get the original reference ID from order meta (the one sent to Wayl during payment)
		$reference_id = $order->get_meta( 'waylchp_reference_id' );
		if ( empty( $reference_id ) ) {
			WaylCHP_Logger::error( 'Reference ID not found for order: ' . $order_id, true );
			return new WP_Error( 'missing_reference_id', __( 'Reference ID not found. Cannot process refund.', 'wayl-checkout' ) );
		}

		// Validate refund reason length (MUST be 100 characters or less)
		$reason_length = mb_strlen( $reason, 'UTF-8' );
		if ( $reason_length > 100 ) {
			WaylCHP_Logger::error( 'Refund reason exceeds 100 characters: ' . $reason_length . ' chars', true );
			return new WP_Error( 'refund_reason_too_long', __( 'Refund reason must be 100 characters or less. Current length: ', 'wayl-checkout' ) . $reason_length );
		}

		// Always use the full order amount (as per Wayl API requirement)
		// Ignore the $amount parameter - Wayl only supports full refunds
		$order_total = $order->get_total();

		// Convert order total to IQD if needed (same conversion as payment)
		$site_currency = get_woocommerce_currency();
		$exchange_rate = floatval( $this->exchange_rate );
		$order_total_iqd = floatval( $order_total );

		if ( $site_currency === 'USD' ) {
			$order_total_iqd *= $exchange_rate;
		}

		$refund_amount_iqd = intval( round( $order_total_iqd ) );

		// Always log refund attempts (even if general logging is disabled) - CRITICAL OPERATION
		WaylCHP_Logger::info( '=== REFUND ATTEMPT START ===', true );
		WaylCHP_Logger::info( 'Order ID: ' . $order_id, true );
		WaylCHP_Logger::info( 'Reference ID: ' . $reference_id, true );
		WaylCHP_Logger::info( 'Order Total: ' . $order_total . ' ' . $site_currency, true );
		WaylCHP_Logger::info( 'Refund Amount (IQD): ' . $refund_amount_iqd . ' (FULL AMOUNT - always)', true );
		WaylCHP_Logger::info( 'Refund Reason Length: ' . $reason_length . ' / 100 characters', true );
		WaylCHP_Logger::info( 'Refund Reason: ' . ( ! empty( $reason ) ? $reason : '(empty)' ), true );
		WaylCHP_Logger::info( 'API Key: ' . ( ! empty( $this->api_key ) ? 'SET' : 'NOT SET' ), true );

		// Call Wayl API to process refund
		$api      = new WaylCHP_API( $this->api_key );
		$response = $api->process_refund( $reference_id, $refund_amount_iqd, $reason );

		if ( ! $response ) {
			WaylCHP_Logger::error( '=== REFUND FAILED ===', true );
			WaylCHP_Logger::error( 'Order ID: ' . $order_id, true );
			WaylCHP_Logger::error( 'Reference ID: ' . $reference_id, true );
			WaylCHP_Logger::error( 'Check API logs above for detailed error information', true );
			return new WP_Error( 'refund_failed', __( 'Refund request failed. Please check logs or contact support.', 'wayl-checkout' ) );
		}

		WaylCHP_Logger::info( '=== REFUND API RESPONSE RECEIVED ===', true );
		WaylCHP_Logger::debug( 'Response: ' . wp_json_encode( $response ), true );

		// Extract refund transaction ID from response
		$refund_transaction_id = '';
		if ( isset( $response['data']['refundId'] ) ) {
			$refund_transaction_id = sanitize_text_field( $response['data']['refundId'] );
		} elseif ( isset( $response['refundId'] ) ) {
			$refund_transaction_id = sanitize_text_field( $response['refundId'] );
		} elseif ( isset( $response['data']['transactionId'] ) ) {
			$refund_transaction_id = sanitize_text_field( $response['data']['transactionId'] );
		}

		// Store refund information in order meta
		$order->update_meta_data( 'waylchp_refund_id', $refund_transaction_id );
		$order->update_meta_data( 'waylchp_refund_amount', $refund_amount_iqd );
		$order->update_meta_data( 'waylchp_refund_reason', sanitize_text_field( $reason ) );
		$order->save_meta_data();

		// Add order note
		$order_note = sprintf(
			/* translators: 1: Refund amount, 2: Currency, 3: Refund transaction ID */
			__( 'Refund processed via Wayl: %1$s %2$s. Refund ID: %3$s', 'wayl-checkout' ),
			number_format( $order_total, 2 ),
			$site_currency,
			$refund_transaction_id ? $refund_transaction_id : __( 'Pending', 'wayl-checkout' )
		);
		if ( ! empty( $reason ) ) {
			$order_note .= ' - ' . esc_html( $reason );
		}
		$order->add_order_note( $order_note );

		if ( $this->log_enabled ) {
			WaylCHP_Logger::info( 'Refund processed successfully for order: ' . $order_id . ' - Refund ID: ' . $refund_transaction_id );
		}

		return true;
	}

	/**
	 * Display Wayl logo in order details (frontend)
	 *
	 * @param WC_Order $order Order object
	 * @return void
	 */
	public function display_wayl_logo_in_order( $order ) {
		if ( ! $order || ! is_a( $order, 'WC_Order' ) ) {
			return;
		}

		if ( $order->get_payment_method() !== $this->id ) {
			return;
		}

		$logo_url = $this->get_wayl_logo_url();
		if ( $logo_url ) {
			echo '<div class="waylchp-order-logo" style="margin-top: 10px;">';
			echo '<img src="' . esc_url( $logo_url ) . '" alt="' . esc_attr__( 'Wayl', 'wayl-checkout' ) . '" style="max-height: 30px; width: auto;" />';
			echo '</div>';
		}
	}

	/**
	 * Display Wayl logo in admin order details
	 *
	 * @param WC_Order $order Order object
	 * @return void
	 */
	public function display_wayl_logo_in_admin( $order ) {
		if ( ! $order || ! is_a( $order, 'WC_Order' ) ) {
			return;
		}

		if ( $order->get_payment_method() !== $this->id ) {
			return;
		}

		$logo_url = $this->get_wayl_logo_url();
		if ( $logo_url ) {
			echo '<div class="waylchp-admin-order-logo" style="margin-top: 10px; padding: 10px; background: #f9f9f9; border: 1px solid #ddd; border-radius: 4px;">';
			echo '<strong>' . esc_html__( 'Payment Method:', 'wayl-checkout' ) . '</strong><br />';
			echo '<img src="' . esc_url( $logo_url ) . '" alt="' . esc_attr__( 'Wayl', 'wayl-checkout' ) . '" style="max-height: 30px; width: auto; margin-top: 5px;" />';
			
			// Display reference ID if available
			$reference_id = $order->get_meta( 'waylchp_reference_id' );
			if ( $reference_id ) {
				echo '<br /><small>' . esc_html__( 'Reference ID:', 'wayl-checkout' ) . ' ' . esc_html( $reference_id ) . '</small>';
			}
			echo '</div>';
		}
	}
}

