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

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

/**
 * ConvesioPay Manual Capture Admin class.
 */
class PeachPay_ConvesioPay_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_convesiopay_capture_payment', array( $this, 'handle_capture_payment' ) );
		add_action( 'wp_ajax_peachpay_convesiopay_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.
	 * Note: Manual capture/cancel only applies to credit card payments, not cryptocurrency payments.
	 *
	 * @param WC_Order $order Order object.
	 */
	public function add_capture_cancel_buttons( $order ) {
		// Only show for ConvesioPay CARD orders
		// Manual capture/cancel is NOT applicable to BTCPay crypto payments because:
		// - Crypto payments are final once confirmed on blockchain
		// - There's no "authorization hold" concept like with credit cards
		// - Crypto transactions cannot be reversed or captured later
		if ( $order->get_payment_method() !== 'peachpay_convesiopay_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( '_convesiopay_payment_id' );
		if ( empty( $payment_id ) ) {
			return;
		}
		
		// Only show capture buttons if manual capture mode is enabled (manualPaymentCapture: true from API)
		$manual_capture_mode = $order->get_meta( '_convesiopay_manual_capture_mode' );
		if ( $manual_capture_mode !== 'yes' ) {
			return;
		}
		
		// Don't show if already captured
		$capture_id = $order->get_meta( '_convesiopay_capture_id' );
		if ( ! empty( $capture_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 for card payments only
		$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 (no wrapper div)
		// Capture button
		echo '<button type="button" class="button button-primary convesiopay-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 convesiopay-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 that JavaScript will show/hide
		echo '<span class="convesiopay-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 ConvesioPay capture API
		$result = $this->capture_payment_api( $payment_id, $currency, $amount );

		if ( $result['success'] ) {
			// Get capture ID from response
			$capture_id = $result['data']['id'];
			$original_payment_id = $result['data']['originalPaymentId'];

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

			// NOTE: We intentionally do NOT update _convesiopay_payment_id to keep the original payment ID
			// This ensures the Payment ID link continues to point to the original authorized payment
			// Check if payment ID has changed and update accordingly
			// $existing_payment_id = $order->get_meta( '_convesiopay_payment_id' );
			// if ( ! empty( $existing_payment_id ) && $existing_payment_id !== $capture_id ) {
			// 	$order->add_order_note( sprintf( __( 'ConvesioPay Payment ID updated from %s to %s (captured)', 'peachpay-for-woocommerce' ), $existing_payment_id, $capture_id ) );
			// }

			// Update capture ID meta and transaction ID (but NOT _convesiopay_payment_id)
			$order->update_meta_data( '_convesiopay_capture_id', $capture_id );
			// $order->update_meta_data( '_convesiopay_payment_id', $capture_id ); // Commented out to keep original payment ID
			$order->set_transaction_id( $capture_id );
			
			// IMPORTANT: Update payment status to "captured" to prevent the webhook handler
			// from failing/cancelling this order if a delayed or duplicate webhook arrives
			$order->update_meta_data( '_convesiopay_payment_status', 'captured' );

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

			wp_send_json_success( array(
				'message' => 'Payment captured successfully',
				'data' => $result['data']
			) );
		} else {
			$order->add_order_note( sprintf(
				'ConvesioPay 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 ConvesioPay cancel API
		$result = $this->cancel_payment_api( $payment_id );
		
		if ( $result['success'] ) {
			// Get cancel ID from response
			$cancel_id = $result['data']['id'];
			$original_payment_id = $result['data']['originalPaymentId'];
			$cancel_status = $result['data']['status'];

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

			// Check if payment ID has changed and update accordingly
			$existing_payment_id = $order->get_meta( '_convesiopay_payment_id' );
			if ( ! empty( $existing_payment_id ) && $existing_payment_id !== $cancel_id ) {
				$order->add_order_note( sprintf( __( 'ConvesioPay Payment ID updated from %s to %s (cancelled)', 'peachpay-for-woocommerce' ), $existing_payment_id, $cancel_id ) );
			}

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

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

			wp_send_json_success( array(
				'message' => 'Payment cancelled successfully',
				'data' => $result['data']
			) );
		} else {
			$order->add_order_note( sprintf(
				'ConvesioPay cancel failed: %s',
				$result['message']
			) );
			
			wp_send_json_error( array( 'message' => $result['message'] ) );
		}
	}
	
	/**
	 * Call ConvesioPay capture API.
	 *
	 * @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( $payment_id, $currency, $amount ) {
		try {
			// Get ConvesioPay configuration
			$config = PeachPay_ConvesioPay_Integration::config();
			$secret_key = $config['secret_key'] ?? '';
			
			if ( empty( $secret_key ) ) {
				return array( 'success' => false, 'message' => 'ConvesioPay secret key not configured' );
			}
			
			// Determine API URL
			$api_url = peachpay_is_test_mode() ? 'https://api-qa.convesiopay.com' : 'https://api.convesiopay.com';
			$capture_url = $api_url . '/v1/payments/' . $payment_id . '/capture';
			
			// Prepare request data
			$request_data = array(
				'currency' => $currency,
				'amount' => $amount
			);
			
			
			peachpay_log(
				'debug',
				'Payments: ConvesioPay Manual capture debug.',
				array(
					'event'     => 'payments.convesiopay_admin.capture.manual.debug',
					'component' => 'payments',
					'feature'   => 'convesiopay_admin',
					'operation' => 'capture.manual',
					'outcome'   => 'debug',
					'method'    => __METHOD__,
					'line'      => __LINE__,
					'data'      => array(
						'details' => 'ConvesioPay: Manual capture API request for payment ' . $payment_id . ' (amount: ' . ( $amount / 100 ) . ' ' . $currency . ')'
			)));

			// Make API request
			$response = wp_remote_post( $capture_url, array(
				'method' => 'POST',
				'timeout' => 30,
				'headers' => array(
					'Authorization' => $secret_key,
					'Content-Type' => 'application/json'
				),
				'body' => json_encode( $request_data )
			) );
			
			if ( is_wp_error( $response ) ) {
				peachpay_log(
					'error',
					'Payments: ConvesioPay Manual capture failed.',
					array(
						'event'     => 'payments.convesiopay_admin.capture.manual.failed',
						'component' => 'payments',
						'feature'   => 'convesiopay_admin',
						'operation' => 'capture.manual',
						'outcome'   => 'failed',
						'method'    => __METHOD__,
						'line'      => __LINE__,
						'data'      => array(
							'details' => 'ConvesioPay: Manual capture network error - ' . $response->get_error_message() . ' (payment ' . $payment_id . ')'
				)));
				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 ) {
				$response_data = json_decode( $response_body, true );
				peachpay_log(
					'info',
					'Payments: ConvesioPay Manual capture success.',
					array(
						'event'     => 'payments.convesiopay_admin.capture.manual.success',
						'component' => 'payments',
						'feature'   => 'convesiopay_admin',
						'operation' => 'capture.manual',
						'outcome'   => 'success',
						'method'    => __METHOD__,
						'line'      => __LINE__,
						'data'      => array(
							'details' => 'ConvesioPay: Manual capture success - payment ' . $payment_id
				)));
				return array( 'success' => true, 'data' => $response_data );
			} else {
				$error_data = json_decode( $response_body, true );
				$error_message = $error_data['message'] ?? "HTTP $response_code error";
				peachpay_log(
					'error',
					'Payments: ConvesioPay Manual capture failed.',
					array(
						'event'     => 'payments.convesiopay_admin.capture.manual.failed',
						'component' => 'payments',
						'feature'   => 'convesiopay_admin',
						'operation' => 'capture.manual',
						'outcome'   => 'failed',
						'method'    => __METHOD__,
						'line'      => __LINE__,
						'data'      => array(
							'details' => 'ConvesioPay: Manual capture API error - ' . $error_message . ' (payment ' . $payment_id . ')'
				)));
				return array( 'success' => false, 'message' => $error_message );
			}
			
		} catch ( Exception $e ) {
			return array( 'success' => false, 'message' => $e->getMessage() );
		}
	}
	
	/**
	 * Call ConvesioPay cancel API.
	 *
	 * @param string $payment_id Payment ID.
	 * @return array
	 */
	private function cancel_payment_api( $payment_id ) {
		try {
			// Get ConvesioPay configuration
			$config = PeachPay_ConvesioPay_Integration::config();
			$secret_key = $config['secret_key'] ?? '';
			
			if ( empty( $secret_key ) ) {
				return array( 'success' => false, 'message' => 'ConvesioPay secret key not configured' );
			}
			
			// Determine API URL
			$api_url = peachpay_is_test_mode() ? 'https://api-qa.convesiopay.com' : 'https://api.convesiopay.com';
			$cancel_url = $api_url . '/v1/payments/' . $payment_id . '/cancel';
			peachpay_log(
				'debug',
				'Payments: Manual cancel debug.',
				array(
					'event'     => 'payments.convesiopay_admin.cancel.manual.debug',
					'component' => 'payments',
					'feature'   => 'convesiopay_admin',
					'operation' => 'cancel.manual',
					'outcome'   => 'debug',
					'method'    => __METHOD__,
					'line'      => __LINE__,
					'data'      => array(
						'details' => 'ConvesioPay: Manual cancel API request for payment ' . $payment_id
				)));

			// Make API request (no body required for cancel)
			$response = wp_remote_post( $cancel_url, array(
				'method' => 'POST',
				'timeout' => 30,
				'headers' => array(
					'Authorization' => $secret_key,
					'Content-Type' => 'application/json'
				),
				'body' => '{}',
			) );
			
			if ( is_wp_error( $response ) ) {
				peachpay_log(
				'error',
				'Payments: ConvesioPay Manual cancel failed.',
				array(
					'event'     => 'payments.convesiopay_admin.cancel.manual.failed',
					'component' => 'payments',
					'feature'   => 'convesiopay_admin',
					'operation' => 'cancel.manual',
					'outcome'   => 'failed',
					'method'    => __METHOD__,
					'line'      => __LINE__,
					'data'      => array(
						'details' => 'ConvesioPay: Manual cancel network error - ' . $response->get_error_message() . ' (payment ' . $payment_id . ')'
				)));
				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 ) {
				$response_data = json_decode( $response_body, true );
				peachpay_log(
				'info',
				'Payments: Manual cancel success.',
				array(
					'event'     => 'payments.convesiopay_admin.cancel.manual.success',
					'component' => 'payments',
					'feature'   => 'convesiopay_admin',
					'operation' => 'cancel.manual',
					'outcome'   => 'success',
					'method'    => __METHOD__,
					'line'      => __LINE__,
					'data'      => array(
						'details' => 'ConvesioPay: Manual cancel success - payment ' . $payment_id
				)));
				return array( 'success' => true, 'data' => $response_data );
			} else {
				$error_data = json_decode( $response_body, true );
				$error_message = $error_data['message'] ?? "HTTP $response_code error";
				peachpay_log(
				'error',
				'Payments: Manual cancel failed.',
				array(
					'event'     => 'payments.convesiopay_admin.cancel.manual.failed',
					'component' => 'payments',
					'feature'   => 'convesiopay_admin',
					'operation' => 'cancel.manual',
					'outcome'   => 'failed',
					'method'    => __METHOD__,
					'line'      => __LINE__,
					'data'      => array(
						'details' => 'ConvesioPay: Manual cancel API error - ' . $error_message . ' (payment ' . $payment_id . ')'
				)));
				return array( 'success' => false, 'message' => $error_message );
			}
			
		} 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 ) {
		// TEMPORARY: Load on all admin pages for debugging
		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_url = plugin_dir_url( __FILE__ ) . 'assets/js/manual-capture.js';
			
			wp_enqueue_script(
				'convesiopay-manual-capture',
				$script_url,
				array( 'jquery' ),
				'1.0.2', // Increment version for cache busting
				true
			);
			
			// Localize script with AJAX URL and nonce
			wp_localize_script( 'convesiopay-manual-capture', 'convesiopayManualCapture', array(
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'nonce' => wp_create_nonce( 'woocommerce-order-item' )
			) );
			
		}
	}
}

// Initialize the manual capture admin functionality
new PeachPay_ConvesioPay_Manual_Capture_Admin();