<?php
/**
 * AnyCoin Payment Gateway AJAX Handlers.
 *
 * @package AnyCoin_Payment_Gateway
 */

defined( 'ABSPATH' ) || exit;

/**
 * AJAX handlers class.
 */
class AnyCoin_Ajax_Handlers {

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

	/**
	 * Initialize hooks.
	 */
	private function init_hooks() {
		// QR code generation.
		add_action( 'wp_ajax_anycoin_generate_qr', [ $this, 'generate_qr_code' ] );
		add_action( 'wp_ajax_nopriv_anycoin_generate_qr', [ $this, 'generate_qr_code' ] );

		// Payment asset update.
		add_action( 'wp_ajax_anycoin_update_payment_asset', [ $this, 'update_payment_asset' ] );
		add_action( 'wp_ajax_nopriv_anycoin_update_payment_asset', [ $this, 'update_payment_asset' ] );

		// Payment status check.
		add_action( 'wp_ajax_anycoin_check_payment', [ $this, 'check_payment' ] );
		add_action( 'wp_ajax_nopriv_anycoin_check_payment', [ $this, 'check_payment' ] );
	}

	/**
	 * AJAX handler for QR code generation.
	 */
	public function generate_qr_code() {
		// Verify nonce (required for security).
		$nonce = isset( $_GET['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ) : '';
		if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( $nonce, 'anycoin_qr' ) ) {
			wp_die( 'Security check failed' );
		}
		// Check if data parameter exists.
		if ( ! isset( $_GET['data'] ) ) {
			wp_die( 'Missing data parameter' );
		}

		$qr_generator = new AnyCoin_QR_Generator();
		$qr_generator->generate_and_output();
	}

	/**
	 * AJAX handler for updating payment asset.
	 */
	public function update_payment_asset() {
		// Verify nonce.
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'anycoin_payment_nonce' ) ) {
			wp_die( 'Security check failed' );
		}

		$order_id     = intval( $_POST['order_id'] ?? 0 );
		$asset_id     = isset( $_POST['asset_id'] ) ? sanitize_text_field( wp_unslash( $_POST['asset_id'] ) ) : '';
		$asset_symbol = isset( $_POST['asset_symbol'] ) ? sanitize_text_field( wp_unslash( $_POST['asset_symbol'] ) ) : '';

		if ( ! $order_id || ! $asset_id || ! $asset_symbol ) {
			wp_send_json_error( [ 'message' => 'Missing required parameters' ] );
			return;
		}

		$valid_assets = [
			'd6329b5b1f7c0805b5c345f4957554002a2f557845f64d7645dae0e051a6498a' => 'ZANO',
			'86143388bd056a8f0bab669f78f14873fac8e2dd8d57898cdb725a2d5e2e4f8f' => 'FUSD',
		];

		if ( ! isset( $valid_assets[ $asset_id ] ) || $valid_assets[ $asset_id ] !== $asset_symbol ) {
			wp_send_json_error( [ 'message' => 'Invalid asset' ] );
			return;
		}

		$payment = AnyCoin_Database_Manager::get_payment_by_order_id( (int) $order_id );
		if ( ! $payment ) {
			wp_send_json_error( [ 'message' => 'Payment not found' ] );
			return;
		}

		// Compute the required amount server-side - never trust a client-posted
		// amount, since it becomes the matching/verification target.
		if ( $asset_id === AnyCoin_Constants::FUSD_ASSET_ID ) {
			$order = wc_get_order( $order_id );
			if ( ! $order ) {
				wp_send_json_error( [ 'message' => 'Order not found' ] );
				return;
			}
			// FUSD is USD-pegged; the payment page charges the order total in FUSD.
			$asset_amount = (float) $order->get_total();
		} else {
			// ZANO amount was computed server-side at checkout.
			$asset_amount = (float) $payment['amount'];
		}

		if ( $asset_amount <= 0 ) {
			wp_send_json_error( [ 'message' => 'Invalid payment amount' ] );
			return;
		}

		$result = AnyCoin_Database_Manager::update_payment(
			(int) $payment['id'],
			[
				'asset_id'     => $asset_id,
				'asset_symbol' => $asset_symbol,
				'asset_amount' => $asset_amount,
			]
		);

		if ( ! $result ) {
			wp_send_json_error( [ 'message' => 'Failed to update payment record' ] );
			return;
		}

		update_post_meta( $order_id, '_anycoin_selected_asset', strtolower( $asset_symbol ) );
		update_post_meta( $order_id, '_anycoin_asset_id', $asset_id );
		update_post_meta( $order_id, '_anycoin_asset_amount', $asset_amount );

		wp_send_json_success(
			[
				'message'      => 'Payment asset updated successfully',
				'asset_id'     => $asset_id,
				'asset_symbol' => $asset_symbol,
				'asset_amount' => $asset_amount,
			]
		);
	}

	/**
	 * AJAX handler for checking payment status.
	 */
	public function check_payment() {
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $nonce, 'anycoin_payment_nonce' ) ) {
			wp_send_json_error(
				[
					'status'  => 'error',
					'message' => 'Security verification failed',
				]
			);
			return;
		}

		$order_id = isset( $_POST['order_id'] ) ? absint( $_POST['order_id'] ) : 0;

		if ( ! $order_id ) {
			wp_send_json_error(
				[
					'status'  => 'error',
					'message' => 'Invalid order ID',
				]
			);
			return;
		}

		$order = wc_get_order( $order_id );

		if ( ! $order ) {
			wp_send_json_error(
				[
					'status'  => 'error',
					'message' => 'Order not found',
				]
			);
			return;
		}

		$payment_gateways = WC()->payment_gateways()->payment_gateways();
		$gateway          = isset( $payment_gateways['anycoin_payment'] ) ? $payment_gateways['anycoin_payment'] : null;

		if ( ! $gateway ) {
			wp_send_json_error(
				[
					'status'  => 'error',
					'message' => 'Payment gateway not available',
				]
			);
			return;
		}

		$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',
			]
		);

		$status = $api->check_payment_status( $order_id );

		$response = [
			'status'       => $status['status'],
			'order_id'     => $order_id,
			'redirect_url' => $order->get_checkout_order_received_url(),
		];

		if ( isset( $status['confirmations'] ) ) {
			$response['confirmations'] = $status['confirmations'];
		}

		if ( isset( $status['tx_hash'] ) ) {
			$response['tx_hash'] = $status['tx_hash'];
		}

		if ( isset( $status['message'] ) ) {
			$response['message'] = $status['message'];
		}

		if ( isset( $status['amount'] ) ) {
			$response['amount'] = $status['amount'];
		}

		$response['required_confirmations'] = $gateway->confirmations;

		wp_send_json_success( $response );
	}
}
