<?php
/**
 * AnyCoin Payment Gateway Payment Page Handler.
 *
 * @package AnyCoin_Payment_Gateway
 */

defined( 'ABSPATH' ) || exit;

/**
 * Payment page handler class
 */
class AnyCoin_Payment_Page_Handler {

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->init_hooks();
	}

	/**
	 * Initialize hooks
	 */
	private function init_hooks() {
		add_action( 'woocommerce_api_anycoin_payment_page', [ $this, 'handle_payment_page' ] );
	}

	/**
	 * Handle payment page display.
	 */
	public function handle_payment_page() {
		$nonce = isset( $_GET['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ) : '';// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- optional for read-only view
		if ( $nonce && ! wp_verify_nonce( $nonce, 'anycoin_payment_page' ) ) {
			wp_die( 'Invalid request' );
		}

		$order_id = isset( $_GET['order_id'] ) ? absint( $_GET['order_id'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only, sanitized

		if ( ! $order_id ) {
			wp_safe_redirect( wc_get_page_permalink( 'checkout' ) );
			exit;
		}

		$order = wc_get_order( $order_id );
		if ( ! $order || $order->get_payment_method() !== 'anycoin_payment' ) {
			wp_safe_redirect( wc_get_page_permalink( 'checkout' ) );
			exit;
		}

		$order_key_param = isset( $_GET['key'] ) ? sanitize_text_field( wp_unslash( $_GET['key'] ) ) : '';// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only, sanitized
		if ( ! $order || ( ! user_can( get_current_user_id(), 'read' ) && $order->get_order_key() !== $order_key_param ) ) {
			wp_safe_redirect( wc_get_page_permalink( 'checkout' ) );
			exit;
		}

		$payment = $this->get_payment_details( $order_id );

		if ( ! $payment ) {
			wp_safe_redirect( $order->get_checkout_payment_url() );
			exit;
		}

		$variables = $this->prepare_template_variables( $order, $payment );

		$this->setup_page_context();

		$this->enqueue_assets();

		get_header();

		$this->load_template( $variables );

		get_footer();
		exit;
	}

	/**
	 * Get payment details from database.
	 *
	 * @param int $order_id Order ID.
	 * @return array|null Payment row.
	 */
	private function get_payment_details( $order_id ) {
		return AnyCoin_Database_Manager::get_payment_by_order_id( (int) $order_id );
	}

	/**
	 * Prepare template variables.
	 *
	 * @param WC_Order $order   Order object.
	 * @param array    $payment Payment record.
	 * @return array Variables for template.
	 */
	private function prepare_template_variables( $order, $payment ) {
		$variables                   = [];
		$variables['order']          = $order;
		$variables['order_id']       = $order->get_id();
		$variables['payment']        = $payment;
		$variables['payment_id']     = $payment['payment_id'];
		$variables['wallet_address'] = $payment['wallet_address'];
		$variables['zano_amount']    = $payment['amount'];
		$variables['order_key']      = $order->get_order_key();

		$variables['price_display'] = $this->get_price_display();

		return $variables;
	}

	/**
	 * Get price display string.
	 */
	private function get_price_display() {
		$gateways = WC()->payment_gateways()->get_available_payment_gateways();
		$gateway  = isset( $gateways['anycoin_payment'] ) ? $gateways['anycoin_payment'] : null;

		if ( $gateway ) {
			$gateway_settings = get_option( 'woocommerce_anycoin_payment_settings', [] );
			$api              = new AnyCoin_API(
				[
					'api_url'            => $gateway_settings['api_url'] ?? '',
					'wallet_address'     => $gateway_settings['wallet_address'] ?? '',
					'view_key'           => $gateway_settings['view_key'] ?? '',
					'payment_id_api_url' => $gateway_settings['payment_id_api_url'] ?? AnyCoin_Constants::PAYMENT_VERIFICATION_API,
					'debug'              => isset( $gateway_settings['debug'] ) && $gateway_settings['debug'] === 'yes',
				]
			);

			$current_price = $api->get_zano_price();
			return is_wp_error( $current_price ) ? '' :
				sprintf( ' (1 ZANO ≈ $%s USD)', number_format( $current_price, 2 ) );
		}

		return '';
	}

	/**
	 * Setup page context for proper theme integration.
	 */
	private function setup_page_context() {
		global $post; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Temporary context for page rendering.

		$checkout_page_id = wc_get_page_id( 'checkout' );
		if ( $checkout_page_id > 0 ) {
			$post = get_post( $checkout_page_id ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- See above justification.
		} else {
			$post                 = new stdClass(); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- See above justification.
			$post->ID             = 0;
			$post->post_title     = 'AnyCoin Payment';
			$post->post_status    = 'publish';
			$post->post_type      = 'page';
			$post->post_content   = '';
			$post->comment_status = 'closed';
			$post->ping_status    = 'closed';
			$post                 = new WP_Post( $post ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- See above justification.
		}
	}

	/**
	 * Enqueue necessary assets.
	 */
	private function enqueue_assets() {
		if ( ! wp_script_is( 'anycoin-payment-script' ) ) {
			wp_enqueue_script(
				'anycoin-payment-script',
				ANYCOIN_PAYMENT_PLUGIN_URL . 'assets/js/anycoin-payment.js',
				[ 'jquery' ],
				ANYCOIN_PAYMENT_VERSION . '.' . time() . '.v2',
				true
			);

			wp_localize_script(
				'anycoin-payment-script',
				'anycoin_params',
				[
					'ajax_url'       => admin_url( 'admin-ajax.php' ),
					'nonce'          => wp_create_nonce( 'anycoin_payment_nonce' ),
					'confirmed_text' => 'Payment confirmed! Your order is being processed.',
					'detected_text'  => 'Payment detected! Waiting for confirmations: %s',
					'pending_text'   => 'Waiting for payment...',
					'failed_text'    => 'Payment failed or expired after 20 minutes.',
					'check_text'     => 'Check for Payment',
					'checking_text'  => 'Checking...',
				]
			);
		}

		if ( ! wp_script_is( 'anycoin-payment-template' ) ) {
			wp_enqueue_script(
				'anycoin-payment-template',
				ANYCOIN_PAYMENT_PLUGIN_URL . 'assets/js/anycoin-template.js',
				[ 'anycoin-payment-script', 'jquery' ],
				ANYCOIN_PAYMENT_VERSION . '.' . time() . '.v1',
				true
			);
		}

		if ( ! wp_style_is( 'anycoin-payment-style' ) ) {
			wp_enqueue_style(
				'anycoin-payment-style',
				ANYCOIN_PAYMENT_PLUGIN_URL . 'assets/css/anycoin-payment.css',
				[],
				ANYCOIN_PAYMENT_VERSION . '.' . time() . '.v2'
			);
		}
	}

	/**
	 * Load payment template.
	 *
	 * @param array $variables Template variables.
	 */
	private function load_template( $variables ) {
		$template_path = ANYCOIN_PAYMENT_PLUGIN_DIR . 'templates/payment-page.php';

		if ( file_exists( $template_path ) ) {
			$order          = $variables['order'] ?? null;
			$order_id       = $variables['order_id'] ?? 0;
			$payment        = $variables['payment'] ?? [];
			$payment_id     = $variables['payment_id'] ?? '';
			$wallet_address = $variables['wallet_address'] ?? '';
			$zano_amount    = $variables['zano_amount'] ?? 0;
			$order_key      = $variables['order_key'] ?? '';
			$price_display  = $variables['price_display'] ?? '';
			include $template_path;
		} else {
			$this->output_fallback_template( $variables );
		}
	}

	/**
	 * Output fallback template when main template doesn't exist.
	 *
	 * @param array $variables Template variables.
	 */
	private function output_fallback_template( $variables ) {
		echo '<div class="woocommerce">';
		echo '<div class="woocommerce-notices-wrapper"></div>';
		echo '<h1>Payment Details</h1>';
		echo '<p>Please send ' . esc_html( $variables['payment']['amount'] ) . ' ZANO to address: ' . esc_html( $variables['payment']['wallet_address'] ) . '</p>';
		echo '<p>Note: This integrated address includes payment tracking. Just send the exact amount to this address.</p>';
		echo '<p><a href="' . esc_url( $variables['order']->get_checkout_order_received_url() ) . '" class="button">Continue</a></p>';
		echo '</div>';
	}
}
