<?php
/**
 * AhaPay Payment Gateway Class
 *
 * @package AhaPay
 * @since 1.0.0
 */

declare(strict_types=1);

if (!defined('ABSPATH')) {
	exit; // Exit if accessed directly
}

use Ahapaybuynowpaylater\Blocks\Ahapaybuynowpaylater_WC_Blocks_Support;
use Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType;
use Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry;


/**
 * Ahapaybuynowpaylater_WC_Gateway Class
 *
 * Handles the AhaPay payment gateway functionality.
 */
class Ahapaybuynowpaylater_WC_Gateway extends WC_Payment_Gateway
{
	/**
	 * Debug mode
	 *
	 * @var string
	 */
	private $debug;

	/**
	 * Environment setting
	 *
	 * @var string
	 */
	private $environment;

	/**
	 * API status
	 *
	 * @var string
	 */
	private $api_status;

	/**
	 * Logger instance
	 *
	 * @var WC_Logger|null
	 */
	private $logger;

	/**
	 * Product label setting
	 *
	 * @var string
	 */
	private $enable_product_label;

	/**
	 * Product label color
	 *
	 * @var string
	 */
	private $product_label_color;

	/**
	 * Product label text
	 *
	 * @var string
	 */
	private $product_label_text;

	/**
	 * Additional CSS entered by the admin for payment fields
	 *
	 * @var string
	 */
	private $additional_css;

	/**
	 * Payment on Product Page setting
	 *
	 * @var string
	 */
	public $enable_product_payment_info;

	/**
	 * Success page setting
	 *
	 * @var string
	 */
	private $success_page;

	/**
	 * Error page setting
	 *
	 * @var string
	 */
	private $error_page;

	/**
	 * Constructor
	 */
	public function __construct()
	{
		// Ensure the old or new class name won't block loading during rename
		if (!class_exists('Ahapaybuynowpaylater_WC_Gateway')) {
			throw new \RuntimeException('AhaPay gateway class not found. Please ensure the AhaPay plugin is installed and activated.');
		}

		$this->setup_properties();
		$this->init_form_fields();
		$this->init_settings();
		$this->load_settings();
		$this->init_hooks();
	}

	/**
	 * Setup gateway properties.
	 */
	private function setup_properties() {
		$this->id = 'ahapaybuynowpaylater';
		$this->has_fields = true;
		$this->method_title = __('AhaPay', 'ahapay-buy-now-pay-later');
		$this->method_description = __('AhaPay Buy Now Pay Later', 'ahapay-buy-now-pay-later');
		$this->supports = array(
			'products',
			'refunds'
		);
	}

	/**
	 * Load settings from options.
	 */
	private function load_settings() {
		$this->title = $this->get_option('title');
		$this->description = $this->get_option('description');
		$this->environment = $this->get_option('environment');
		$this->enabled = $this->get_option('enabled');
		$this->api_status = $this->get_option('api_status');
		$this->debug = $this->get_option('debug');
        $this->enable_product_label = $this->get_option('enable_product_label');
		$this->product_label_color = $this->get_option('product_label_color');
		$this->enable_product_payment_info = $this->get_option('enable_product_payment_info');
        $this->success_page = $this->get_option('success_page');
        $this->error_page = $this->get_option('error_page');
        // Load additional admin-provided CSS for payment fields
        $this->additional_css = $this->get_option('additional_css');
	}

	/**
	 * Initialize hooks.
	 */
	private function init_hooks() {
		add_action(
			'woocommerce_update_options_payment_gateways_' . $this->id,
			array($this, 'process_admin_options')
		);
		add_action('admin_enqueue_scripts', array(__CLASS__, 'enqueue_admin_styles'));
		// Use instance method so we can attach admin-provided inline CSS
		add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_styles'));
	}


	/**
	 * Initialize the gateway.
	 */
	public static function init() {
		if (!class_exists('WC_Payment_Gateway')) {
			return;
		}
		add_action('woocommerce_blocks_loaded', array(__CLASS__, 'ahapay_gateway_block_support'), 0);
	}

	/**
	 * Get plugin URL.
	 *
	 * @return string
	 */
	public static function plugin_url() {
		return untrailingslashit(plugins_url('/', __FILE__));
	}

	/**
	 * Get plugin absolute path.
	 *
	 * @return string
	 */
	public static function plugin_abspath() {
		return trailingslashit(plugin_dir_path(__FILE__));
	}

	/**
	 * Check if gateway is available.
	 *
	 * @return bool
	 */
	public function is_available() {
		// Optionally add checks like currency or shipping methods here
		$currency = get_woocommerce_currency();
		if ( 'MYR' !== $currency && 'RM' !== $currency ) {
			return false;
		}

		return $this->enabled === 'yes';
	}

	/**
	 * Initialize form fields.
	 */

	public function init_form_fields()
	{
		$status_info = $this->get_api_status_info($this->get_option('api_status'));

		$this->form_fields = [
			'enabled' => [
				'title' => __('Enable/Disable', 'ahapay-buy-now-pay-later'),
				'label' => __('Enable AhaPay Payments', 'ahapay-buy-now-pay-later'),
				'type' => 'checkbox',
				'default' => 'no'
			],
			'title' => [
				'title' => __('Title', 'ahapay-buy-now-pay-later'),
				'type' => 'text',
//				'default' => __('AhaPay <img src="' . AHAPAYBUYNOWPAYLATER_PLUGIN_URL . 'assets/images/ahapay-logo.png" alt="AhaPay" style="height: 24px; vertical-align: middle; margin-left: 8px;" class="radio-control-wc-payment-method-options-ahapay__label">', 'ahapay-buy-now-pay-later'),
				'default' => __('AhaPay – 4 easy payments, 0% interest rate', 'ahapay-buy-now-pay-later'),
				'description' => __('This title will be shown with the logo on checkout page.', 'ahapay-buy-now-pay-later'),
				'custom_attributes' => ['readonly' => 'readonly'],
			],


			'description' => [
				'title' => __('Description', 'ahapay-buy-now-pay-later'),
				'type' => 'textarea',
				'default' => __('Pay 25% today and the remaining in 3 monthly payments', 'ahapay-buy-now-pay-later'),
				'custom_attributes' => ['readonly' => 'readonly'],
			],
			'environment' => [
				'title' => __('Environment', 'ahapay-buy-now-pay-later'),
				'type' => 'select',
				'options' => [
					'sandbox' => __('Test', 'ahapay-buy-now-pay-later'),
					'live' => __('Production', 'ahapay-buy-now-pay-later')
				],
				'default' => 'sandbox',
				'desc_tip' => __('Select the environment for AhaPay integration.', 'ahapay-buy-now-pay-later'),
			],
			'api_key' => [
				'title' => __('API Key', 'ahapay-buy-now-pay-later'),
				'type' => 'password',
				'description' => __('Enter your AhaPay API Key', 'ahapay-buy-now-pay-later'),
				'custom_attributes' => ['autocomplete' => 'off'],
				'desc_tip' => true,
			],
			'api_status' => [
				'title' => '',
				'type' => 'title',
				'description' => $this->get_api_status_html($status_info)
			],
			'debug' => [
				'title' => __('Debug Log', 'ahapay-buy-now-pay-later'),
				'type' => 'checkbox',
				'label' => __('Enable logging', 'ahapay-buy-now-pay-later'),
				'default' => 'no',
				'description' => __('Log payment events for debugging purposes', 'ahapay-buy-now-pay-later'),
			],

			'enable_product_payment_info' => [
				'title'       => __('Enable AhaPay info on Product page', 'ahapay-buy-now-pay-later'),
				'type'        => 'checkbox',
				'label'       => __('Show the product is available to purchase via AhaPay on Product pages', 'ahapay-buy-now-pay-later'),
				'default'     => 'no',
			],

			'enable_product_label' => [
				'title'       => __('Enable Product Label/Watermark', 'ahapay-buy-now-pay-later'),
				'type'        => 'checkbox',
				'label'       => __('Show label or watermark on product images', 'ahapay-buy-now-pay-later'),
				'default'     => 'no',
			],

			'product_label_text' => [
				'title'       => __('Product Label Text', 'ahapay-buy-now-pay-later'),
				'type'        => 'text',
				'description' => __('Enter the label text shown on product images. Example: 0% installments with AhaPay', 'ahapay-buy-now-pay-later'),
				'default'     => '0% installments with AhaPay',
			],

            'additional_css' => [
                'title'       => __('Additional CSS for Payment Fields', 'ahapay-buy-now-pay-later'),
                'type'        => 'textarea',
                'description' => __('Enter custom CSS that will be applied to AhaPay payment fields. Example: .ahapay-title { color: #000; }', 'ahapay-buy-now-pay-later'),
                'default'     => '',
                'desc_tip'    => true,
            ],

			'product_label_color' => [
				'title'       => __('Label/Watermark Color', 'ahapay-buy-now-pay-later'),
				'type' => 'color',
				'description' => __('Choose the label color.', 'ahapay-buy-now-pay-later'),
				'default' => '#fc642d',
			],
			'product_label_text_color' => [
				'title'       => __('Label/Watermark Text Color', 'ahapay-buy-now-pay-later'),
				'type' => 'color',
				'description' => __('Choose the label text color.', 'ahapay-buy-now-pay-later'),
				'default' => '#fc642d',
			],
			'success_page' => [
				'title'       => __('Success Page Description', 'ahapay-buy-now-pay-later'),
				'type'        => 'select',
				'description' => __('Select a page to redirect the customer to after successful payment', 'ahapay-buy-now-pay-later'),
				'default'     => '',
				'options'     => $this->get_pages_options(),
			],
			'error_page' => [
				'title'       => __('Error Page Description', 'ahapay-buy-now-pay-later'),
				'type'        => 'select',
				'description' => __('Select a page to redirect the customer to after unsuccessful payment', 'ahapay-buy-now-pay-later'),
				'default'     => '',
				'options'     => $this->get_pages_options(),
			],
		];

	}

	/**
	 * Enqueue admin styles for AhaPay
	 */
	public static function enqueue_admin_styles() {
		wp_enqueue_style(
			'ahapay-admin-css',
			plugins_url('assets/css/ahapay-admin.css', dirname(__FILE__)),
			array(),
           AHAPAYBUYNOWPAYLATER_VERSION
		);
	}
	/**
	 * Enqueue frontend styles for AhaPay
	 */
	public function enqueue_frontend_styles() {
		wp_enqueue_style(
			'ahapaybuynowpaylater-block-style',
			plugins_url('assets/css/ahapaybuynowpaylater-block-style.css', dirname(__FILE__)),
			array(), AHAPAYBUYNOWPAYLATER_VERSION
		);

		// If admin provided additional CSS, append it inline scoped to the gateway stylesheet
		if (!empty($this->additional_css)) {
			// Output the raw CSS saved by admin; it was sanitized with sanitize_textarea_field on save.
			wp_add_inline_style('ahapaybuynowpaylater-block-style', $this->additional_css);
		}
	}

	/**
	 * Add custom CSS for status indicators
	 */
	public function admin_options() {
        parent::admin_options();
    }

	/**
	 * Get API status information.
	 *
	 * @param string $api_status
	 * @return array
	 */
	private function get_api_status_info($api_status) {
		$status_info = [
			'api_status' => [
				'color' => '#e74c3c',
				'text' => __('Inactive', 'ahapay-buy-now-pay-later')
			],
			'api_key' => [
				'color' => '#e74c3c',
				'text' => __('Inactive', 'ahapay-buy-now-pay-later')
			]
		];

		switch ($api_status) {
			case 'healthy_not_verified':
				$status_info['api_status'] = [
					'color' => '#27ae60',
					'text' => __('Healthy', 'ahapay-buy-now-pay-later')
				];
				$status_info['api_key'] = [
					'color' => '#e74c3c',
					'text' => __('Invalid', 'ahapay-buy-now-pay-later')
				];
				break;

			case 'active_verified':
			case 'active_verified_enabled':
				$status_info['api_status'] = [
					'color' => '#27ae60',
					'text' => __('Healthy', 'ahapay-buy-now-pay-later')
				];
				$status_info['api_key'] = [
					'color' => '#27ae60',
					'text' => __('Verified', 'ahapay-buy-now-pay-later')
				];
				break;
		}

		return $status_info;
	}

	/**
	 * Get API status HTML.
	 *
	 * @param array $status_info
	 * @return string
	 */
	private function get_api_status_html($status_info) {
		ob_start();
		?>
        <span class="gateway-status-title"><?php esc_html_e('Gateway Status', 'ahapay-buy-now-pay-later'); ?></span>
        <div class="gateway-status-container">
            <span class="status-label"><?php esc_html_e('API Status', 'ahapay-buy-now-pay-later'); ?></span>
            <span class="status-indicator" style="background: <?php echo esc_attr($status_info['api_status']['color']); ?>"></span>
            <span class="status-text" style="color: <?php echo esc_attr($status_info['api_status']['color']); ?>">
            <?php echo esc_html($status_info['api_status']['text']); ?>
        </span>

            <span class="status-label api-key-label"><?php esc_html_e('API Key Status', 'ahapay-buy-now-pay-later'); ?></span>
            <span class="status-indicator" style="background: <?php echo esc_attr($status_info['api_key']['color']); ?>"></span>
            <span class="status-text" style="color: <?php echo esc_attr($status_info['api_key']['color']); ?>;">
            <?php echo esc_html($status_info['api_key']['text']); ?>
        </span>
        </div>

		<?php
		return ob_get_clean();
	}

	/**
	 * Process admin options.
	 */
	public function process_admin_options()
	{
		// Security: ensure the current user has rights to update gateway settings
		if (!current_user_can('manage_woocommerce')) {
			return;
		}

		// Verify WooCommerce settings nonce to prevent CSRF
		if (function_exists('check_admin_referer')) {
			// This will die/exit on failure which is acceptable for admin actions
			check_admin_referer('woocommerce-settings');
		} else {
			// Fallback manual verification if check_admin_referer is not available
			if (empty($_POST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'woocommerce-settings')) {
				$this->add_error('Nonce verification failed.');
				$this->display_errors();
				return;
			}
		}

		$api_key = isset($_POST['woocommerce_ahapaybuynowpaylater_api_key']) ? sanitize_text_field(wp_unslash($_POST['woocommerce_ahapaybuynowpaylater_api_key'])) : '';
		$environment = isset($_POST['woocommerce_ahapaybuynowpaylater_environment']) ? sanitize_text_field(wp_unslash($_POST['woocommerce_ahapaybuynowpaylater_environment'])) : 'sandbox';
		$api_status = isset($_POST['woocommerce_ahapaybuynowpaylater_api_status']) ? sanitize_text_field(wp_unslash($_POST['woocommerce_ahapaybuynowpaylater_api_status'])) : 'inactive';
		$encryptApikey = $this->encrypt_api_key($api_key, get_option('ahapaybuynowpaylater_secret_key'));
		$base_url = $environment === 'sandbox' ? AHAPAYBUYNOWPAYLATER_SANDBOX_BASE_URL : AHAPAYBUYNOWPAYLATER_LIVE_BASE_URL;
		$enabled = isset($_POST['woocommerce_ahapaybuynowpaylater_enabled']) && $_POST['woocommerce_ahapaybuynowpaylater_enabled'] === '1' ? 'yes' : 'no';
		$enabled_label = isset($_POST['woocommerce_ahapaybuynowpaylater_enable_product_label']) && $_POST['woocommerce_ahapaybuynowpaylater_enable_product_label'] === '1' ? 'yes' : 'no';
		$enabled_payment_info = isset($_POST['woocommerce_ahapaybuynowpaylater_enable_product_payment_info']) && $_POST['woocommerce_ahapaybuynowpaylater_enable_product_payment_info'] === '1' ? 'yes' : 'no';
		$success_page = isset($_POST['woocommerce_ahapaybuynowpaylater_success_page']) ? absint($_POST['woocommerce_ahapaybuynowpaylater_success_page']) : '';
		$error_page = isset($_POST['woocommerce_ahapaybuynowpaylater_error_page']) ? absint($_POST['woocommerce_ahapaybuynowpaylater_error_page']) : '';

		// Additional CSS provided by admin
		$additional_css = isset($_POST['woocommerce_ahapaybuynowpaylater_additional_css']) ? sanitize_textarea_field(wp_unslash($_POST['woocommerce_ahapaybuynowpaylater_additional_css'])) : '';

		$response = wp_remote_get($base_url . '/v1/health', [
			'headers' => ['Content-Type' => 'application/json', 'X-ApiKey' => $api_key],
		]);

		if (wp_remote_retrieve_response_code($response) !== 200) {
			$body = wp_remote_retrieve_body($response);
			$data = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
			$error = $data['error'] ?? ['message' => 'API verification failed. Unknown Reason.'];
			$this->add_error('API verification failed.' . ' Error: ' . $error['message']);
			$this->update_option('api_status', 'healthy_not_verified');
			$this->display_errors();
		} else {
			$this->update_option('api_status', $enabled === 'yes' ? 'active_verified_enabled' : 'active_verified');
		}
		$this->update_option('environment', $environment);
		$this->update_option('api_key', $encryptApikey);
		$this->update_option('enabled', $enabled);
		$this->update_option('debug', isset($_POST['woocommerce_ahapaybuynowpaylater_debug']) ? 'yes' : 'no');
		$this->update_option('enable_product_label',$enabled_label);
		$this->update_option('enable_product_payment_info',$enabled_payment_info);
		$this->update_option('product_label_color', isset($_POST['woocommerce_ahapaybuynowpaylater_product_label_color']) ? sanitize_text_field(wp_unslash($_POST['woocommerce_ahapaybuynowpaylater_product_label_color'])) : 'orange');
		$this->update_option('product_label_text_color', isset($_POST['woocommerce_ahapaybuynowpaylater_product_label_text_color']) ? sanitize_hex_color(wp_unslash($_POST['woocommerce_ahapaybuynowpaylater_product_label_text_color'])) : '#fc642d');
		$this->update_option('product_label_text', isset($_POST['woocommerce_ahapaybuynowpaylater_product_label_text']) ? sanitize_text_field(wp_unslash($_POST['woocommerce_ahapaybuynowpaylater_product_label_text'])) : '0% installments with AhaPay');
		// Save additional CSS (trusted admin input, sanitized as textarea)
		$this->update_option('additional_css', $additional_css);
		$this->update_option('success_page', $success_page);
		$this->update_option('error_page', $error_page);
		$this->update_option('success_page', $success_page);
		$this->update_option('error_page', $error_page);
		return;
	}


	/**
	 * Overridden get_option method for handling encrypted API key.
	 *
	 * @param string $key
	 * @param mixed $empty_value
	 * @return mixed
	 */
	public function get_option($key, $empty_value = null)
	{
		// Check if the key is 'api_key'
		if ($key === 'api_key') {
			$encrypted_value = parent::get_option($key, $empty_value);
			if (!empty($encrypted_value)) {
				// Decrypt the value using the secret key
				return $this->decrypt_api_key($encrypted_value, get_option('ahapaybuynowpaylater_secret_key'));
			}
		}
		return parent::get_option($key, $empty_value);
	}

	/**
	 * Get Secret Key
	 *
	 * @return string
	 */
	private function get_secret_key() {
		$secret_key = get_option('ahapaybuynowpaylater_secret_key');
		if (empty($secret_key)) {
			$secret_key = wp_generate_password(32, true, true);
			update_option('ahapaybuynowpaylater_secret_key', $secret_key);
		}
		return $secret_key;
	}

	/**
	 * Encrypt API key.
	 *
	 * @param string $api_key
	 * @param string $secret_key
	 * @return string
	 */
	private function encrypt_api_key($api_key, $secret_key) {
		if (empty($api_key) || empty($secret_key)) {
			return '';
		}

		$method = 'aes-256-cbc';
		$iv_length = openssl_cipher_iv_length($method);
		$iv = openssl_random_pseudo_bytes($iv_length);

		$encrypted = openssl_encrypt(
			$api_key,
			$method,
			$secret_key,
			OPENSSL_RAW_DATA,
			$iv
		);

		return base64_encode($iv . $encrypted);
	}

	/**
	 * Decrypt API key.
	 *
	 * @param string $encrypted_api_key
	 * @param string $secret_key
	 * @return string
	 */
	private function decrypt_api_key($encrypted_api_key, $secret_key) {
		if (empty($encrypted_api_key) || empty($secret_key)) {
			return '';
		}

		$method = 'aes-256-cbc';
		$iv_length = openssl_cipher_iv_length($method);

		$decoded = base64_decode($encrypted_api_key);
		if ($decoded === false) {
			return '';
		}

		$iv = substr($decoded, 0, $iv_length);
		$encrypted = substr($decoded, $iv_length);

		return openssl_decrypt(
			$encrypted,
			$method,
			$secret_key,
			OPENSSL_RAW_DATA,
			$iv
		);
	}



	/**
	 * Get WordPress pages as options
	 *
	 * @return array
	 */
	private function get_pages_options() {
		$pages = get_pages();
		$options = ['' => __('Select a page', 'ahapay-buy-now-pay-later')];

		foreach ($pages as $page) {
			$options[$page->ID] = $page->post_title;
		}

		return $options;
	}


	/**
	 * Display payment fields on checkout page
	 */
	public function payment_fields() {
		echo '
        <div class="ahapay-payment-fields">
            <div class="ahapay-title">Split your purchase in 4 equal payments, 0% interest</div>
            <div class="ahapay-subtitle">Pay 25% today and the remaining in 3 monthly payments</div>
            <div class="ahapay-progress-bar"><div class="ahapay-progress"></div></div>
            <div class="ahapay-timeline">
                <div><strong>today</strong><br>25%</div>
                <div><strong>1 month later</strong><br>25%</div>
                <div><strong>2 months later</strong><br>25%</div>
                <div><strong>3 months later</strong><br>25%</div>
            </div>
	</div>';
	}

	/**
	 * Process payment
	 *
	 * @param int $order_id
	 * @return array
	 */
	public function process_payment($order_id)
	{
		$order = wc_get_order($order_id);
		$total_amount= $order->get_total();
		if ($total_amount <= 55) {
			$error_message = 'Order amount should be greater than 55.00 MYR to';
			wc_add_notice('Payment error: ' . $error_message, 'error');
			return array(
				'result'   => 'failure',
				'messages' => wp_strip_all_tags($error_message)
			);
		}

		$orderItems = [];
		$WC_Order_Items = $order->get_items();
		$i = 0;
		foreach ($WC_Order_Items as $item) {
			$product = $item->get_product();
			$product_id = $product->get_id();
			$product_name = $product->get_name();
			$product_price = $product->get_price();
			$discount_amount = $product->get_sale_price()  ? $product->get_regular_price() - $product->get_sale_price() : 0;
			$product_quantity = $item->get_quantity();
			$category_ids = $product->get_category_ids();
			$categories = [];
			foreach ($category_ids as $cat_id) {
				$term = get_term_by('id', $cat_id, 'product_cat');
				if ($term && !is_wp_error($term)) {
					$categories[] = $term->name;
				}
			}
			$orderItems[$i] = [
				'category' => $categories,
				'name' => $product_name,
				'price' => $product_price,
				'original_price' => $product_price,
				'discount' => $discount_amount,
				'quantity' => $product_quantity
			];
		}
		$success_page_url = !empty($this->success_page) ? get_permalink($this->success_page) : get_site_url();
		$error_page_url = !empty($this->error_page) ? get_permalink($this->error_page) : get_site_url();

		$redirect_url = [];
		if (!empty($success_page_url) || !empty($error_page_url)) {
			$redirect_url = [
				'success_redirect_url' => $success_page_url,
				'failed_redirect_url' => $error_page_url
			];
		}
		// Build REST callback URL safely to avoid redirects or wrong base paths/schemes
		$callback_url = rest_url('ahapaybuynowpaylater/v1/callback');

		$base_url = $this->environment === 'sandbox' ? AHAPAYBUYNOWPAYLATER_SANDBOX_BASE_URL : AHAPAYBUYNOWPAYLATER_LIVE_BASE_URL;
		$apiKey = $this->get_option('api_key');
		$response = wp_remote_post($base_url . '/v1/orders', [
			'body' => json_encode([
				'amount' => $order->get_total(),
				'reference_number' => (string)$order->get_id(),
				'order_items' => $orderItems,
				'redirect_urls' => $redirect_url,
				'callback_url' => $callback_url,
			]),
			'headers' => ['Content-Type' => 'application/json', 'X-ApiKey' => $apiKey]
		]);

		$body = json_decode(wp_remote_retrieve_body($response), true);

		if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
			$error_message = is_wp_error($response) ? $response->get_error_message() : $body['error']['message'] ?? 'Unknown error';
			$this->log('AhaPay API request failed: ' . json_encode($body, JSON_THROW_ON_ERROR), 'error');
			wc_add_notice('Payment error: ' . $error_message, 'error');
			return array(
				'result'   => 'failure',
				'messages' => wp_strip_all_tags($error_message)
			);
		}



		if (!empty($body['data']['link'])) {

			update_post_meta($order_id, '_ahapaybuynowpaylater_order_payment_url', esc_url_raw($body['data']['link']));
			update_post_meta($order_id, '_ahapaybuynowpaylater_order_id', sanitize_text_field($body['data']['online_order_id']));
			$order->add_order_note('AhaPay payment initiated. Transaction ID: ' . $body['data']['online_order_id']);
			return array(
				'result' => 'success',
				'redirect' =>  esc_url_raw($body['data']['link'])
			);
		}

		wc_add_notice('Failed to initiate AhaPay payment.', 'error');
		return;
	}

	/**
	 * Process refund
	 *
	 * @param int $order_id
	 * @param float|null $amount
	 * @param string $reason
	 * @return bool|WP_Error
	 */
	public function process_refund($order_id, $amount = null, $reason = '')
	{
		$order = wc_get_order($order_id);
		if (!$order) {
			return new \WP_Error('invalid_order', 'Invalid order.');
		}

		// Only full refunds are allowed, you can modify this if you want to allow partial refunds
		if ($amount !== $order->get_total()) {
			return new \WP_Error('invalid_amount', 'Invalid refund amount. Only full refunds are allowed.');
		}

		$transaction = get_post_meta($order_id, '_ahapaybuynowpaylater_order_id', true);
		if (empty($transaction)) {
			return new \WP_Error('invalid_transaction', 'Invalid transaction ID.');
		}

		// Example API call to process refund.
		$base_url = $this->environment === 'sandbox' ? AHAPAYBUYNOWPAYLATER_SANDBOX_BASE_URL : AHAPAYBUYNOWPAYLATER_LIVE_BASE_URL;
		$apiKey = $this->get_option('api_key');
		$response = wp_remote_post($base_url . '/v1/orders/' . $transaction . '/refund', [
			'headers' => [
				'Content-Type' => 'application/json',
				'X-ApiKey' => $apiKey,
			],
		]);

		// Check for request errors.
		if (is_wp_error($response)) {
			return new \WP_Error('refund_request_failed', $response->get_error_message());
		}

		$body = json_decode(wp_remote_retrieve_body($response), true);
		// TODO Need to Check the actual response of refund success and update accordingly
		if (!empty($body['data']['success']) && $body['data']['success'] === true) {
			// Optionally add refund meta, etc.
			$order->add_order_note(sprintf('Refunded %s for order %s', wc_price($order->get_total()), $transaction));
			// Update order status if needed
			$order->update_status('refunded', 'Order refunded via AhaPay');
			$order->save();
			return true;
		}

		return new \WP_Error('refund_failed', 'The refund could not be processed. Reason: ' . $body['error']['message'] ?? 'Unknown error');
	}


	/**
	 * Get payment gateway icon
	 *
	 * @return string
	 */
    public function get_icon() {
        $icon_url  = plugin_dir_url( __DIR__ ) . 'assets/img/ahapay-logo.png';
        $icon_html = sprintf('<img src="%s" alt="%s" class="ahapay-gateway-icon" />', $icon_url, $this->method_title );
        return apply_filters( 'woocommerce_gateway_icon', $icon_html, $this->id );
    }


	/**
	 * Registers WooCommerce Blocks integration.
	 *
	 */
	public static function ahapay_gateway_block_support()
	{
		if (is_admin() || !class_exists(AbstractPaymentMethodType::class) || (!class_exists('Ahapaybuynowpaylater_WC_Gateway') )) {
			return;
		}

		include_once AHAPAYBUYNOWPAYLATER_PLUGIN_DIR . 'includes/class-ahapay-payments-blocks.php';

		if (class_exists('Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType')) {

			add_action(
				'woocommerce_blocks_payment_method_type_registration',
				static function(PaymentMethodRegistry $payment_method_registry) {
					$payment_method_registry->register(new Ahapaybuynowpaylater_WC_Blocks_Support);
				}
			);
 		}
 	}


	/**
	 * Log debug messages.
	 *
	 * @param string $message
	 * @param string $level
	 */
	public function log($message, $level = 'info') {
		if ($this->debug !== 'yes') {
			return;
		}

		if (empty($this->logger)) {
			$this->logger = wc_get_logger();
		}

		$this->logger->log(
			$level === 'error' ? 'error' : 'info',
			$message,
			array('source' => 'ahapaybuynowpaylater')
		);
	}



}
