<?php
defined( 'ABSPATH' ) || exit;

class Woocom_Pay_Gateway extends WC_Payment_Gateway {

	public function __construct() {
		$this->id                 = 'woocom_pay';
		$this->icon               = WOOCOM_PAY_PLUGIN_URL . 'assets/logo.PNG';
		$this->has_fields         = true;
		$this->method_title       = __( 'UPI Payment (Woocom-Pay)', 'woocom-pay' );
		$this->method_description = __( 'Accept payments via any UPI application without a payment gateway.', 'woocom-pay' );
		$this->supports           = [ 'products' ];

		$this->init_form_fields();
		$this->init_settings();

		$this->title       = $this->get_option( 'title', __( 'UPI Payment', 'woocom-pay' ) );
		$this->description = $this->get_option( 'description', __( 'Pay using Google Pay, PhonePe, Paytm, BHIM, or any UPI app.', 'woocom-pay' ) );
		$this->enabled     = $this->get_option( 'enabled', 'yes' );

		add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, [ $this, 'process_payment_settings' ] );
		add_action( 'woocommerce_thankyou_' . $this->id, [ $this, 'render_payment_page' ] );
		add_action( 'woocommerce_receipt_' . $this->id, [ $this, 'render_payment_page' ] );

		// Shrink the gateway icon on checkout.
		add_filter( 'woocommerce_gateway_icon', [ $this, 'filter_gateway_icon' ], 10, 2 );

		// Load CSS + copy-button JS on checkout page.
		add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_checkout_assets' ] );

		// Load media picker on the gateway settings page.
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_gateway_admin_assets' ] );

		// AJAX handlers for transaction submission.
		add_action( 'wp_ajax_wcp_submit_transaction', [ $this, 'handle_transaction_submission' ] );
		add_action( 'wp_ajax_nopriv_wcp_submit_transaction', [ $this, 'handle_transaction_submission' ] );
	}

	public function filter_gateway_icon( string $icon_html, string $gateway_id ): string {
		if ( $gateway_id !== $this->id ) {
			return $icon_html;
		}
		return '<img src="' . esc_url( WOOCOM_PAY_PLUGIN_URL . 'assets/logo.PNG' ) . '" alt="' . esc_attr( $this->title ) . '" style="max-height:28px;width:auto;vertical-align:middle;">';
	}

	public function enqueue_checkout_assets(): void {
		if ( ! is_checkout() && ! is_wc_endpoint_url() ) {
			return;
		}
		wp_enqueue_style( 'woocom-pay-public', WOOCOM_PAY_PLUGIN_URL . 'public/css/public.css', [], WOOCOM_PAY_VERSION );
		wp_enqueue_script( 'woocom-pay-public', WOOCOM_PAY_PLUGIN_URL . 'public/js/public.js', [ 'jquery' ], WOOCOM_PAY_VERSION, true );
	}

	public function enqueue_gateway_admin_assets( string $hook ): void {
		// Only load on the WooCommerce payment gateway settings page for this gateway.
		$screen = get_current_screen();
		if ( ! $screen ) {
			return;
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$is_gateway_page = ( $hook === 'woocommerce_page_wc-settings' )
			&& isset( $_GET['tab'] ) && $_GET['tab'] === 'checkout'
			&& isset( $_GET['section'] ) && $_GET['section'] === $this->id;

		if ( ! $is_gateway_page ) {
			return;
		}

		wp_enqueue_media();
		wp_add_inline_script( 'jquery', $this->gateway_admin_js() );
	}

	private function gateway_admin_js(): string {
		return <<<'JS'
jQuery( function( $ ) {
	// Upload QR button.
	$( document ).on( 'click', '.wcp-upload-qr-btn', function( e ) {
		e.preventDefault();
		var targetId  = $( this ).data( 'target' );
		var previewId = $( this ).data( 'preview' );
		var frame = wp.media( {
			title: 'Select UPI QR Code Image',
			button: { text: 'Use this image' },
			multiple: false,
			library: { type: 'image' }
		} );
		frame.on( 'select', function() {
			var att = frame.state().get( 'selection' ).first().toJSON();
			$( '#' + targetId ).val( att.url );
			var $preview = $( '#' + previewId );
			$preview.find( 'img' ).attr( 'src', att.url );
			$preview.show();
		} );
		frame.open();
	} );

	// Remove QR button.
	$( document ).on( 'click', '.wcp-remove-qr-btn', function( e ) {
		e.preventDefault();
		var targetId  = $( this ).data( 'target' );
		var previewId = $( this ).data( 'preview' );
		$( '#' + targetId ).val( '' );
		$( '#' + previewId ).hide();
	} );
} );
JS;
	}

	public function payment_fields(): void {
		$manager   = WCP_Gateway_Manager::instance();
		$available = $manager->get_available();

		if ( empty( $available ) ) {
			echo '<p class="wcp-checkout-desc">' . esc_html__( 'No payment methods are currently available. Please contact the store owner.', 'woocom-pay' ) . '</p>';
			return;
		}

		if ( $this->description ) {
			echo '<p class="wcp-checkout-desc">' . wp_kses_post( $this->description ) . '</p>';
		}

		if ( count( $available ) > 1 ) {
			echo '<div class="wcp-pm-selector">';
			echo '<p class="wcp-pm-label">' . esc_html__( 'Select payment method:', 'woocom-pay' ) . '</p>';
			$first = true;
			foreach ( $available as $id => $gw ) {
				echo '<label class="wcp-pm-option' . ( $first ? ' wcp-pm-active' : '' ) . '">';
				echo '<input type="radio" name="wcp_payment_method" value="' . esc_attr( $id ) . '"'
					. ( $first ? ' checked' : '' ) . '>';
				echo '<span class="wcp-pm-name">' . esc_html( $gw->get_label() ) . '</span>';
				echo '</label>';
				$first = false;
			}
			echo '</div>';
		} else {
			$id = key( $available );
			echo '<input type="hidden" name="wcp_payment_method" value="' . esc_attr( $id ) . '">';
		}

		// Show UPI destination block if UPI is one of the available methods.
		if ( isset( $available['upi'] ) ) {
			$shared        = get_option( 'woocom_pay_settings', [] );
			$upi_id        = $this->get_option( 'upi_id', $shared['upi_id'] ?? '' );
			$merchant_name = $this->get_option( 'merchant_name', $shared['merchant_name'] ?? get_bloginfo( 'name' ) );

			$extra_class = count( $available ) > 1 ? ' wcp-pm-detail' : '';
			echo '<div class="wcp-checkout-vpa' . esc_attr( $extra_class ) . '" data-for-method="upi">';
			if ( $merchant_name ) {
				echo '<span class="wcp-checkout-vpa-name">' . esc_html( $merchant_name ) . '</span>';
			}
			if ( $upi_id ) {
				echo '<div class="wcp-checkout-vpa-row">';
				echo '<span class="wcp-checkout-vpa-label">' . esc_html__( 'UPI / VPA ID:', 'woocom-pay' ) . '</span>';
				echo '<span class="wcp-checkout-vpa-id">' . esc_html( $upi_id ) . '</span>';
				echo '<button type="button" class="wcp-copy-btn wcp-checkout-copy" data-copy="' . esc_attr( $upi_id ) . '">'
					. esc_html__( 'Copy', 'woocom-pay' ) . '</button>';
				echo '</div>';
				echo '<p class="wcp-checkout-vpa-hint">'
					. esc_html__( 'You will be redirected to complete your payment after placing the order.', 'woocom-pay' )
					. '</p>';
			}
			echo '</div>';
		}

		// For non-UPI gateways, show a short description block.
		// The first selected method's block is visible; others hidden.
		$default_method = key( $available );
		foreach ( $available as $id => $gw ) {
			if ( $id === 'upi' ) {
				continue;
			}
			// Show if this is the first selected method AND UPI is not available.
			$visible = ( $id === $default_method && ! isset( $available['upi'] ) );
			echo '<div class="wcp-pm-detail" data-for-method="' . esc_attr( $id ) . '"'
				. ( $visible ? '' : ' style="display:none;"' ) . '>';
			echo '<p class="wcp-checkout-vpa-hint">'
				. esc_html__( 'You will be redirected to a secure hosted payment page after placing the order.', 'woocom-pay' )
				. '</p>';
			echo '</div>';
		}
	}

	public function init_form_fields(): void {
		$this->form_fields = [
			'enabled' => [
				'title'   => __( 'Enable/Disable', 'woocom-pay' ),
				'type'    => 'checkbox',
				'label'   => __( 'Enable UPI Payment', 'woocom-pay' ),
				'default' => 'yes',
			],

			// ── Merchant / UPI section ─────────────────────────────
			'section_merchant' => [
				'title'       => __( 'Merchant & UPI Details', 'woocom-pay' ),
				'type'        => 'title',
				'description' => __( 'These details are shown to the customer on the checkout and payment pages.', 'woocom-pay' ),
			],
			'merchant_name' => [
				'title'       => __( 'Merchant Name', 'woocom-pay' ),
				'type'        => 'text',
				'description' => __( 'Your business name displayed to the customer during payment.', 'woocom-pay' ),
				'default'     => get_bloginfo( 'name' ),
				'desc_tip'    => true,
				'placeholder' => __( 'e.g. Touch2me Technologies', 'woocom-pay' ),
			],
			'upi_id' => [
				'title'       => __( 'UPI / VPA ID', 'woocom-pay' ),
				'type'        => 'text',
				'description' => __( 'Your UPI Virtual Payment Address (VPA). Customers will send money here.', 'woocom-pay' ),
				'default'     => '',
				'desc_tip'    => true,
				'placeholder' => __( 'e.g. yourname@okicici', 'woocom-pay' ),
			],
			'qr_image' => [
				'title'       => __( 'UPI QR Code', 'woocom-pay' ),
				'type'        => 'qr_image',
				'description' => __( 'Upload your UPI QR code image (PNG/JPG/WEBP). Shown on desktop so customers can scan directly.', 'woocom-pay' ),
				'default'     => '',
			],

			// ── Display section ───────────────────────────────────
			'section_display' => [
				'title' => __( 'Display', 'woocom-pay' ),
				'type'  => 'title',
			],
			'title' => [
				'title'       => __( 'Payment Method Title', 'woocom-pay' ),
				'type'        => 'text',
				'description' => __( 'Label shown on the checkout page payment method list.', 'woocom-pay' ),
				'default'     => __( 'UPI Payment', 'woocom-pay' ),
				'desc_tip'    => true,
			],
			'description' => [
				'title'       => __( 'Description', 'woocom-pay' ),
				'type'        => 'textarea',
				'description' => __( 'Short description shown below the payment method title on checkout.', 'woocom-pay' ),
				'default'     => __( 'Pay using Google Pay, PhonePe, Paytm, BHIM, or any UPI app.', 'woocom-pay' ),
				'desc_tip'    => true,
			],
		];
	}

	// ── Custom field: QR image with media picker ──────────────────

	public function generate_qr_image_html( string $key, array $data ): string {
		$field_key   = $this->get_field_key( $key );
		$current_url = $this->get_option( $key, '' );
		$title       = $data['title'] ?? '';
		$description = $data['description'] ?? '';

		ob_start();
		?>
		<tr valign="top">
			<th scope="row" class="titledesc">
				<label for="<?php echo esc_attr( $field_key ); ?>"><?php echo esc_html( $title ); ?></label>
			</th>
			<td class="forminp">
				<fieldset>
					<?php if ( $current_url ) : ?>
					<div id="<?php echo esc_attr( $field_key ); ?>_preview" style="margin-bottom:10px;">
						<img src="<?php echo esc_url( $current_url ); ?>"
							style="max-width:160px;max-height:160px;border:1px solid #ddd;padding:6px;border-radius:6px;display:block;">
					</div>
					<?php else : ?>
					<div id="<?php echo esc_attr( $field_key ); ?>_preview" style="display:none;margin-bottom:10px;">
						<img src="" style="max-width:160px;max-height:160px;border:1px solid #ddd;padding:6px;border-radius:6px;display:block;">
					</div>
					<?php endif; ?>

					<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
						<input type="text"
							id="<?php echo esc_attr( $field_key ); ?>"
							name="<?php echo esc_attr( $field_key ); ?>"
							value="<?php echo esc_attr( $current_url ); ?>"
							class="regular-text"
							placeholder="<?php esc_attr_e( 'Image URL or upload below', 'woocom-pay' ); ?>"
							style="max-width:360px;">
						<button type="button"
							class="button wcp-upload-qr-btn"
							data-target="<?php echo esc_attr( $field_key ); ?>"
							data-preview="<?php echo esc_attr( $field_key ); ?>_preview">
							&#128247; <?php esc_html_e( 'Upload QR Image', 'woocom-pay' ); ?>
						</button>
						<?php if ( $current_url ) : ?>
						<button type="button"
							class="button wcp-remove-qr-btn"
							data-target="<?php echo esc_attr( $field_key ); ?>"
							data-preview="<?php echo esc_attr( $field_key ); ?>_preview">
							<?php esc_html_e( 'Remove', 'woocom-pay' ); ?>
						</button>
						<?php endif; ?>
					</div>

					<?php if ( $description ) : ?>
					<p class="description"><?php echo esc_html( $description ); ?></p>
					<?php endif; ?>
				</fieldset>
			</td>
		</tr>
		<?php
		return ob_get_clean();
	}

	public function validate_qr_image_field( string $key, $value ): string {
		return esc_url_raw( sanitize_text_field( $value ) );
	}

	public function process_payment_settings(): void {
		$this->process_admin_options();

		// Sync UPI ID, QR, and merchant name to the shared woocom_pay_settings option
		// so the Woocom-Pay settings page and all reading code stays in sync.
		$shared = get_option( 'woocom_pay_settings', [] );
		$shared['merchant_name'] = $this->get_option( 'merchant_name', '' );
		$shared['upi_id']        = $this->get_option( 'upi_id', '' );
		$shared['qr_image']      = $this->get_option( 'qr_image', '' );
		update_option( 'woocom_pay_settings', $shared );
	}

	public function process_payment( $order_id ): array {
		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			return [ 'result' => 'failure' ];
		}

		$method  = sanitize_key( $_POST['wcp_payment_method'] ?? 'upi' ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
		$manager = WCP_Gateway_Manager::instance();
		$gateway = $manager->get( $method );

		if ( ! $gateway || ! $gateway->is_enabled() || ! $gateway->is_configured() ) {
			wc_add_notice( __( 'The selected payment method is not available. Please try again.', 'woocom-pay' ), 'error' );
			return [ 'result' => 'failure' ];
		}

		// Server-side Pro check: block API gateway usage without a valid license.
		if ( $method !== 'upi' && ! WCP_License::is_pro() ) {
			wc_add_notice( __( 'This payment method requires Woocom-Pay Pro. Please choose UPI or contact the store owner.', 'woocom-pay' ), 'error' );
			return [ 'result' => 'failure' ];
		}

		$order->update_meta_data( '_wcp_payment_method', $method );

		$has_partial = $order->get_meta( '_wcp_has_partial' );
		$amount      = $has_partial ? (float) $order->get_meta( '_wcp_paid_amount' ) : (float) $order->get_total();

		if ( $method === 'upi' ) {
			$order->update_status( 'awaiting-pay', __( 'Awaiting UPI payment.', 'woocom-pay' ) );
			$order->save();
			WC()->cart->empty_cart();
			return [ 'result' => 'success', 'redirect' => $order->get_checkout_order_received_url() ];
		}

		// API gateway: create a hosted payment link and redirect there.
		$return_url  = home_url( "/?wc-api=woocom_pay_{$method}&order_id={$order->get_id()}" );
		$payment_url = $gateway->create_payment( $order, $amount, $return_url );

		if ( is_wp_error( $payment_url ) ) {
			wc_add_notice( $payment_url->get_error_message(), 'error' );
			return [ 'result' => 'failure' ];
		}

		$order->update_status(
			'awaiting-pay',
			sprintf( __( 'Awaiting payment via %s.', 'woocom-pay' ), $gateway->get_label() )
		);
		$order->save();
		WC()->cart->empty_cart();

		return [ 'result' => 'success', 'redirect' => $payment_url ];
	}

	public function render_payment_page( int $order_id ): void {
		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			return;
		}

		$method = $order->get_meta( '_wcp_payment_method' ) ?: 'upi';

		// API gateway payments are processed externally; show a simple confirmation here.
		if ( $method !== 'upi' ) {
			$this->render_gateway_thankyou( $order, $method );
			return;
		}

		// ── UPI flow (unchanged) ───────────────────────────────────────────────
		$shared            = get_option( 'woocom_pay_settings', [] );
		$merchant_name     = $this->get_option( 'merchant_name', $shared['merchant_name'] ?? get_bloginfo( 'name' ) );
		$upi_id            = $this->get_option( 'upi_id', $shared['upi_id'] ?? '' );
		$qr_image          = $this->get_option( 'qr_image', $shared['qr_image'] ?? '' );
		$enable_txn_id     = ! empty( $shared['enable_txn_id'] );
		$enable_screenshot = ! empty( $shared['enable_screenshot'] );

		$has_partial = $order->get_meta( '_wcp_has_partial' );
		$paid_amount = (float) $order->get_meta( '_wcp_paid_amount' );
		$balance     = (float) $order->get_meta( '_wcp_balance_amount' );
		$amount      = $has_partial ? $paid_amount : (float) $order->get_total();

		$upi_url = 'upi://pay?' . http_build_query( [
			'pa' => $upi_id,
			'pn' => $merchant_name,
			'am' => number_format( $amount, 2, '.', '' ),
			'cu' => 'INR',
			'tn' => 'Order-' . $order_id,
		] );

		$is_mobile = wp_is_mobile();

		wp_enqueue_style( 'woocom-pay-public', WOOCOM_PAY_PLUGIN_URL . 'public/css/public.css', [], WOOCOM_PAY_VERSION );
		wp_enqueue_script( 'woocom-pay-public', WOOCOM_PAY_PLUGIN_URL . 'public/js/public.js', [ 'jquery' ], WOOCOM_PAY_VERSION, true );
		wp_localize_script( 'woocom-pay-public', 'wcpData', [
			'ajaxUrl' => admin_url( 'admin-ajax.php' ),
			'nonce'   => wp_create_nonce( 'wcp_submit_transaction' ),
			'orderId' => $order_id,
		] );

		include WOOCOM_PAY_PLUGIN_DIR . 'public/views/payment-page.php';
	}

	private function render_gateway_thankyou( WC_Order $order, string $method ): void {
		$manager = WCP_Gateway_Manager::instance();
		$gateway = $manager->get( $method );
		$label   = $gateway ? $gateway->get_label() : ucfirst( $method );

		$status  = $order->get_status();
		$is_paid = in_array( $status, [ 'pay-verified', 'bal-pending', 'completed', 'processing' ], true );

		wp_enqueue_style( 'woocom-pay-public', WOOCOM_PAY_PLUGIN_URL . 'public/css/public.css', [], WOOCOM_PAY_VERSION );
		?>
		<div class="wcp-payment-wrap">
			<div class="wcp-payment-card">
				<div class="wcp-payment-header">
					<img src="<?php echo esc_url( WOOCOM_PAY_PLUGIN_URL . 'assets/logo.PNG' ); ?>" alt="Woocom-Pay" class="wcp-logo">
					<?php if ( $is_paid ) : ?>
					<h2><?php esc_html_e( 'Payment Received!', 'woocom-pay' ); ?></h2>
					<?php else : ?>
					<h2><?php esc_html_e( 'Payment Pending', 'woocom-pay' ); ?></h2>
					<?php endif; ?>
					<p class="wcp-header-sub"><?php echo esc_html( sprintf( __( 'Order #%s', 'woocom-pay' ), $order->get_order_number() ) ); ?></p>
				</div>
				<div class="wcp-success-box" style="display:block;">
					<?php if ( $is_paid ) : ?>
					<div class="wcp-success-icon">&#10003;</div>
					<h3><?php echo esc_html( sprintf( __( 'Paid via %s', 'woocom-pay' ), $label ) ); ?></h3>
					<p><?php esc_html_e( 'Your payment was received successfully. We will process your order shortly.', 'woocom-pay' ); ?></p>
					<?php else : ?>
					<p><?php esc_html_e( 'Your payment is being processed. You will receive an email confirmation soon.', 'woocom-pay' ); ?></p>
					<?php endif; ?>
				</div>
			</div>
		</div>
		<?php
	}

	public function handle_transaction_submission(): void {
		check_ajax_referer( 'wcp_submit_transaction', 'nonce' );

		$order_id  = (int) ( $_POST['order_id'] ?? 0 );
		$txn_id    = sanitize_text_field( $_POST['transaction_id'] ?? '' );
		$remarks   = sanitize_textarea_field( $_POST['remarks'] ?? '' );

		if ( ! $order_id ) {
			wp_send_json_error( [ 'message' => __( 'Invalid order.', 'woocom-pay' ) ] );
		}

		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			wp_send_json_error( [ 'message' => __( 'Order not found.', 'woocom-pay' ) ] );
		}

		// Verify order ownership (guest checkout allowed by matching order key in session or order email).
		$settings = get_option( 'woocom_pay_settings', [] );
		$enable_txn_id     = ! empty( $settings['enable_txn_id'] );
		$enable_screenshot = ! empty( $settings['enable_screenshot'] );
		$enable_approval   = ! empty( $settings['enable_approval'] );

		if ( $enable_txn_id && empty( $txn_id ) ) {
			wp_send_json_error( [ 'message' => __( 'Transaction ID is required.', 'woocom-pay' ) ] );
		}

		// Handle screenshot upload.
		$screenshot_path = '';
		if ( $enable_screenshot && ! empty( $_FILES['screenshot'] ) && $_FILES['screenshot']['error'] === UPLOAD_ERR_OK ) {
			$result = self::handle_screenshot_upload( $_FILES['screenshot'] );
			if ( is_wp_error( $result ) ) {
				wp_send_json_error( [ 'message' => $result->get_error_message() ] );
			}
			$screenshot_path = $result;
		}

		$has_partial  = $order->get_meta( '_wcp_has_partial' );
		$paid_amount  = $has_partial ? (float) $order->get_meta( '_wcp_paid_amount' ) : (float) $order->get_total();
		$balance      = $has_partial ? (float) $order->get_meta( '_wcp_balance_amount' ) : 0.0;
		$product_total = $has_partial ? (float) $order->get_meta( '_wcp_product_total' ) : $paid_amount;
		$payment_type = $has_partial ? 'partial' : 'full';

		// Get first product.
		$items      = $order->get_items();
		$first_item = reset( $items );
		$product_id = $first_item ? (int) $first_item->get_product_id() : 0;

		$txn_record_id = Woocom_Pay_DB::insert( [
			'order_id'            => $order_id,
			'customer_id'         => (int) $order->get_customer_id(),
			'product_id'          => $product_id,
			'payment_type'        => $payment_type,
			'product_price'       => $product_total,
			'paid_amount'         => $paid_amount,
			'balance_amount'      => $balance,
			'transaction_id'      => $txn_id,
			'screenshot_path'     => $screenshot_path,
			'remarks'             => $remarks,
			'verification_status' => $enable_approval ? 'pending' : 'approved',
		] );

		if ( ! $txn_record_id ) {
			wp_send_json_error( [ 'message' => __( 'Could not save transaction. Please try again.', 'woocom-pay' ) ] );
		}

		$order->update_meta_data( '_wcp_txn_record_id', $txn_record_id );

		if ( $enable_approval ) {
			$order->update_status( 'pay-submitted', __( 'UPI payment submitted, awaiting admin verification.', 'woocom-pay' ) );
			Woocom_Pay_Emails::send_customer_payment_submitted( $order );
			Woocom_Pay_Emails::send_admin_payment_submitted( $order );
		} else {
			if ( $payment_type === 'partial' ) {
				$order->update_status( 'bal-pending', __( 'Advance payment verified. Balance pending.', 'woocom-pay' ) );
			} else {
				$order->update_status( 'pay-verified', __( 'Payment auto-verified.', 'woocom-pay' ) );
				$order->payment_complete( $txn_id );
			}
			Woocom_Pay_Emails::send_customer_payment_approved( $order );
		}

		$order->save();

		wp_send_json_success( [
			'message'  => __( 'Payment details submitted successfully!', 'woocom-pay' ),
			'redirect' => $order->get_view_order_url(),
		] );
	}

	public static function handle_screenshot_upload( array $file ): string|WP_Error {
		$allowed_types = [ 'image/jpeg', 'image/png', 'image/gif', 'image/webp' ];
		$finfo         = finfo_open( FILEINFO_MIME_TYPE );
		$mime          = finfo_file( $finfo, $file['tmp_name'] );
		finfo_close( $finfo );

		if ( ! in_array( $mime, $allowed_types, true ) ) {
			return new WP_Error( 'invalid_file', __( 'Only JPG, PNG, GIF, and WEBP images are allowed.', 'woocom-pay' ) );
		}

		if ( $file['size'] > 5 * 1024 * 1024 ) {
			return new WP_Error( 'file_too_large', __( 'Screenshot must be under 5MB.', 'woocom-pay' ) );
		}

		$upload  = wp_upload_dir();
		$dir     = $upload['basedir'] . '/woocom-pay-screenshots/';
		$ext     = pathinfo( $file['name'], PATHINFO_EXTENSION );
		$ext     = strtolower( preg_replace( '/[^a-z0-9]/i', '', $ext ) );
		$name    = wp_unique_filename( $dir, 'txn-' . time() . '.' . $ext );
		$dest    = $dir . $name;

		if ( ! move_uploaded_file( $file['tmp_name'], $dest ) ) {
			return new WP_Error( 'upload_failed', __( 'Failed to upload screenshot.', 'woocom-pay' ) );
		}

		return $upload['baseurl'] . '/woocom-pay-screenshots/' . $name;
	}
}
