<?php
/**
 * PeachPay ConvesioPay BTCPay Gateway
 *
 * @package PeachPay
 */

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

require_once PEACHPAY_ABSPATH . 'core/abstract/class-peachpay-payment-gateway.php';

/**
 * ConvesioPay BTCPay Gateway
 */
class PeachPay_ConvesioPay_BTCPay_Gateway extends PeachPay_Payment_Gateway {
	/**
	 * Track if gateway was properly initialized
	 */
	private $initialized = false;
	
	/**
	 * Gateway settings
	 */
	public $settings = array();
	
	/**
	 * Gateway properties
	 */
	public $id;
	public $title;
	public $description;
	public $method_title;
	public $method_description;
	public $icon;
	public $has_fields;
	public $supports;
	public $enabled;
	
	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->id                    = 'peachpay_convesiopay_btcpay';
		$this->title                 = 'Crypto';
		$this->description           = sprintf( __( 'After selecting %s a prompt will appear to complete your payment.', 'peachpay-for-woocommerce' ), 'Crypto' );
		$this->method_title          = sprintf( __( '%s via ConvesioPay (PeachPay)', 'peachpay-for-woocommerce' ), 'Crypto' );
		$this->method_description    = 'Accept cryptocurrency payments through ConvesioPay BTCPay Server.';
		$this->has_fields            = true;
		$this->supports              = array( 'products', 'refunds', 'blocks' );
		
		// Set up BTCPay icons - using generic card icon as fallback since Bitcoin icons don't exist
		$this->icon = '';
		$this->icons = array(
			'full'  => array(
				'color' => PeachPay::get_asset_url( 'img/marks/card-small.svg' ),
			),
			'small' => array(
				'color' => PeachPay::get_asset_url( 'img/marks/card-small.svg' ),
			),
		);
		
		// Set payment provider info
		$this->payment_provider = 'ConvesioPay';
		$this->payment_method_family = __( 'Cryptocurrency', 'peachpay-for-woocommerce' );
		
		// Restrict to USD currency only
		$this->currencies = array( 'USD' );
		
		// Override max_amount to prevent JSON encoding issues
		// $this->max_amount = 999999.99; // Commented out to show "Not restricted"
		
		// Call parent constructor
		parent::__construct();
		
		// Enable gateway by default if not set
		if (!isset($this->settings['enabled'])) {
			$this->enabled = 'yes';
		}
		
		// Add hooks
		add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		
		// Initialize form fields
		$this->init_form_fields();
		$this->min_amount = 20;
		// Mark as initialized
		$this->initialized = true;
	}

	/**
	 * Initialize gateway form fields.
	 */
	public function init_form_fields() {
		// Call parent method to get standard fields
		parent::init_form_fields();
		// Modify the active_locations field after parent initialization
		if ( isset( $this->form_fields['active_locations'] ) ) {
			$this->form_fields['active_locations']['options']     = array(
				'default'               => __( 'Native checkout and PeachPay Express Checkout', 'peachpay-for-woocommerce' ),
				'checkout_page_only'    => __( 'Native checkout only', 'peachpay-for-woocommerce' ),
				'express_checkout_only' => __( 'PeachPay Express Checkout only', 'peachpay-for-woocommerce' ),
			);
			$this->form_fields['active_locations']['description'] = __( 'Native checkout means the standard WooCommerce classic/block checkout payment method area. This setting does not control ConvesioPay Accelerated Checkout buttons.', 'peachpay-for-woocommerce' );
		}
	}

	/**
	 * Gets the minimum charge with proper formatting to show $0.50 instead of $0.5
	 *
	 * @return string
	 */
	public function get_minimum_charge() {
		$min_charge = parent::get_minimum_charge();
		// Ensure proper formatting with 2 decimal places
		return number_format( (float) $min_charge, 2, '.', '' );
	}

	/**
	 * Gets the maximum charge - return INF to show "Not restricted"
	 *
	 * @return float
	 */
	public function get_maximum_charge() {
		return INF;
	}

	/**
	 * Check if the gateway is available for use.
	 *
	 * @param boolean $skip_cart_check Whether to skip cart check.
	 * @return boolean
	 */
	public function is_available( $skip_cart_check = false ) {
		// Always hide this gateway from the standard WooCommerce payment methods list.
		// BTCPay/Crypto is only available within the unified ConvesioPay gateway.
		// This gateway class exists for fee calculation and internal processing only.
		return false;
	}

	/**
	 * Check if BTCPay is actually enabled for internal use.
	 * This is used by the unified gateway to determine if crypto should be shown.
	 *
	 * @return boolean
	 */
	public function is_btcpay_enabled_internal() {
		if ( ! PeachPay_ConvesioPay_Integration::is_btcpay_enabled() ) {
			return false;
		}

		// Check if gateway is properly initialized
		if ( ! $this->initialized ) {
			return false;
		}
		
		// Check if ConvesioPay is connected - this is the key availability check
		if ( ! PeachPay_ConvesioPay_Integration::connected() ) {
			return false;
		}
		
		// Check if gateway is enabled
		if ( $this->enabled !== 'yes' ) {
			return false;
		}
		
		return true;
	}

	/**
	 * Get ConvesioPay configuration.
	 *
	 * @return array
	 */
	private function get_convesiopay_config() {
		return PeachPay_ConvesioPay_Integration::config();
	}

	/**
	 * Process the payment.
	 *
	 * @param int $order_id Order ID.
	 * @return array
	 */
	public function process_payment( $order_id ) {
		// SERVER-SIDE SAFETY CHECK: never process BTCPay payments when the
		// method is disabled in WooCommerce/PeachPay settings.
		if ( ! PeachPay_ConvesioPay_Integration::is_btcpay_enabled() ) {
			return array(
				'result'  => 'failure',
				'message' => __( 'BTCPay payment method is disabled.', 'peachpay-for-woocommerce' ),
			);
		}

		$transaction_id = null;
		$payment_token = null;

		// Check for transaction ID and payment token
		if (isset($_POST['peachpay_transaction_id'])) {
			$transaction_id = $_POST['peachpay_transaction_id'];
		}

		if (isset($_POST['convesiopay_payment_token'])) {
			$payment_token = $_POST['convesiopay_payment_token'];
		}

		// Check for BTCPay session ID from frontend
		if (isset($_POST['btcpay_session_id'])) {
			$btcpay_session_id = sanitize_text_field($_POST['btcpay_session_id']);
		}

		// Check for BTCPay payment confirmation data from frontend
		$btcpay_payment_id = null;
		$btcpay_invoice_id = null;
		$btcpay_status = null;

		if (isset($_POST['btcpay_payment_id'])) {
			$btcpay_payment_id = sanitize_text_field($_POST['btcpay_payment_id']);
		}

		if (isset($_POST['btcpay_invoice_id'])) {
			$btcpay_invoice_id = sanitize_text_field($_POST['btcpay_invoice_id']);
		}

		if (isset($_POST['btcpay_status'])) {
			$btcpay_status = sanitize_text_field($_POST['btcpay_status']);
		}

		$should_process_locally = ($transaction_id === 'btc-transaction-id-placeholder' || $payment_token === 'btc-pay-token-placeholder' || !empty($btcpay_session_id));

		if ($should_process_locally) {
			$order = wc_get_order( $order_id );

			if ( ! $order ) {
				return array(
					'result'   => 'failure',
					'message'  => __( 'Order not found.', 'peachpay-for-woocommerce' ),
				);
			}

			if ($btcpay_payment_id && $btcpay_status === 'Processing') {
				// Payment received - set to processing
				$order->update_status('processing', sprintf(__('BTCPay cryptocurrency payment received. Payment ID: %s', 'peachpay-for-woocommerce'), $btcpay_payment_id));
				$payment_url = peachpay_convesiopay_dashboard_url() . '/payments/' . $btcpay_payment_id;
				$order->add_order_note(sprintf(__('BTCPay payment confirmed. Payment ID: %s, Invoice ID: %s, Status: %s | <a href="%s" target="_blank">View Payment</a>', 'peachpay-for-woocommerce'), $btcpay_payment_id, $btcpay_invoice_id, $btcpay_status, $payment_url));
			} else {
				// No payment confirmation - set to pending
				$order->update_status('pending', __('Awaiting BTCPay cryptocurrency payment confirmation.', 'peachpay-for-woocommerce'));
				$order->add_order_note(__('Customer initiated BTCPay cryptocurrency payment.', 'peachpay-for-woocommerce'));
			}


			// Store payment method info
			$order->set_payment_method_title( $this->get_title() );
			$order->update_meta_data('_convesiopay_payment_type', 'btcpay');
			if ($payment_token && $payment_token !== 'btc-pay-token-placeholder') {
				$order->update_meta_data('_convesiopay_payment_token', $payment_token);
			}
			if ($transaction_id && $transaction_id !== 'btc-transaction-id-placeholder') {
				$order->update_meta_data('_peachpay_transaction_id', $transaction_id);
			}

			// Store BTCPay specific payment information
			if ($btcpay_payment_id) {
				$order->update_meta_data('_btcpay_payment_id', $btcpay_payment_id);
				$order->set_transaction_id($btcpay_payment_id); // Set WooCommerce transaction ID to BTCPay payment ID
			}
			if ($btcpay_invoice_id) {
				$order->update_meta_data('_btcpay_invoice_id', $btcpay_invoice_id);
			}
			if ($btcpay_status) {
				$order->update_meta_data('_btcpay_status', $btcpay_status);
			}
			if ($btcpay_session_id) {
				$order->update_meta_data('_btcpay_session_id', $btcpay_session_id);
			}

			$order->save();

			// Clear cart
			WC()->cart->empty_cart();

			$return_url = $this->get_return_url( $order );
			
			return array(
				'result'   => 'success',
				'redirect' => $return_url,
			);
		}

		// Use parent gateway processing - it will handle ConvesioPay API response properly
		$parent_result = parent::process_payment( $order_id );
		return $parent_result;
	}

	/**
	 * Get transaction URL for viewing payment in ConvesioPay dashboard
	 *
	 * @param WC_Order $order Order object.
	 * @return string Transaction URL.
	 */
	public function get_transaction_url( $order ) {
		$payment_id = $order->get_meta( '_convesiopay_payment_id' );
		if ( empty( $payment_id ) ) {
			$payment_id = $order->get_meta( '_btcpay_payment_id' );
		}
		if ( empty( $payment_id ) ) {
			$payment_id = $order->get_transaction_id();
		}

		if ( ! empty( $payment_id ) ) {
			$this->view_transaction_url = peachpay_convesiopay_dashboard_url() . '/payments/%s';
			return parent::get_transaction_url( $order );
		}

		return '';
	}

	/**
	 * Enqueue gateway scripts.
	 */
	public function enqueue_scripts() {
		if ( ! $this->is_available() ) {
			return;
		}

		// Only enqueue BTCPay classic checkout script if NOT using WooCommerce Blocks
		// WooCommerce Blocks has its own btcpay-blocks.js script
		if ( ! $this->is_woocommerce_blocks_checkout() ) {
			// Enqueue BTCPay specific scripts for classic checkout
			wp_enqueue_script(
				'peachpay-convesiopay-btcpay',
				plugins_url( 'assets/js/btcpay.js', dirname( __FILE__ ) ),
				array( 'jquery', 'peachpay-convesiopay-checkout' ),
				'2.6.0',
				true
			);

			// Add BTCPay configuration
			$config = $this->get_convesiopay_config();
			
			wp_localize_script(
				'peachpay-convesiopay-btcpay',
				'peachpayConvesioPayBTCPay',
				array(
					'gateway_id'    => $this->id,
					'is_available'  => $this->is_available(),
					'client_key'    => $config['client_key'] ?? '',
					'api_url'       => peachpay_is_test_mode() ? 'https://api-qa.convesiopay.com' : 'https://api.convesiopay.com',
					'ajax_url'      => admin_url( 'admin-ajax.php' ),
					'nonce'         => wp_create_nonce( 'peachpay_convesiopay_nonce' ),
					'integration_name' => $config['integration_name'] ?? '',
				)
			);
		}
	}

	/**
	 * Check if we're on a WooCommerce Blocks checkout page.
	 *
	 * @return boolean
	 */
	private function is_woocommerce_blocks_checkout() {
		// Check if we're on checkout page first
		if ( ! is_checkout() ) {
			return false;
		}
		
		// Check if WooCommerce Blocks is active
		if ( ! class_exists( 'Automattic\WooCommerce\Blocks\Package' ) ) {
			return false;
		}
		
		// Check if the current checkout page is using blocks
		global $post;
		if ( $post && has_block( 'woocommerce/checkout', $post ) ) {
			return true;
		}
		
		// Additional check: look for blocks-specific elements in the DOM
		// This is a fallback for cases where the block check might not work
		if ( isset( $_SERVER['HTTP_USER_AGENT'] ) && strpos( $_SERVER['HTTP_USER_AGENT'], 'wc-blocks' ) !== false ) {
			return true;
		}
		
		return false;
	}

	/**
	 * Get gateway icon with size and style options.
	 *
	 * @param boolean $flex Whether to use flex display.
	 * @param string $size Icon size (full/small).
	 * @param string $background Icon style (color/white).
	 * @return string
	 */
	public function get_icon( $flex = false, $size = 'full', $background = 'color' ) {
		if ( isset( $this->icons[ $size ][ $background ] ) ) {
			return '<img src="' . esc_url( $this->icons[ $size ][ $background ] ) . '" alt="' . esc_attr( $this->get_title() ) . '" class="peachpay-payment-method-icon peachpay-payment-method-icon-' . esc_attr( $size ) . '">';
		}
		
		// Fallback to first available icon
		foreach ( $this->icons as $size_key => $styles ) {
			foreach ( $styles as $style_key => $url ) {
				return '<img src="' . esc_url( $url ) . '" alt="' . esc_attr( $this->get_title() ) . '" class="peachpay-payment-method-icon peachpay-payment-method-icon-' . esc_attr( $size_key ) . '">';
			}
		}
		
		return '';
	}

	/**
	 * Check if gateway is properly initialized.
	 *
	 * @return boolean
	 */
	public function is_initialized() {
		return $this->initialized;
	}
}