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

class Woocom_Pay_Balance {

	public static function init(): void {
		add_action( 'init', [ __CLASS__, 'register_rewrite' ] );
		add_action( 'template_redirect', [ __CLASS__, 'handle_balance_page' ] );

		// AJAX handler for balance payment.
		add_action( 'wp_ajax_wcp_submit_balance', [ __CLASS__, 'handle_balance_submission' ] );
		add_action( 'wp_ajax_nopriv_wcp_submit_balance', [ __CLASS__, 'handle_balance_submission' ] );

		// Admin: generate balance payment link.
		add_action( 'woocommerce_order_actions', [ __CLASS__, 'add_order_action' ] );
		add_action( 'woocommerce_order_action_wcp_generate_balance_link', [ __CLASS__, 'generate_balance_link_action' ] );
	}

	public static function register_rewrite(): void {
		add_rewrite_rule( '^pay-balance/([0-9]+)/?$', 'index.php?wcp_balance_order=$matches[1]', 'top' );
		add_filter( 'query_vars', function ( $vars ) {
			$vars[] = 'wcp_balance_order';
			return $vars;
		} );
	}

	public static function handle_balance_page(): void {
		$order_id = (int) get_query_var( 'wcp_balance_order' );
		if ( ! $order_id ) {
			return;
		}

		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			wp_die( esc_html__( 'Order not found.', 'woocom-pay' ) );
		}

		$settings      = get_option( 'woocom_pay_settings', [] );
		$gw_settings   = get_option( 'woocommerce_woocom_pay_settings', [] );
		$merchant_name = $gw_settings['merchant_name'] ?? ( $settings['merchant_name'] ?? get_bloginfo( 'name' ) );
		$upi_id        = $gw_settings['upi_id'] ?? ( $settings['upi_id'] ?? '' );
		$qr_image      = $gw_settings['qr_image'] ?? ( $settings['qr_image'] ?? '' );
		$balance       = (float) $order->get_meta( '_wcp_balance_amount' );

		if ( $balance <= 0 ) {
			wp_die( esc_html__( 'No balance is due for this order.', 'woocom-pay' ) );
		}

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

		$is_mobile = wp_is_mobile();

		// Available gateways for balance payment (same set as checkout).
		$manager            = WCP_Gateway_Manager::instance();
		$available_gateways = $manager->get_available();
		$default_method     = $order->get_meta( '_wcp_payment_method' ) ?: 'upi';
		// Default to first available if the original method is no longer configured.
		if ( ! isset( $available_gateways[ $default_method ] ) ) {
			$default_method = key( $available_gateways ) ?: 'upi';
		}

		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_balance' ),
			'balanceLinkNonce' => wp_create_nonce( 'wcp_create_balance_link' ),
			'orderId'          => $order_id,
			'action'           => 'wcp_submit_balance',
		] );

		get_header();
		include WOOCOM_PAY_PLUGIN_DIR . 'public/views/balance-payment.php';
		get_footer();
		exit;
	}

	public static function handle_balance_submission(): void {
		check_ajax_referer( 'wcp_submit_balance', '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' ) ] );
		}

		$settings           = get_option( 'woocom_pay_settings', [] );
		$enable_approval    = ! empty( $settings['enable_approval'] );
		$enable_txn_id      = ! empty( $settings['enable_txn_id'] );
		$enable_screenshot  = ! empty( $settings['enable_screenshot'] );

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

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

		$balance  = (float) $order->get_meta( '_wcp_balance_amount' );
		$items    = $order->get_items();
		$first    = reset( $items );
		$product_id = $first ? (int) $first->get_product_id() : 0;

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

		if ( $enable_approval ) {
			$order->update_status( 'bal-submitted', __( 'Balance payment submitted, awaiting admin verification.', 'woocom-pay' ) );
			Woocom_Pay_Emails::send_admin_balance_submitted( $order );
		} else {
			$order->update_meta_data( '_wcp_balance_amount', 0 );
			$order->update_status( 'completed', __( 'Balance payment completed.', 'woocom-pay' ) );
			$order->payment_complete( $txn_id );
			Woocom_Pay_Emails::send_customer_payment_approved( $order );
		}

		$order->save();

		wp_send_json_success( [
			'message' => __( 'Balance payment submitted successfully!', 'woocom-pay' ),
		] );
	}

	public static function get_balance_link( int $order_id ): string {
		return home_url( "/pay-balance/{$order_id}/" );
	}

	public static function add_order_action( array $actions ): array {
		$actions['wcp_generate_balance_link'] = __( 'Woocom-Pay: Copy Balance Payment Link', 'woocom-pay' );
		return $actions;
	}

	public static function generate_balance_link_action( WC_Order $order ): void {
		$link = self::get_balance_link( $order->get_id() );
		$order->add_order_note( sprintf(
			/* translators: %s: balance payment link */
			__( 'Balance payment link generated: %s', 'woocom-pay' ),
			esc_url( $link )
		) );

		Woocom_Pay_Emails::send_customer_balance_reminder( $order, $link );
	}
}
