<?php

namespace DigitalApps\PaymentsForAdyen\Gateways;

use DigitalApps\PaymentsForAdyen\Adyen_Payment_Method_Status;

defined('ABSPATH') || exit;

/**
 * Utility class for common Adyen gateway functionality
 */
class Adyen_Gateway_Utils
{
	/**
	 * Display generic Adyen status notice for payment methods not enabled in Adyen account
	 *
	 * @param \WC_Payment_Gateway $gateway The gateway instance
	 * @param string $payment_method_name The display name of the payment method (e.g., 'Card', 'PayPal', 'Apple Pay')
	 * @param bool $check_screen_context Whether to check if we're on the WooCommerce settings page
	 */
	public static function display_adyen_status_notice($gateway, $payment_method_name = null, $check_screen_context = false)
	{
		// Only show notice on WooCommerce settings page for payment gateways if requested
		if ($check_screen_context) {
			$screen = get_current_screen();
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only screen routing parameter.
			$tab = isset($_GET['tab']) ? sanitize_key(wp_unslash($_GET['tab'])) : '';
			if (!$screen || $screen->id !== 'woocommerce_page_wc-settings' || 'checkout' !== $tab) {
				return;
			}
		}

		if ('yes' === $gateway->enabled && !$gateway->is_available()) {
			$message = $payment_method_name
				/* translators: %s: Payment method name. */
				? sprintf(__('%s is not enabled or configured correctly in your Adyen account. Please check your Adyen Customer Area.', 'digital-apps-payments-for-adyen'), $payment_method_name)
				: __('This payment method is not enabled or configured correctly in your Adyen account. Please check your Adyen Customer Area.', 'digital-apps-payments-for-adyen');

			echo '<div class="notice notice-error"><p>' . esc_html($message) . '</p></div>';
		}
	}

	/**
	 * Display generic Adyen API credentials notice for payment methods with missing credentials
	 *
	 * @param \WC_Payment_Gateway $gateway The gateway instance
	 * @param string $payment_method_name The display name of the payment method (e.g., 'Alipay', 'WeChat Pay')
	 */
	public static function display_adyen_credentials_notice($gateway, $payment_method_name = null)
	{
		if ('yes' === $gateway->enabled) {
			$settings = get_option('digitalapps_payments_for_adyen_settings', []);
			if (empty($settings['apiKey']) || empty($settings['merchantAccount'])) {
				$message = $payment_method_name
					/* translators: %s: Payment method name. */
					? sprintf(__('%s is enabled but Adyen API credentials are not configured. Please check your Adyen Customer Area.', 'digital-apps-payments-for-adyen'), $payment_method_name)
					: __('This payment method is enabled but Adyen API credentials are not configured. Please check your Adyen Customer Area.', 'digital-apps-payments-for-adyen');

				echo '<div class="notice notice-error"><p>' . esc_html($message) . '</p></div>';
			}
		}
	}

	/**
	 * Get enhanced status information for a payment method
	 *
	 * @param string $gateway_id WooCommerce gateway ID
	 * @return array
	 */
	public static function get_payment_method_status($gateway_id)
	{
		return Adyen_Payment_Method_Status::get_method_status_info($gateway_id);
	}

	/**
	 * Display enhanced Adyen status notice with detailed information
	 *
	 * @param \WC_Payment_Gateway $gateway The gateway instance
	 * @param bool $check_screen_context Whether to check if we're on the WooCommerce settings page
	 */
	public static function display_enhanced_adyen_status_notice($gateway, $check_screen_context = true)
	{
		// Only show notice on WooCommerce settings page for payment gateways if requested
		if ($check_screen_context) {
			$screen = get_current_screen();
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only screen routing parameter.
			$tab = isset($_GET['tab']) ? sanitize_key(wp_unslash($_GET['tab'])) : '';
			if (!$screen || $screen->id !== 'woocommerce_page_wc-settings' || 'checkout' !== $tab) {
				return;
			}

			// Only show on the specific gateway's settings page
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only screen routing parameter.
			$section = isset($_GET['section']) ? sanitize_key(wp_unslash($_GET['section'])) : '';
			if ($section !== $gateway->id) {
				return;
			}
		}

		// Get status information
		$status = self::get_payment_method_status($gateway->id);

		if ($status) {
			// Handle different status states
			if ($status['credentials_missing']) {
				$notice_class = 'notice-warning';
				$icon = '⚠️';
				$additional_message = __('Configure your Adyen API credentials in the main Adyen settings to check payment method availability.', 'digital-apps-payments-for-adyen');
			} elseif (!empty($status['verification_error'])) {
				$notice_class = 'notice-warning';
				$icon = '⚠️';
				$additional_message = __('The gateway has not been disabled by this check. Correct the settings and verify the connection before taking payments.', 'digital-apps-payments-for-adyen');
			} elseif ($status['enabled']) {
				$notice_class = 'notice-success';
				$icon = '✅';
				$additional_message = '';
			} else {
				$notice_class = 'notice-warning';
				$icon = '❌';
				$additional_message = __('Confirm the selected merchant account and its payment method configuration before accepting payments.', 'digital-apps-payments-for-adyen');
			}

			/* translators: %s: Payment method name. */
			$status_heading = sprintf(__('%s Adyen Status:', 'digital-apps-payments-for-adyen'), $status['display_name']);
			printf(
				'<div class="notice %1$s"><p><strong>%2$s %3$s</strong> %4$s%5$s</p></div>',
				esc_attr($notice_class),
				esc_html($icon),
				esc_html($status_heading),
				esc_html($status['status_message']),
				$additional_message ? '<br><em>' . esc_html($additional_message) . '</em>' : ''
			);
		}
	}

	/**
	 * Add status information to gateway form fields
	 *
	 * @param array $form_fields Existing form fields
	 * @param string $gateway_id WooCommerce gateway ID
	 * @return array Modified form fields
	 */
	public static function add_status_to_form_fields($form_fields, $gateway_id)
	{
		$status = self::get_payment_method_status($gateway_id);

		if ($status && isset($form_fields['enabled'])) {
			// Handle different status states
			if ($status['credentials_missing']) {
				$color = '#ffc107';
				$background = '#fff3cd';
				$icon = '⚠️';
			} elseif (!empty($status['verification_error'])) {
				$color = '#dba617';
				$background = '#fcf9e8';
				$icon = '⚠️';
			} elseif ($status['enabled']) {
				$color = '#28a745';
				$background = '#d4edda';
				$icon = '✅';
			} else {
				$color = '#dc3545';
				$background = '#f8d7da';
				$icon = '❌';
			}

				$status_html = sprintf(
				'<div style="margin-top: 10px; padding: 10px; border-left: 4px solid %s; background: %s;">
					<strong>%s Adyen Status:</strong> %s %s
				</div>',
					esc_attr($color),
					esc_attr($background),
					esc_html($status['display_name']),
					esc_html($icon),
					esc_html($status['status_message'])
			);

			$form_fields['enabled']['description'] = ($form_fields['enabled']['description'] ?? '') . $status_html;
		}

		return $form_fields;
	}
}
