<?php
/**
 * NMI Manual Capture Admin functionality.
 *
 * @package PeachPay
 */

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

/**
 * NMI Manual Capture Admin class.
 */
class PeachPay_NMI_Manual_Capture_Admin {
	
	/**
	 * Constructor.
	 */
	public function __construct() {
		// Add capture/cancel buttons to order details page
		add_action( 'woocommerce_order_item_add_action_buttons', array( $this, 'add_capture_cancel_buttons' ) );
		
		// Add AJAX handlers for capture and cancel
		add_action( 'wp_ajax_peachpay_nmi_capture_payment', array( $this, 'handle_capture_payment' ) );
		add_action( 'wp_ajax_peachpay_nmi_cancel_payment', array( $this, 'handle_cancel_payment' ) );
		
		// Enqueue admin scripts
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );
	}
	
	/**
	 * Add capture and cancel buttons to WooCommerce order details page.
	 *
	 * @param WC_Order $order Order object.
	 */
	public function add_capture_cancel_buttons( $order ) {
		// Only show for NMI CARD orders
		if ( $order->get_payment_method() !== 'peachpay_nmi_card' ) {
			return;
		}
		
		// Only show for Pending orders (authorized but not captured)
		if ( $order->get_status() !== 'pending' ) {
			return;
		}
		
		// Get payment ID
		$payment_id = $order->get_meta( '_nmi_payment_id' );
		if ( empty( $payment_id ) ) {
			return;
		}
		
		$order_id = $order->get_id();
		$order_total = $order->get_total();
		$order_currency = $order->get_currency();
		$payment_method = $order->get_payment_method();
		
		// Convert to minor units (cents)
		$amount_minor = intval( $order_total * 100 );
		
		// Button text
		$capture_text = 'Capture Payment';
		$cancel_text = 'Cancel Payment';
		$capture_title = 'Capture this authorized payment';
		$cancel_title = 'Cancel this authorized payment';
		
		// Add buttons directly inline with existing WooCommerce buttons
		// Capture button
		echo '<button type="button" class="button button-primary nmi-capture-btn" ';
		echo 'data-order-id="' . esc_attr( $order_id ) . '" ';
		echo 'data-payment-id="' . esc_attr( $payment_id ) . '" ';
		echo 'data-amount="' . esc_attr( $amount_minor ) . '" ';
		echo 'data-currency="' . esc_attr( $order_currency ) . '" ';
		echo 'data-payment-method="' . esc_attr( $payment_method ) . '" ';
		echo 'title="' . esc_attr( $capture_title ) . '">';
		echo esc_html( $capture_text );
		echo '</button>';
		
		echo ' ';
		
		// Cancel button  
		echo '<button type="button" class="button nmi-cancel-btn" ';
		echo 'data-order-id="' . esc_attr( $order_id ) . '" ';
		echo 'data-payment-id="' . esc_attr( $payment_id ) . '" ';
		echo 'data-payment-method="' . esc_attr( $payment_method ) . '" ';
		echo 'title="' . esc_attr( $cancel_title ) . '">';
		echo esc_html( $cancel_text );
		echo '</button>';
		
		// Add hidden loading indicator
		echo '<span class="nmi-loading" style="display: none; margin-left: 10px;">';
		echo '<span class="spinner is-active"></span> Processing...';
		echo '</span>';
	}
	
	/**
	 * Handle capture payment AJAX request.
	 */
	public function handle_capture_payment() {
		// Security check
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( array( 'message' => 'Insufficient permissions' ) );
			return;
		}
		
		// Verify nonce
		if ( ! wp_verify_nonce( $_POST['nonce'] ?? '', 'woocommerce-order-item' ) ) {
			wp_send_json_error( array( 'message' => 'Security check failed' ) );
			return;
		}
		
		$order_id = intval( $_POST['order_id'] ?? 0 );
		$payment_id = sanitize_text_field( $_POST['payment_id'] ?? '' );
		$amount = intval( $_POST['amount'] ?? 0 );
		$currency = sanitize_text_field( $_POST['currency'] ?? 'USD' );
		
		if ( empty( $order_id ) || empty( $payment_id ) || empty( $amount ) ) {
			wp_send_json_error( array( 'message' => 'Missing required parameters' ) );
			return;
		}
		
		// Get order
		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			wp_send_json_error( array( 'message' => 'Order not found' ) );
			return;
		}
		
		// Call NMI capture API
		$result = $this->capture_payment_api( $order, $payment_id, $currency, $amount );

		if ( $result['success'] ) {
			// Get capture ID from response
			$capture_id = $result['data']['transactionid'] ?? $payment_id;

			// Update order
			$order->add_order_note( sprintf(
				'NMI payment manually captured. Capture ID: %s, Original Payment ID: %s',
				$capture_id,
				$payment_id
			) );

			// Update capture ID meta and transaction ID
			$order->update_meta_data( '_nmi_capture_id', $capture_id );
			$order->set_transaction_id( $capture_id );

			$order->update_status( 'processing', 'Payment captured manually via NMI.' );
			$order->save();

			wp_send_json_success( array(
				'message' => 'Payment captured successfully',
				'data' => $result['data']
			) );
		} else {
			// Log error
			$order->add_order_note( sprintf(
				'NMI capture failed: %s',
				$result['message']
			) );
			
			wp_send_json_error( array( 'message' => $result['message'] ) );
		}
	}
	
	/**
	 * Handle cancel payment AJAX request.
	 */
	public function handle_cancel_payment() {
		// Security check
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( array( 'message' => 'Insufficient permissions' ) );
			return;
		}
		
		// Verify nonce
		if ( ! wp_verify_nonce( $_POST['nonce'] ?? '', 'woocommerce-order-item' ) ) {
			wp_send_json_error( array( 'message' => 'Security check failed' ) );
			return;
		}
		
		$order_id = intval( $_POST['order_id'] ?? 0 );
		$payment_id = sanitize_text_field( $_POST['payment_id'] ?? '' );
		
		if ( empty( $order_id ) || empty( $payment_id ) ) {
			wp_send_json_error( array( 'message' => 'Missing required parameters' ) );
			return;
		}
		
		// Get order
		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			wp_send_json_error( array( 'message' => 'Order not found' ) );
			return;
		}
		
		// Call NMI cancel API
		$result = $this->cancel_payment_api( $order, $payment_id );
		
		if ( $result['success'] ) {
			// Get cancel ID from response
			$cancel_id = $result['data']['transactionid'] ?? $payment_id;

			// Update order
			$order->add_order_note( sprintf(
				'NMI payment manually cancelled. Cancel ID: %s, Original Payment ID: %s',
				$cancel_id,
				$payment_id
			) );

			// Update payment ID meta and transaction ID
			$order->update_meta_data( '_nmi_cancel_id', $cancel_id );
			$order->update_meta_data( '_nmi_payment_id', $cancel_id );
			$order->set_transaction_id( $cancel_id );

			$order->update_status( 'cancelled', 'Payment cancelled manually via NMI.' );
			$order->save();

			wp_send_json_success( array(
				'message' => 'Payment cancelled successfully',
				'data' => $result['data']
			) );
		} else {
			// Log error
			$order->add_order_note( sprintf(
				'NMI cancel failed: %s',
				$result['message']
			) );
			
			wp_send_json_error( array( 'message' => $result['message'] ) );
		}
	}
	
	/**
	 * Get NMI Security Key from gateway settings.
	 *
	 * @return string
	 */
	private function get_security_key() {
		$gateway_settings = get_option( 'woocommerce_peachpay_nmi_card_settings', array() );
		return $gateway_settings['private_key'] ?? '';
	}

	/**
	 * Call NMI capture API.
	 *
	 * @param WC_Order $order Order object.
	 * @param string   $payment_id Payment ID.
	 * @param string   $currency Currency code.
	 * @param int      $amount Amount in minor units.
	 * @return array
	 */
	private function capture_payment_api( $order, $payment_id, $currency, $amount ) {
		try {
			// Get NMI Security Key from gateway settings
			$security_key = $this->get_security_key();

			if ( empty( $security_key ) ) {
				return array( 'success' => false, 'message' => 'NMI Security Key not configured' );
			}

			// NMI API URL - use same gateway as original auth; legacy orders without meta assumed Direct Post (Secure)
			$mode = $order->get_meta( '_nmi_payment_mode' );
			$is_direct_post = ( $mode === 'directpost' || ( empty( $mode ) && ! $order->get_meta( '_nmi_payment_method' ) ) );
			$api_url = PeachPay_NMI_Integration::get_api_endpoint();

			// Prepare request data for NMI API
			$request_data = array(
				'type'          => 'capture',
				'security_key'  => $security_key,
				'transactionid' => $payment_id,
				'amount'        => number_format( $amount / 100, 2, '.', '' ), // Convert cents to dollars
				'currency'      => $currency,
			);
			
			// Make API request
			$response = wp_remote_post( $api_url, array(
				'method' => 'POST',
				'timeout' => 30,
				'headers' => array(
					'Content-Type' => 'application/x-www-form-urlencoded'
				),
				'body' => http_build_query( $request_data )
			) );
			
			if ( is_wp_error( $response ) ) {
				return array( 'success' => false, 'message' => $response->get_error_message() );
			}
			
			$response_code = wp_remote_retrieve_response_code( $response );
			$response_body = wp_remote_retrieve_body( $response );
			
			if ( $response_code === 200 ) {
				// Parse NMI response (format: response=1&responsetext=SUCCESS&transactionid=...)
				parse_str( $response_body, $response_data );
				
				if ( isset( $response_data['response'] ) && $response_data['response'] == '1' ) {
					return array( 
						'success' => true, 
						'data' => array(
							'transactionid' => $response_data['transactionid'] ?? $payment_id,
							'originalPaymentId' => $payment_id,
							'status' => 'captured'
						)
					);
				} else {
					$error_message = $response_data['responsetext'] ?? 'Capture failed';
					return array( 'success' => false, 'message' => $error_message );
				}
			} else {
				return array( 'success' => false, 'message' => "HTTP $response_code error" );
			}
			
		} catch ( Exception $e ) {
			return array( 'success' => false, 'message' => $e->getMessage() );
		}
	}
	
	/**
	 * Call NMI cancel API.
	 *
	 * @param WC_Order $order Order object.
	 * @param string   $payment_id Payment ID.
	 * @return array
	 */
	private function cancel_payment_api( $order, $payment_id ) {
		try {
			// Get NMI Security Key from gateway settings
			$security_key = $this->get_security_key();

			if ( empty( $security_key ) ) {
				return array( 'success' => false, 'message' => 'NMI Security Key not configured' );
			}

			// NMI API URL - use same gateway as original auth; legacy orders without meta assumed Direct Post (Secure)
			$mode = $order->get_meta( '_nmi_payment_mode' );
			$is_direct_post = ( $mode === 'directpost' || ( empty( $mode ) && ! $order->get_meta( '_nmi_payment_method' ) ) );
			$api_url = PeachPay_NMI_Integration::get_api_endpoint();

			// Prepare request data for NMI API (void transaction)
			$request_data = array(
				'type'          => 'void',
				'security_key'  => $security_key,
				'transactionid' => $payment_id,
			);
			
			// Make API request
			$response = wp_remote_post( $api_url, array(
				'method' => 'POST',
				'timeout' => 30,
				'headers' => array(
					'Content-Type' => 'application/x-www-form-urlencoded'
				),
				'body' => http_build_query( $request_data )
			) );
			
			if ( is_wp_error( $response ) ) {
				return array( 'success' => false, 'message' => $response->get_error_message() );
			}
			
			$response_code = wp_remote_retrieve_response_code( $response );
			$response_body = wp_remote_retrieve_body( $response );
			
			if ( $response_code === 200 ) {
				// Parse NMI response
				parse_str( $response_body, $response_data );
				
				if ( isset( $response_data['response'] ) && $response_data['response'] == '1' ) {
					return array( 
						'success' => true, 
						'data' => array(
							'transactionid' => $response_data['transactionid'] ?? $payment_id,
							'originalPaymentId' => $payment_id,
							'status' => 'cancelled'
						)
					);
				} else {
					$error_message = $response_data['responsetext'] ?? 'Cancel failed';
					return array( 'success' => false, 'message' => $error_message );
				}
			} else {
				return array( 'success' => false, 'message' => "HTTP $response_code error" );
			}
			
		} catch ( Exception $e ) {
			return array( 'success' => false, 'message' => $e->getMessage() );
		}
	}
	
	/**
	 * Enqueue admin scripts for manual capture functionality.
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_admin_scripts( $hook ) {
		// Only load on admin pages
		if ( ! is_admin() ) {
			return;
		}
		
		// Check if this is likely an order page
		if ( strpos( $hook, 'wc-orders' ) !== false || 
			 $hook === 'post.php' || 
			 isset( $_GET['page'] ) && $_GET['page'] === 'wc-orders' ) {
			
			$script_path = dirname( __FILE__ ) . '/assets/js/manual-capture.js';
			if ( ! file_exists( $script_path ) ) {
				return; // Don't enqueue if file doesn't exist
			}
			
			$script_url = plugin_dir_url( __FILE__ ) . 'assets/js/manual-capture.js';
			
			wp_enqueue_script(
				'nmi-manual-capture',
				$script_url,
				array( 'jquery' ),
				'1.0.0',
				true
			);
			
			// Localize script with AJAX URL and nonce
			wp_localize_script( 'nmi-manual-capture', 'nmiManualCapture', array(
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'nonce' => wp_create_nonce( 'woocommerce-order-item' )
			) );
		}
	}
}

// TODO: Manual capture UI temporarily disabled.
// The integration for manual capture (including JS handlers and API calls)
// will be implemented in a future update. Do not remove this class or logic,
// only prevent the buttons from rendering for now.
// To re-enable, uncomment the line below:
// new PeachPay_NMI_Manual_Capture_Admin();

