<?php
/**
 * Handles AJAX for BNPL.
 */

namespace Flo_Checkout\Gateways\BNPL;

use Northmill_Online_Shared_Checkout\Northmill_Online_Shared\Modules\Loggers\Log_Level_Enum;

/**
 * Class BNPL_AJAX
 */
class BNPL_AJAX {

	/**
	 * Sets up the necessary actions and hooks for the plugin.
	 *
	 * @return void
	 */
	public static function setup(): void {
		if ( BNPL_Settings::is_enabled() ) {
			// Ajax hooks for transaction status check.
			add_action( 'wp_ajax_northmill_bnpl_transaction_check', array( self::class, 'ajax_transaction_status_check' ) );
			add_action( 'wp_ajax_nopriv_northmill_bnpl_transaction_check', array( self::class, 'ajax_transaction_status_check' ) );

			// Ajax hooks for transaction cancellation.
			add_action( 'wp_ajax_northmill_bnpl_transaction_cancel', array( self::class, 'ajax_transaction_cancel' ) );
			add_action( 'wp_ajax_nopriv_northmill_bnpl_transaction_cancel', array( self::class, 'ajax_transaction_cancel' ) );
		}
	}

	/**
	 * AJAX handler for the frontend polling
	 */
	public static function ajax_transaction_status_check(): void {
		if ( ! check_ajax_referer( 'northmill_bnpl_transaction' ) ) {
			wp_die( 'Nonce error' );
		}

		// Get order from the order key.
		$order_key = sanitize_text_field( $_POST['order_key'] );
		$order_id  = wc_get_order_id_by_order_key( $order_key );

		if ( empty( $order_id ) ) {
			wp_die( 'Missing order ID' );
		}

		$transaction = BNPL_Transactions::check_transaction_status( $order_id, 'ajax' );

		if ( ! $transaction ) {
			wp_die( 'Failed to get transaction' );
		}

		$response = array(
			'status' => $transaction->get_status_text(),
		);
		wp_send_json_success( $response );
	}

	/**
	 * AJAX handler for attempting to cancel a BNPL transaction
	 */
	public static function ajax_transaction_cancel(): void {
		if ( ! check_ajax_referer( 'northmill_bnpl_transaction' ) ) {
			wp_die( 'Nonce error' );
		}

		// Get order from the order key.
		$order_key = sanitize_text_field( $_POST['order_key'] );
		$order_id  = wc_get_order_id_by_order_key( $order_key );

		$order = wc_get_order( $order_id );

		if ( empty( $order ) ) {
			wp_die( 'Order not found' );
		}
		$transaction_id = $order->get_meta( 'northmill_bnpl_transaction_id' );

		if ( ! $transaction_id ) {
			BNPL_Settings::log( 'Transaction ID not found on order', array( 'order_id' => $order_id ), Log_Level_Enum::ERROR );
			wp_die( 'Transaction ID not found on order' );
		}

		$cancel_result = BNPL_API::instance()->cancel_transaction( $transaction_id );

		if ( $cancel_result ) {
			wp_send_json_success();
		} else {
			wp_send_json_error(
				array(
					'status'  => 'failed',
					'message' => 'Failed to cancel transaction',
				)
			);
		}
	}
}
