<?php

namespace DigitalApps\PaymentsForAdyen;

defined('ABSPATH') || exit;

/**
 * Adyen Payment Method Status Checker
 * 
 * This class handles checking the status of payment methods in Adyen
 * and provides utilities for displaying status information in the admin.
 */
class Adyen_Payment_Method_Status
{
	/**
	 * Mapping of WooCommerce gateway IDs to Adyen payment method types
	 */
	const PAYMENT_METHOD_MAPPING = [
		'digitalapps_payments_for_adyen_card' => 'scheme',
		'digitalapps_payments_for_adyen_ideal' => 'ideal',
		'digitalapps_payments_for_adyen_paypal' => 'paypal',
		'digitalapps_payments_for_adyen_googlepay' => 'googlepay',
		'digitalapps_payments_for_adyen_bcmc' => 'bcmc',
		'digitalapps_payments_for_adyen_sepa' => 'sepadirectdebit',
		'digitalapps_payments_for_adyen_sofort' => 'directEbanking',
		'digitalapps_payments_for_adyen_alipay' => 'alipay',
		'digitalapps_payments_for_adyen_wechatpay' => 'wechatpay',
		'digitalapps_payments_for_adyen_klarna' => 'klarna',
		'digitalapps_payments_for_adyen_afterpay' => 'afterpay_default',
		'digitalapps_payments_for_adyen_pix' => 'pix',
	];

	/**
	 * Display names for payment methods
	 */
	const PAYMENT_METHOD_NAMES = [
		'digitalapps_payments_for_adyen_card' => 'Credit/Debit Cards',
		'digitalapps_payments_for_adyen_ideal' => 'iDEAL',
		'digitalapps_payments_for_adyen_paypal' => 'PayPal',
		'digitalapps_payments_for_adyen_googlepay' => 'Google Pay',
		'digitalapps_payments_for_adyen_bcmc' => 'Bancontact',
		'digitalapps_payments_for_adyen_sepa' => 'SEPA Direct Debit',
		'digitalapps_payments_for_adyen_sofort' => 'Sofort',
		'digitalapps_payments_for_adyen_alipay' => 'Alipay',
		'digitalapps_payments_for_adyen_wechatpay' => 'WeChat Pay',
		'digitalapps_payments_for_adyen_klarna' => 'Klarna',
		'digitalapps_payments_for_adyen_afterpay' => 'Afterpay',
		'digitalapps_payments_for_adyen_pix' => 'PIX',
	];

	/**
	 * Cache for payment methods to avoid multiple API calls
	 */
	private static $payment_methods_cache = null;
	private static $payment_methods_result_cache = null;
	private static $cache_expiry = null;

	/**
	 * Check if Adyen API credentials are configured
	 *
	 * @return bool
	 */
	public static function are_credentials_configured()
	{
		$settings = get_option('digitalapps_payments_for_adyen_settings', []);
		return !empty($settings['apiKey']) && !empty($settings['merchantAccount']);
	}

	/**
	 * Get available payment methods from Adyen with caching
	 *
	 * @return array|null Returns null if credentials are not configured
	 */
	public static function get_available_payment_methods()
	{
		// Check if credentials are configured
		if (!self::are_credentials_configured()) {
			return null;
		}

		// Check if cache is still valid (5 minutes)
		if (self::$payment_methods_cache !== null && self::$cache_expiry > time()) {
			return self::$payment_methods_cache;
		}

		$client = new Adyen_Client();
		$result = $client->get_payment_methods_result();
		$methods = !empty($result['success']) ? $result['paymentMethods'] : [];

		// Cache the results for 5 minutes
		self::$payment_methods_cache = $methods;
		self::$payment_methods_result_cache = $result;
		self::$cache_expiry = time() + 300; // 5 minutes

		return $methods;
	}

	/**
	 * Check if a specific payment method is enabled in Adyen
	 *
	 * @param string $gateway_id WooCommerce gateway ID (e.g., 'digitalapps_payments_for_adyen_card')
	 * @return bool
	 */
	public static function is_method_enabled_in_adyen($gateway_id)
	{
		if (!isset(self::PAYMENT_METHOD_MAPPING[$gateway_id])) {
			return false;
		}

		$adyen_type = self::PAYMENT_METHOD_MAPPING[$gateway_id];
		$methods = self::get_available_payment_methods();

		// If methods is null (credentials not configured), return false
		if ($methods === null) {
			return false;
		}

		foreach ($methods as $method) {
			if ($method['type'] === $adyen_type) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Get the display name for a payment method
	 *
	 * @param string $gateway_id WooCommerce gateway ID
	 * @return string
	 */
	public static function get_method_display_name($gateway_id)
	{
		return self::PAYMENT_METHOD_NAMES[$gateway_id]
			?? ucfirst(str_replace(['digitalapps_payments_for_adyen_', '_'], ['', ' '], $gateway_id));
	}

	/**
	 * Get the Adyen payment method type for a gateway
	 *
	 * @param string $gateway_id WooCommerce gateway ID
	 * @return string|null
	 */
	public static function get_adyen_method_type($gateway_id)
	{
		return self::PAYMENT_METHOD_MAPPING[$gateway_id] ?? null;
	}

	/**
	 * Get status information for a payment method
	 *
	 * @param string $gateway_id WooCommerce gateway ID
	 * @return array
	 */
	public static function get_method_status_info($gateway_id)
	{
		$display_name = self::get_method_display_name($gateway_id);
		$adyen_type = self::get_adyen_method_type($gateway_id);

		// Check if credentials are configured first
		if (!self::are_credentials_configured()) {
			return [
				'enabled' => false,
				'credentials_missing' => true,
				'display_name' => $display_name,
				'adyen_type' => $adyen_type,
				/* translators: %s: Payment method name. */
				'status_message' => sprintf(__('Adyen API credentials are not configured. Please set your credentials to check %s status.', 'digital-apps-payments-for-adyen'), $display_name),
				'status_class' => 'digitalapps-payments-for-adyen-status-credentials-missing'
			];
		}

		// Credentials are configured, check if method is enabled.
		self::get_available_payment_methods();
		$result = self::$payment_methods_result_cache;
		if (!is_array($result) || empty($result['success'])) {
			return [
				'enabled' => false,
				'credentials_missing' => false,
				'verification_error' => true,
				'display_name' => $display_name,
				'adyen_type' => $adyen_type,
				'status_message' => __('Adyen could not verify this payment method. Check the merchant account and API key, then use Verify connection in the plugin settings.', 'digital-apps-payments-for-adyen'),
				'status_class' => 'digitalapps-payments-for-adyen-status-verification-error',
			];
		}

		$is_enabled = self::is_method_enabled_in_adyen($gateway_id);

		return [
			'enabled' => $is_enabled,
			'credentials_missing' => false,
			'verification_error' => false,
			'display_name' => $display_name,
			'adyen_type' => $adyen_type,
			'status_message' => $is_enabled
				/* translators: %s: Payment method name. */
				? sprintf(__('%s is enabled in your Adyen account.', 'digital-apps-payments-for-adyen'), $display_name)
				/* translators: %s: Payment method name. */
				: sprintf(__('%s was not returned by Adyen for this merchant account. Check the merchant account and payment method configuration in the Adyen Customer Area.', 'digital-apps-payments-for-adyen'), $display_name),
			'status_class' => $is_enabled ? 'digitalapps-payments-for-adyen-status-enabled' : 'digitalapps-payments-for-adyen-status-disabled'
		];
	}

	/**
	 * Get all payment methods status
	 *
	 * @return array
	 */
	public static function get_all_methods_status()
	{
		$status = [];
		foreach (array_keys(self::PAYMENT_METHOD_MAPPING) as $gateway_id) {
			$status[$gateway_id] = self::get_method_status_info($gateway_id);
		}
		return $status;
	}

	/**
	 * Clear the payment methods cache
	 */
	public static function clear_cache()
	{
		self::$payment_methods_cache = null;
		self::$payment_methods_result_cache = null;
		self::$cache_expiry = null;
	}

	/**
	 * Get formatted status HTML for admin display
	 *
	 * @param string $gateway_id WooCommerce gateway ID
	 * @return string
	 */
	public static function get_status_html($gateway_id)
	{
		$status = self::get_method_status_info($gateway_id);

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

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