<?php

namespace Devikit\Ifirma;

use Devikit\Ifirma\Admin\Settings;
use Devikit\Ifirma\Api\Client;

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

class InvoiceManager {

	/**
	 * @var Client
	 */
	private $api_client;

	/**
	 * @var Settings
	 */
	private $settings;

	/**
	 * Constructor
	 * 
	 * @param Client $api_client
	 * @param Settings $settings
	 */
	public function __construct( Client $api_client, Settings $settings ) {
		$this->api_client = $api_client;
		$this->settings = $settings;

		add_action( 'add_meta_boxes', [ $this, 'add_order_meta_box' ] );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_metabox_scripts' ] );
		add_action( 'wp_ajax_devikit_ifirma_create_invoice', [ $this, 'ajax_create_invoice' ] );
		add_action( 'wp_ajax_devikit_ifirma_download_pdf', [ $this, 'ajax_download_pdf' ] );
		add_action( 'wp_ajax_devikit_ifirma_send_invoice_email', [ $this, 'ajax_send_invoice_email' ] );
		
		// Delayed invoice email handler (Action Scheduler) — 5 min for KSeF
		add_action( 'devikit_ifirma_send_delayed_invoice_email', [ $this, 'handle_delayed_invoice_email' ], 10, 2 );
		
		// Frontend downloads (My Account -> single order view only)
		add_action( 'woocommerce_order_details_after_customer_details', [ $this, 'display_document_download_buttons' ], 20 );
		add_action( 'template_redirect', [ $this, 'handle_invoice_download' ] );
		add_action( 'template_redirect', [ $this, 'handle_proforma_download' ] );
		add_action( 'template_redirect', [ $this, 'handle_rachunek_download' ] );
	}

	/**
	 * Resolve the tax identifier (NIP / EU VAT / foreign Tax ID) for a given order.
	 *
	 * Czyta z wielu potencjalnych pól meta zamówienia (również z zewnętrznych wtyczek,
	 * np. WooCommerce EU VAT Number, nip-field-for-woocommerce, itp.) i zwraca pierwsze
	 * niepuste. Dzięki temu wartość trafia do iFirma pod jedną etykietą NIP niezależnie
	 * od tego, w którym polu klient ją wpisał.
	 *
	 * Lista kluczy jest filtrowalna przez `devikit_ifirma_order_tax_id_meta_keys`.
	 * Finalną wartość można nadpisać filtrem `devikit_ifirma_order_tax_id`.
	 *
	 * @param \WC_Order|int|null $order Order object or order ID.
	 * @return string Tax identifier or empty string.
	 */
	public static function get_order_tax_id( $order ) {
		if ( is_numeric( $order ) ) {
			$order = wc_get_order( (int) $order );
		}
		if ( ! $order instanceof \WC_Order ) {
			return '';
		}

		$default_keys = [
			'_billing_nip',
			'vat_number',
			'_vat_number',
			'_billing_vat_number',
			'_billing_tax_number',
			'_tax_number',
			'_billing_euvatno',
			'_wc_billing/devikit-ifirma/billing_nip',
			'_wc_billing/nip-field-wc/billing_nip',
		];

		$keys = apply_filters( 'devikit_ifirma_order_tax_id_meta_keys', $default_keys, $order );
		if ( ! is_array( $keys ) ) {
			$keys = $default_keys;
		}

		$tax_id = '';
		foreach ( $keys as $key ) {
			if ( ! is_string( $key ) || $key === '' ) {
				continue;
			}
			$value = $order->get_meta( $key );
			if ( is_string( $value ) && trim( $value ) !== '' ) {
				$tax_id = trim( $value );
				break;
			}
		}

		return (string) apply_filters( 'devikit_ifirma_order_tax_id', $tax_id, $order, $keys );
	}

	/**
	 * Add Meta Box
	 */
	public function add_order_meta_box() {
		add_meta_box(
			'devikit_ifirma_invoice',
			__( 'iFirma Invoice', 'invoicing-integration-for-ifirma-and-woocommerce' ),
			[ $this, 'render_meta_box' ],
			'shop_order',
			'side',
			'high'
		);
		
		// HPOS support
		if ( class_exists( '\Automattic\WooCommerce\Internal\DataStores\Orders\CustomOrdersTableController' ) && wc_get_container()->get( \Automattic\WooCommerce\Internal\DataStores\Orders\CustomOrdersTableController::class )->custom_orders_table_usage_is_enabled() ) {
			add_meta_box(
				'devikit_ifirma_invoice',
				__( 'iFirma Invoice', 'invoicing-integration-for-ifirma-and-woocommerce' ),
				[ $this, 'render_meta_box' ],
				wc_get_page_screen_id( 'shop_order' ),
				'side',
				'high'
			);
		}
	}
	
	/**
	 * Enqueue metabox scripts
	 */
	public function enqueue_metabox_scripts( $hook_suffix ) {
		if ( ! in_array( $hook_suffix, [ 'post.php', 'woocommerce_page_wc-orders' ], true ) ) {
			return;
		}
		
		global $post;
		$order_id = null;
		
		if ( $post && $post->post_type === 'shop_order' ) {
			$order_id = $post->ID;
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		} elseif ( isset( $_GET['id'] ) ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$order_id = absint( $_GET['id'] );
		}
		
		if ( ! $order_id ) {
			return;
		}
		
		wp_enqueue_script( 'jquery' );
		
		$metabox_js = "
			jQuery(document).ready(function($) {
				$('#devikit-ifirma-create-invoice').on('click', function() {
					var \$btn = $(this);
					var \$loading = $('#devikit-ifirma-loading');
					var \$error = $('#devikit-ifirma-error');
					
					\$btn.hide();
					\$loading.show();
					\$error.text('');

					$.post(ajaxurl, {
						action: 'devikit_ifirma_create_invoice',
						order_id: \$btn.data('order-id'),
						nonce: '" . esc_js( wp_create_nonce( 'ifirma_create_invoice' ) ) . "'
					}, function(response) {
						\$loading.hide();
						if (response.success) {
							location.reload();
						} else {
							\$btn.show();
							\$error.text(response.data.message);
						}
					});
				});
				
				$('#devikit-ifirma-download-pdf').on('click', function() {
					var \$btn = $(this);
					var invoiceId = \$btn.data('invoice-id');
					var invoiceNumber = \$btn.data('invoice-number');
					var documentType = \$btn.data('document-type') || 'invoice';
					var originalText = \$btn.text();
					
					\$btn.prop('disabled', true).text('" . esc_js( __( 'Downloading...', 'invoicing-integration-for-ifirma-and-woocommerce' ) ) . "');
					
					$.post(ajaxurl, {
						action: 'devikit_ifirma_download_pdf',
						invoice_id: invoiceId,
						invoice_number: invoiceNumber,
						document_type: documentType,
						nonce: '" . esc_js( wp_create_nonce( 'ifirma_download_pdf' ) ) . "'
					}, function(response) {
						\$btn.prop('disabled', false).text(originalText);
						
						if (response.success && response.data.pdf) {
							var binary = atob(response.data.pdf);
							var array = new Uint8Array(binary.length);
							for (var i = 0; i < binary.length; i++) {
								array[i] = binary.charCodeAt(i);
							}
							var blob = new Blob([array], {type: 'application/pdf'});
							var url = window.URL.createObjectURL(blob);
							var a = document.createElement('a');
							a.href = url;
							a.download = response.data.filename;
							document.body.appendChild(a);
							a.click();
							window.URL.revokeObjectURL(url);
							document.body.removeChild(a);
						} else {
							alert(response.data.message || '" . esc_js( __( 'Failed to download PDF', 'invoicing-integration-for-ifirma-and-woocommerce' ) ) . "');
						}
					});
				});
				
				$('#devikit-ifirma-send-email').off('click').on('click', function(e) {
					e.preventDefault();
					
					var \$btn = $(this);
					var \$loading = $('#devikit-ifirma-email-loading');
					var \$success = $('#devikit-ifirma-email-success');
					var \$error = $('#devikit-ifirma-email-error');
					
					if (!confirm('" . esc_js( __( 'Are you sure you want to send the invoice to the customer?', 'invoicing-integration-for-ifirma-and-woocommerce' ) ) . "')) {
						return false;
					}
					
					\$btn.prop('disabled', true).hide();
					\$loading.show();
					\$success.hide();
					\$error.text('');

					$.post(ajaxurl, {
						action: 'devikit_ifirma_send_invoice_email',
						order_id: \$btn.data('order-id'),
						nonce: '" . esc_js( wp_create_nonce( 'ifirma_send_email' ) ) . "'
					}, function(response) {
						\$loading.hide();
						if (response.success) {
							\$success.show();
							setTimeout(function() {
								\$btn.prop('disabled', false).show();
								\$success.hide();
							}, 3000);
						} else {
							\$btn.prop('disabled', false).show();
							\$error.text(response.data && response.data.message ? response.data.message : '" . esc_js( __( 'Unknown error', 'invoicing-integration-for-ifirma-and-woocommerce' ) ) . "');
						}
					}).fail(function(xhr, status, error) {
						\$loading.hide();
						\$btn.prop('disabled', false).show();
						\$error.text('AJAX Error: ' + error);
					});
					
					return false;
				});
				
				// Proforma button handler
				$('#devikit-ifirma-create-proforma').on('click', function() {
					var \$btn = $(this);
					var \$loading = $('#devikit-ifirma-proforma-loading');
					var \$error = $('#devikit-ifirma-proforma-error');
					
					\$btn.hide();
					\$loading.show();
					\$error.text('');

					$.post(ajaxurl, {
						action: 'devikit_ifirma_create_proforma',
						order_id: \$btn.data('order-id'),
						nonce: '" . esc_js( wp_create_nonce( 'ifirma_create_proforma' ) ) . "'
					}, function(response) {
						\$loading.hide();
						if (response.success) {
							location.reload();
						} else {
							\$btn.show();
							\$error.text(response.data.message);
						}
					});
				});
			});
		";
		
		wp_add_inline_script( 'jquery', $metabox_js );
	}

	/**
	 * Render Meta Box
	 */
	public function render_meta_box( $post_or_order_object ) {
		$order = ( $post_or_order_object instanceof \WC_Order ) ? $post_or_order_object : wc_get_order( $post_or_order_object->ID );
		if ( ! $order ) {
			return;
		}

		$invoice_id = $order->get_meta( '_ifirma_invoice_id' );
		$invoice_number = $order->get_meta( '_ifirma_invoice_number' );
		
		$proforma_id = $order->get_meta( '_ifirma_proforma_id' );
		$proforma_number = $order->get_meta( '_ifirma_proforma_number' );

		// FREE only checks if PRO is installed. PRO renders its sections and checks license internally.
		$pro_installed = class_exists( 'Devikit\IfirmaPro\Plugin' );

		?>
		<div class="devikit-ifirma-metabox">
			<?php 
			// Proforma display
			if ( $proforma_id ) :
				if ( $pro_installed ) :
					do_action( 'devikit_ifirma_metabox_proforma_display', $order, $proforma_id, $proforma_number );
				else :
					?>
					<p>
						<strong><?php echo esc_html__( 'Proforma Created:', 'invoicing-integration-for-ifirma-and-woocommerce' ); ?></strong><br>
						<?php echo esc_html( $proforma_number ?: $proforma_id ); ?>
					</p>
					<p>
						<button type="button" class="button" id="devikit-ifirma-download-proforma-pdf" 
								data-invoice-id="<?php echo esc_attr( $proforma_id ); ?>"
								data-invoice-number="<?php echo esc_attr( $proforma_number ); ?>">
							<?php echo esc_html__( 'Download PDF', 'invoicing-integration-for-ifirma-and-woocommerce' ); ?>
						</button>
					</p>
					<p style="margin-top:10px;">
						<button type="button" class="button" disabled style="opacity:0.5; cursor:not-allowed;">
							<?php echo esc_html__( 'Send Proforma by Email', 'invoicing-integration-for-ifirma-and-woocommerce' ); ?> 🔒
						</button>
						<br>
						<small style="color:#666; margin-top:5px; display:block;">
							<?php
							printf(
								/* translators: %s: Link to PRO version */
								esc_html__( 'Available in %s', 'invoicing-integration-for-ifirma-and-woocommerce' ),
								'<a href="https://devikit.pl/produkt/ifirma-woocommerce-pro/" target="_blank" style="color:#006b9f;">' . esc_html__( 'PRO version', 'invoicing-integration-for-ifirma-and-woocommerce' ) . '</a>'
							);
							?>
						</small>
					</p>
					<hr style="margin:15px 0;">
					<?php
				endif;
			endif;
			?>
			
			<?php if ( $invoice_id ) : ?>
				<p>
					<strong><?php echo esc_html__( 'Invoice Created:', 'invoicing-integration-for-ifirma-and-woocommerce' ); ?></strong><br>
					<?php echo esc_html( $invoice_number ?: $invoice_id ); ?>
				</p>
				
				<?php
				// Check for total mismatch - can be 'minor' (1-2 grosze) or 'major' (> 2 grosze)
				$mismatch_type = $order->get_meta( '_ifirma_invoice_total_mismatch' );
				// Handle legacy 'yes' value as 'minor'
				if ( $mismatch_type === 'yes' ) {
					$mismatch_type = 'minor';
				}
				
				if ( $mismatch_type === 'minor' || $mismatch_type === 'major' ) {
					$order_total = floatval( $order->get_meta( '_ifirma_invoice_order_total' ) );
					$invoice_total = floatval( $order->get_meta( '_ifirma_invoice_ifirma_total' ) );
					$difference = floatval( $order->get_meta( '_ifirma_invoice_total_difference' ) );
					
					if ( $mismatch_type === 'major' ) {
						// Major mismatch - red warning, email was blocked
					?>
						<div style="background: #f8d7da; border-left: 4px solid #dc3545; padding: 10px; margin: 10px 0;">
							<p style="margin: 0; color: #721c24; font-weight: bold;">
								⚠️ <?php 
								printf(
									/* translators: 1: Invoice total, 2: Order total */
									esc_html__( 'SIGNIFICANT DIFFERENCE: Invoice total (%1$s) differs from order total (%2$s). Email was NOT sent automatically.', 'invoicing-integration-for-ifirma-and-woocommerce' ),
									number_format( $invoice_total, 2, ',', ' ' ),
									number_format( $order_total, 2, ',', ' ' )
								);
								?>
						</p>
						</div>
						<?php
					} else {
						// Minor mismatch - yellow info, email was sent
						?>
						<div style="background: #fff3cd; border-left: 4px solid #ffc107; padding: 10px; margin: 10px 0;">
							<p style="margin: 0; color: #856404;">
							<?php 
							printf(
									/* translators: 1: Invoice total, 2: Order total */
									esc_html__( 'Note: Invoice total (%1$s) slightly differs from order total (%2$s). This is typically caused by VAT rounding differences between systems.', 'invoicing-integration-for-ifirma-and-woocommerce' ),
								number_format( $invoice_total, 2, ',', ' ' ),
									number_format( $order_total, 2, ',', ' ' )
							);
							?>
						</p>
					</div>
					<?php
				}
				}
				?>
				
				<?php 
				// Get invoice type (domestic, wdt, foreign, oss) - defaults to 'invoice' for backward compatibility
				$invoice_type_meta = $order->get_meta( '_ifirma_invoice_type' );
				$document_type_for_download = 'invoice';
				if ( $invoice_type_meta === 'wdt' ) {
					$document_type_for_download = 'wdt';
				} elseif ( $invoice_type_meta === 'foreign' ) {
					$document_type_for_download = 'foreign';
				} elseif ( $invoice_type_meta === 'oss' ) {
					$document_type_for_download = 'oss';
				}
				?>
				<p>
					<button type="button" class="button" id="devikit-ifirma-download-pdf" 
							data-invoice-id="<?php echo esc_attr( $invoice_id ); ?>"
							data-invoice-number="<?php echo esc_attr( $invoice_number ); ?>"
							data-document-type="<?php echo esc_attr( $document_type_for_download ); ?>">
						<?php echo esc_html__( 'Download PDF', 'invoicing-integration-for-ifirma-and-woocommerce' ); ?>
					</button>
				</p>
				<p style="margin-top:10px;">
					<?php if ( $pro_installed ) : ?>
						<?php do_action( 'devikit_ifirma_render_send_email', $order ); ?>
					<?php else : ?>
						<button type="button" class="button" disabled style="opacity:0.5; cursor:not-allowed;">
							<?php echo esc_html__( 'Send Invoice by Email', 'invoicing-integration-for-ifirma-and-woocommerce' ); ?> 🔒
						</button>
						<br>
						<small style="color:#666; margin-top:5px; display:block;">
							<?php 
							printf(
								/* translators: %s: Link to PRO version */
								esc_html__( 'Available in %s', 'invoicing-integration-for-ifirma-and-woocommerce' ),
								'<a href="https://devikit.pl/produkt/ifirma-woocommerce-pro/" target="_blank" style="color:#006b9f;">' . esc_html__( 'PRO version', 'invoicing-integration-for-ifirma-and-woocommerce' ) . '</a>'
							);
							?>
						</small>
					<?php endif; ?>
				</p>
			<?php endif; ?>
			
			<?php if ( ! $invoice_id || ! $proforma_id ) : ?>
				<?php if ( ! $invoice_id && ! $proforma_id ) : ?>
					<p><?php echo esc_html__( 'No documents created yet.', 'invoicing-integration-for-ifirma-and-woocommerce' ); ?></p>
				<?php elseif ( $proforma_id && ! $invoice_id ) : ?>
					<hr style="margin:15px 0;">
				<?php endif; ?>
				
				<p style="margin-top:10px;">
					<?php if ( ! $invoice_id ) : ?>
						<button type="button" class="button button-primary" id="devikit-ifirma-create-invoice" data-order-id="<?php echo esc_attr( $order->get_id() ); ?>">
							<?php echo esc_html__( 'Create Invoice', 'invoicing-integration-for-ifirma-and-woocommerce' ); ?>
						</button>
					<?php endif; ?>
				</p>
					
				<?php if ( ! $proforma_id ) : ?>
					<p style="margin-top:10px;">
						<?php if ( $pro_installed ) : ?>
							<?php do_action( 'devikit_ifirma_render_create_proforma', $order ); ?>
						<?php else : ?>
							<button type="button" class="button" disabled style="opacity:0.5; cursor:not-allowed;">
								<?php echo esc_html__( 'Create Proforma', 'invoicing-integration-for-ifirma-and-woocommerce' ); ?> 🔒
							</button>
							<br>
							<small style="color:#666; margin-top:5px; display:block;">
								<?php 
								printf(
									/* translators: %s: Link to PRO version */
									esc_html__( 'Proformas available in %s', 'invoicing-integration-for-ifirma-and-woocommerce' ),
									'<a href="https://devikit.pl/produkt/ifirma-woocommerce-pro/" target="_blank" style="color:#006b9f;">' . esc_html__( 'PRO version', 'invoicing-integration-for-ifirma-and-woocommerce' ) . '</a>'
								);
								?>
							</small>
						<?php endif; ?>
					</p>
				<?php endif; ?>
				<span id="devikit-ifirma-loading" style="display:none;"><?php echo esc_html__( 'Creating invoice...', 'invoicing-integration-for-ifirma-and-woocommerce' ); ?></span>
				<p id="devikit-ifirma-error" style="color:red; margin-top:10px;"></p>
			<?php endif; ?>
		</div>

		<?php
		// Hook for PRO features (PRO renders rachunek etc.; when license invalid, PRO shows disabled)
		if ( $pro_installed ) {
			do_action( 'devikit_ifirma_metabox_after_invoice', $order );
		} else {
			// Show disabled rachunek section in FREE
			?>
			<div class="ifirma-rachunek-section" style="margin-top: 15px; padding-top: 15px; border-top: 1px solid #ddd;">
				<h4 style="margin: 0 0 10px 0;"><?php echo esc_html__( 'Rachunek', 'invoicing-integration-for-ifirma-and-woocommerce' ); ?></h4>
				<p>
					<button type="button" class="button" disabled style="opacity:0.5; cursor:not-allowed;">
						<?php echo esc_html__( 'Create Rachunek', 'invoicing-integration-for-ifirma-and-woocommerce' ); ?> 🔒
					</button>
					<br>
					<small style="color:#666; margin-top:5px; display:block;">
						<?php 
						printf(
							/* translators: %s: link to PRO version */
							esc_html__( 'Rachunki available in %s', 'invoicing-integration-for-ifirma-and-woocommerce' ),
							'<a href="https://devikit.pl/produkt/ifirma-woocommerce-pro/" target="_blank" style="color:#006b9f;">' . esc_html__( 'PRO version', 'invoicing-integration-for-ifirma-and-woocommerce' ) . '</a>'
						);
						?>
					</small>
				</p>
			</div>
			<?php
		}
	}

	/**
	 * AJAX Create Invoice
	 */
	public function ajax_create_invoice() {
		check_ajax_referer( 'ifirma_create_invoice', 'nonce' );
		
		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_send_json_error( [ 'message' => __( 'Unauthorized', 'invoicing-integration-for-ifirma-and-woocommerce' ) ] );
		}

		$order_id = isset( $_POST['order_id'] ) ? absint( $_POST['order_id'] ) : 0;
		$order = wc_get_order( $order_id );

		if ( ! $order ) {
			wp_send_json_error( [ 'message' => __( 'Order not found', 'invoicing-integration-for-ifirma-and-woocommerce' ) ] );
		}

		$result = $this->create_invoice_for_order( $order );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( [ 'message' => $result->get_error_message() ] );
		}

		wp_send_json_success();
	}
	
	/**
	 * AJAX Download PDF
	 */
	public function ajax_download_pdf() {
		check_ajax_referer( 'ifirma_download_pdf', 'nonce' );
		
		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_send_json_error( [ 'message' => __( 'Unauthorized', 'invoicing-integration-for-ifirma-and-woocommerce' ) ] );
		}

		$invoice_id = isset( $_POST['invoice_id'] ) ? absint( $_POST['invoice_id'] ) : 0;
		$invoice_number = isset( $_POST['invoice_number'] ) ? sanitize_text_field( wp_unslash( $_POST['invoice_number'] ) ) : 'invoice';
		$document_type = isset( $_POST['document_type'] ) ? sanitize_text_field( wp_unslash( $_POST['document_type'] ) ) : 'invoice';

		if ( ! $invoice_id ) {
			wp_send_json_error( [ 'message' => __( 'Invoice ID missing', 'invoicing-integration-for-ifirma-and-woocommerce' ) ] );
		}

		$pdf_content = $this->api_client->download_pdf( $invoice_id, $document_type );

		if ( is_wp_error( $pdf_content ) ) {
			$this->api_client->log( 'PDF Download Error: ' . $pdf_content->get_error_message(), 'error' );
			wp_send_json_error( [ 'message' => $pdf_content->get_error_message() ] );
		}

		if ( empty( $pdf_content ) ) {
			wp_send_json_error( [ 'message' => __( 'PDF content is empty', 'invoicing-integration-for-ifirma-and-woocommerce' ) ] );
		}

		wp_send_json_success( [ 
			'pdf' => base64_encode( $pdf_content ),
			'filename' => sanitize_file_name( $invoice_number ) . '.pdf'
		] );
	}
	
	/**
	 * AJAX Send Invoice Email
	 */
	public function ajax_send_invoice_email() {
		check_ajax_referer( 'ifirma_send_email', 'nonce' );
		
		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_send_json_error( [ 'message' => __( 'Unauthorized', 'invoicing-integration-for-ifirma-and-woocommerce' ) ] );
		}
		
		if ( ! class_exists( 'Devikit\IfirmaPro\Plugin' ) ) {
			wp_send_json_error( [ 'message' => __( 'PRO version required', 'invoicing-integration-for-ifirma-and-woocommerce' ) ] );
		}
		
		WC()->mailer();

		$order_id = isset( $_POST['order_id'] ) ? absint( $_POST['order_id'] ) : 0;
		$order = wc_get_order( $order_id );

		if ( ! $order ) {
			wp_send_json_error( [ 'message' => __( 'Order not found', 'invoicing-integration-for-ifirma-and-woocommerce' ) ] );
		}
		
		$invoice_id = $order->get_meta( '_ifirma_invoice_id' );
		$invoice_number = $order->get_meta( '_ifirma_invoice_number' );
		
		if ( ! $invoice_id ) {
			wp_send_json_error( [ 'message' => __( 'Invoice not found', 'invoicing-integration-for-ifirma-and-woocommerce' ) ] );
		}
		
		$invoice_data = [
			'number' => $invoice_number,
			'id' => $invoice_id
		];
		
		do_action( 'devikit_ifirma_invoice_generated', $order_id, $invoice_data );
		
		$order->add_order_note( __( 'Invoice email sent to customer', 'invoicing-integration-for-ifirma-and-woocommerce' ) );

		wp_send_json_success( [ 'message' => __( 'Email sent successfully', 'invoicing-integration-for-ifirma-and-woocommerce' ) ] );
	}

	/**
	 * Create Invoice for Order
	 * 
	 * @param \WC_Order $order
	 * @param bool $is_automatic Whether invoice is created automatically
	 * @return int|\WP_Error Invoice ID or error
	 */
	public function create_invoice_for_order( $order, $is_automatic = false ) {
		if ( ! $order instanceof \WC_Order ) {
			return new \WP_Error( 'ifirma_invalid_order', __( 'Invalid order.', 'invoicing-integration-for-ifirma-and-woocommerce' ) );
		}

		$existing_id = absint( $order->get_meta( '_ifirma_invoice_id' ) );
		if ( $existing_id ) {
			$existing_number = $order->get_meta( '_ifirma_invoice_number' );
			return new \WP_Error(
				'ifirma_invoice_exists',
				sprintf(
					/* translators: %s: Invoice number or iFirma ID */
					__( 'An invoice is already linked to this order (%1$s).', 'invoicing-integration-for-ifirma-and-woocommerce' ),
					$existing_number ? $existing_number : (string) $existing_id
				)
			);
		}

		$order_id = $order->get_id();
		$lock_key = 'devikit_ifirma_invoice_lock_' . $order_id;

		if ( ! add_option( $lock_key, '1', '', 'no' ) ) {
			return new \WP_Error(
				'ifirma_invoice_in_progress',
				__( 'Invoice creation is already in progress for this order. Please wait and refresh the page.', 'invoicing-integration-for-ifirma-and-woocommerce' )
			);
		}

		try {
			$order = wc_get_order( $order_id );
			if ( ! $order ) {
				return new \WP_Error( 'ifirma_order_not_found', __( 'Order not found.', 'invoicing-integration-for-ifirma-and-woocommerce' ) );
			}

			if ( absint( $order->get_meta( '_ifirma_invoice_id' ) ) ) {
				$existing_number = $order->get_meta( '_ifirma_invoice_number' );
				$existing_id     = absint( $order->get_meta( '_ifirma_invoice_id' ) );
				return new \WP_Error(
					'ifirma_invoice_exists',
					sprintf(
						/* translators: %s: Invoice number or iFirma ID */
						__( 'An invoice is already linked to this order (%1$s).', 'invoicing-integration-for-ifirma-and-woocommerce' ),
						$existing_number ? $existing_number : (string) $existing_id
					)
				);
			}

			return $this->process_create_invoice_for_order( $order, $is_automatic );
		} finally {
			delete_option( $lock_key );
		}
	}

	/**
	 * Internal invoice creation (caller must hold devikit_ifirma_invoice_lock_{order_id}).
	 *
	 * @param \WC_Order $order
	 * @param bool      $is_automatic
	 * @return int|\WP_Error
	 */
	private function process_create_invoice_for_order( $order, $is_automatic = false ) {
		$invoice_data = $this->prepare_invoice_data( $order );
		$invoice_data = apply_filters( 'devikit_ifirma_invoice_data', $invoice_data, $order );
		
		// Detect invoice type based on customer country
		$invoice_type = $this->api_client->detect_invoice_type( $invoice_data );
		$invoice_data['invoice_type'] = $invoice_type;

		// Sync contractor by NIP/VAT (avoid duplicates in iFirma)
		$contractor_identifier = $this->api_client->ensure_contractor( $invoice_data['customer'] );
		if ( is_wp_error( $contractor_identifier ) ) {
			$order->add_order_note( __( 'iFirma Contractor Sync Error: ', 'invoicing-integration-for-ifirma-and-woocommerce' ) . $contractor_identifier->get_error_message() );
			return $contractor_identifier;
		}
		if ( ! empty( $contractor_identifier ) ) {
			$invoice_data['contractor_identifier'] = $contractor_identifier;
		}
		
		$this->api_client->log( 'Invoice data prepared (type: ' . $invoice_type . '): ' . wp_json_encode( $invoice_data, JSON_UNESCAPED_UNICODE ), 'debug' );

		// Use appropriate API based on invoice type
		if ( $invoice_type === 'wdt' ) {
			$response = $this->api_client->create_wdt_invoice( $invoice_data );
		} elseif ( $invoice_type === 'foreign' ) {
			$response = $this->api_client->create_foreign_invoice( $invoice_data );
		} elseif ( $invoice_type === 'oss' ) {
			$response = $this->api_client->create_oss_invoice( $invoice_data );
		} else {
			// Domestic invoice
		$response = $this->api_client->create_invoice( $invoice_data );
		}

		if ( is_wp_error( $response ) ) {
			$order->add_order_note( __( 'iFirma Invoice Error: ', 'invoicing-integration-for-ifirma-and-woocommerce' ) . $response->get_error_message() );
			return $response;
		}

		$this->api_client->log( 'Invoice API response: ' . wp_json_encode( $response, JSON_UNESCAPED_UNICODE ), 'debug' );

		// Parse response - iFirma returns Identyfikator
		$invoice_id = null;
		$invoice_number = null;
		$details = null;
		
		if ( isset( $response['response'] ) && isset( $response['response']['Kod'] ) && $response['response']['Kod'] === 0 ) {
			$invoice_id = $response['response']['Identyfikator'] ?? null;
			
			// Fetch invoice details to get the full number
			if ( $invoice_id ) {
				if ( $invoice_type === 'wdt' ) {
					$details = $this->api_client->get_invoice_details( $invoice_id, 'wdt' );
				} elseif ( $invoice_type === 'foreign' ) {
					$details = $this->api_client->get_invoice_details( $invoice_id, 'foreign' );
				} elseif ( $invoice_type === 'oss' ) {
					$details = $this->api_client->get_invoice_details( $invoice_id, 'oss' );
				} else {
					$details = $this->api_client->get_invoice_details( $invoice_id, 'invoice' );
				}
				
				if ( ! is_wp_error( $details ) && isset( $details['response']['PelnyNumer'] ) ) {
					$invoice_number = $details['response']['PelnyNumer'];
				} elseif ( ! is_wp_error( $details ) && isset( $details['response']['Numer'] ) ) {
					$invoice_number = $details['response']['Numer'];
				}
			}
		}

		if ( $invoice_id ) {
			// Get invoice total for validation from details response
			$invoice_total = 0;
			if ( isset( $details['response']['WartoscBrutto'] ) ) {
				$invoice_total = floatval( $details['response']['WartoscBrutto'] );
			}
			
			$order_total = floatval( $order->get_total() );
			$total_difference = abs( $invoice_total - $order_total );
			
			// Determine mismatch severity:
			// - minor: 0.01-0.02 PLN (rounding differences) - warning only, email sent
			// - major: > 0.02 PLN (significant difference) - block email, highlight red
			$mismatch_type = 'none';
			if ( $total_difference >= 0.001 && $invoice_total > 0 ) {
				$mismatch_type = $total_difference <= 0.02 ? 'minor' : 'major';
			}
			
			$order->update_meta_data( '_ifirma_invoice_id', $invoice_id );
			$order->update_meta_data( '_ifirma_invoice_number', $invoice_number );
			$order->update_meta_data( '_ifirma_invoice_type', $invoice_type ); // domestic, wdt, foreign, oss
			
			if ( $mismatch_type !== 'none' ) {
				$order->update_meta_data( '_ifirma_invoice_total_mismatch', $mismatch_type ); // 'minor' or 'major'
				$order->update_meta_data( '_ifirma_invoice_order_total', $order_total );
				$order->update_meta_data( '_ifirma_invoice_ifirma_total', $invoice_total );
				$order->update_meta_data( '_ifirma_invoice_total_difference', $total_difference );
			} else {
				$order->delete_meta_data( '_ifirma_invoice_total_mismatch' );
			}

			$save_error = $this->persist_invoice_order_link( $order, $invoice_id );
			if ( is_wp_error( $save_error ) ) {
				return $this->handle_invoice_link_save_failure( $order, $invoice_id, $invoice_number, $save_error );
			}

			if ( $mismatch_type === 'major' ) {
				$order->add_order_note( sprintf(
					/* translators: 1: Invoice number/ID, 2: Order total, 3: Invoice total */
					__( 'iFirma Invoice created: %1$s (SIGNIFICANT TOTAL MISMATCH: Order %2$s vs Invoice %3$s - email blocked)', 'invoicing-integration-for-ifirma-and-woocommerce' ),
					$invoice_number ?: $invoice_id,
					number_format( $order_total, 2, ',', ' ' ),
					number_format( $invoice_total, 2, ',', ' ' )
				) );
			} elseif ( $mismatch_type === 'minor' ) {
				$order->add_order_note( sprintf(
					/* translators: 1: Invoice number/ID, 2: Order total, 3: Invoice total */
					__( 'iFirma Invoice created: %1$s (Minor rounding difference: Order %2$s vs Invoice %3$s)', 'invoicing-integration-for-ifirma-and-woocommerce' ),
					$invoice_number ?: $invoice_id,
					number_format( $order_total, 2, ',', ' ' ),
					number_format( $invoice_total, 2, ',', ' ' )
				) );
			} else {
				$order->add_order_note( sprintf(
					/* translators: %s: Invoice number/ID */
					__( 'iFirma Invoice created: %s', 'invoicing-integration-for-ifirma-and-woocommerce' ),
					$invoice_number ?: $invoice_id
				) );
			}

			$order->save();

			// Send email only if there's no major mismatch
			// Minor mismatch (1-2 grosze) = email sent (rounding differences)
			// Major mismatch (> 2 grosze) = email blocked
			if ( $mismatch_type !== 'major' ) {
				$this->maybe_send_invoice_email( $order, [
					'id' => $invoice_id,
					'number' => $invoice_number,
				], $is_automatic );
			}

			return $invoice_id;
		}

		return new \WP_Error( 'ifirma_unknown_error', __( 'Unknown response from iFirma API', 'invoicing-integration-for-ifirma-and-woocommerce' ) );
	}

	/**
	 * Save invoice meta on the order and verify it persisted.
	 *
	 * @param \WC_Order $order
	 * @param int|string $invoice_id
	 * @return true|\WP_Error
	 */
	private function persist_invoice_order_link( $order, $invoice_id ) {
		$save_result = $order->save();

		if ( is_wp_error( $save_result ) ) {
			return $save_result;
		}

		if ( ! $save_result ) {
			return new \WP_Error(
				'ifirma_order_save_failed',
				__( 'Could not save invoice link to the order.', 'invoicing-integration-for-ifirma-and-woocommerce' )
			);
		}

		$reloaded = wc_get_order( $order->get_id() );
		if ( ! $reloaded || absint( $reloaded->get_meta( '_ifirma_invoice_id' ) ) !== absint( $invoice_id ) ) {
			return new \WP_Error(
				'ifirma_order_meta_missing',
				__( 'Invoice link was not stored on the order.', 'invoicing-integration-for-ifirma-and-woocommerce' )
			);
		}

		return true;
	}

	/**
	 * Handle failure to link a successfully created iFirma invoice to the WooCommerce order.
	 *
	 * @param \WC_Order       $order
	 * @param int|string      $invoice_id
	 * @param string|null     $invoice_number
	 * @param \WP_Error       $save_error
	 * @return \WP_Error
	 */
	private function handle_invoice_link_save_failure( $order, $invoice_id, $invoice_number, $save_error ) {
		$display_ref = $invoice_number ? $invoice_number : (string) $invoice_id;

		$this->api_client->log(
			'Invoice created in iFirma (ID: ' . $invoice_id . ', number: ' . ( $invoice_number ?: 'n/a' ) . ') but order link save failed for order #' . $order->get_id() . ': ' . $save_error->get_error_message(),
			'error'
		);

		$order->add_order_note( sprintf(
			/* translators: 1: iFirma invoice ID, 2: invoice number or em dash */
			__( 'iFirma: invoice created in iFirma (ID: %1$s, number: %2$s) but failed to save the order link. Do not issue again.', 'invoicing-integration-for-ifirma-and-woocommerce' ),
			$invoice_id,
			$invoice_number ? $invoice_number : '—'
		) );
		$order->save();

		return new \WP_Error(
			'ifirma_order_link_failed',
			sprintf(
				/* translators: %s: Invoice number or iFirma ID */
				__( 'Invoice was created in iFirma (%1$s) but could not be linked to this order. Do not create another invoice — check iFirma or contact support.', 'invoicing-integration-for-ifirma-and-woocommerce' ),
				$display_ref
			),
			[ 'ifirma_invoice_id' => $invoice_id ]
		);
	}
	
	/**
	 * Maybe send invoice email with optional 5-minute delay for automatic creation.
	 *
	 * For automatic invoice creation the email is delayed by 5 minutes
	 * to allow KSeF (Krajowy System e-Faktur) to process the invoice.
	 * Manual creation / manual send button sends the email immediately.
	 *
	 * @param \WC_Order $order
	 * @param array     $invoice       Array with id, number keys.
	 * @param bool      $is_automatic  Whether the invoice was created automatically.
	 */
	private function maybe_send_invoice_email( $order, $invoice, $is_automatic = false ) {
		if ( ! class_exists( 'Devikit\IfirmaPro\Plugin' ) ) {
			return;
		}
		
		$pro_settings = get_option( 'devikit_ifirma_pro_settings', [] );
		
		if ( empty( $pro_settings['send_invoice_email'] ) || $pro_settings['send_invoice_email'] !== 'yes' ) {
			return;
		}
		
		$invoice_data = [
			'number' => $invoice['number'] ?? '',
			'id'     => $invoice['id'],
		];
		
		if ( $is_automatic && function_exists( 'as_schedule_single_action' ) ) {
			$delay_minutes = apply_filters( 'devikit_ifirma_invoice_email_delay_minutes', 5 );
			
			as_schedule_single_action(
				time() + ( $delay_minutes * 60 ),
				'devikit_ifirma_send_delayed_invoice_email',
				[
					'order_id'     => $order->get_id(),
					'invoice_data' => $invoice_data,
				],
				'devikit-ifirma'
			);
			
			$order->add_order_note( sprintf(
				/* translators: %d: delay in minutes */
				__( 'Invoice email scheduled — will be sent in %d minutes (waiting for KSeF processing)', 'invoicing-integration-for-ifirma-and-woocommerce' ),
				$delay_minutes
			) );
		} else {
			WC()->mailer();
			do_action( 'devikit_ifirma_invoice_generated', $order->get_id(), $invoice_data );
			$order->add_order_note( __( 'Invoice email sent to customer', 'invoicing-integration-for-ifirma-and-woocommerce' ) );
		}
	}
	
	/**
	 * Handle delayed invoice email (called by Action Scheduler after 5 min).
	 *
	 * @param int   $order_id
	 * @param array $invoice_data
	 */
	public function handle_delayed_invoice_email( $order_id, $invoice_data ) {
		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			return;
		}
		
		WC()->mailer();
		do_action( 'devikit_ifirma_invoice_generated', $order_id, $invoice_data );
		$order->add_order_note( __( 'Invoice email sent to customer (delayed — after KSeF processing)', 'invoicing-integration-for-ifirma-and-woocommerce' ) );
	}

	/**
	 * Prepare Invoice Data
	 * 
	 * @param \WC_Order $order
	 * @param string $type Document type
	 * @return array
	 */
	public function prepare_invoice_data( $order, $type = 'invoice' ) {
		$settings = get_option( 'devikit_ifirma_settings', [] );
		$lump_sum_enable = isset( $settings['lump_sum_enable'] ) && $settings['lump_sum_enable'] === 'yes';
		$lump_sum_default_value = isset( $settings['lump_sum_default_value'] ) ? (string) $settings['lump_sum_default_value'] : 'empty';
		
		$invoice_date = current_time( 'Y-m-d' );
		$sale_date    = $order->get_date_created() ? $order->get_date_created()->date( 'Y-m-d' ) : $invoice_date;

		// DataWystawienia always stays as today. DataSprzedazy keeps the order date.
		// iFirma: accounting month must match the sale date; issue date may differ.
		// Numbering chronology is preserved relative to the issue date.
		
		$payment_days = isset( $settings['payment_deadline_days'] ) ? intval( $settings['payment_deadline_days'] ) : 14;
		$payment_date = gmdate( 'Y-m-d', strtotime( $invoice_date . ' + ' . $payment_days . ' days' ) );
		
		$currency = $order->get_currency();
		if ( empty( $currency ) ) {
			// Fallback to store base currency if order currency is missing.
			$currency = get_option( 'woocommerce_currency', 'PLN' );
		}
		if ( empty( $currency ) ) {
			$currency = 'PLN';
		}
		
		// Get NIP / EU VAT / foreign Tax ID (czytane z wielu pól - patrz self::get_order_tax_id()).
		$nip = self::get_order_tax_id( $order );

		// Build customer data
		$is_company = ! empty( $order->get_billing_company() );
		$billing_country_code = $order->get_billing_country();
		$billing_address_1 = (string) $order->get_billing_address_1();
		$billing_address_2 = (string) $order->get_billing_address_2();
		$billing_street = trim( $billing_address_1 . ( $billing_address_2 !== '' ? ' ' . $billing_address_2 : '' ) );
		$customer = [
			'name'         => $is_company ? $order->get_billing_company() : trim( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() ),
			'is_company'   => $is_company,
			'street'       => $billing_street,
			'postcode'     => $order->get_billing_postcode(),
			'city'         => $order->get_billing_city(),
			'country'      => $this->get_country_name( $billing_country_code ),
			'country_code' => $billing_country_code,
			'email'        => $order->get_billing_email(),
			'phone'        => $order->get_billing_phone(),
			'nip'          => $nip,
		];
		
		// Determine payment method
		$wc_payment_method = $order->get_payment_method();
		
		// Determine if paid
		$is_paid = 0;
		if ( $wc_payment_method !== 'cod' ) {
			$order_status = $order->get_status();
			if ( $order_status === 'completed' || $order->is_paid() ) {
				$is_paid = floatval( $order->get_total() );
			}
		}
		
		// Build items - PRO settings (GTU/PKWiU defaults) when PRO features enabled (PRO gates via filter)
		$pro_features_enabled = (bool) apply_filters( 'devikit_ifirma_pro_features_enabled', false );
		$pro_settings = $pro_features_enabled ? get_option( 'devikit_ifirma_pro_settings', [] ) : [];
		$default_gtu = ( is_array( $pro_settings ) && ! empty( $pro_settings['default_gtu'] ) ) ? sanitize_text_field( (string) $pro_settings['default_gtu'] ) : '';
		$default_pkwiu = ( is_array( $pro_settings ) && ! empty( $pro_settings['default_pkwiu'] ) ) ? sanitize_text_field( (string) $pro_settings['default_pkwiu'] ) : '';
		$default_unit = ( is_array( $pro_settings ) && ! empty( $pro_settings['default_unit'] ) ) ? sanitize_text_field( (string) $pro_settings['default_unit'] ) : 'szt.';

		$items = [];
		$lump_sum_rates_for_shipping = [];
		foreach ( $order->get_items() as $item ) {
			$product = $item->get_product();
			$variation_id = method_exists( $item, 'get_variation_id' ) ? absint( $item->get_variation_id() ) : 0;
			
			$vat_symbol = $this->get_item_vat_symbol( $item, $product, $settings );
			
			$item_total_net = round( floatval( $item->get_total() ), 2 );
			$item_total_tax = floatval( $item->get_total_tax() );
			$item_total_gross = round( floatval( $item_total_net + $item_total_tax ), 2 );
			$unit_price_net = round( $item_total_net / floatval( $item->get_quantity() ), 2 );
			$unit_price_gross = round( $item_total_gross / floatval( $item->get_quantity() ), 2 );
			
			// Calculate actual VAT rate from order (for OSS invoices)
			$vat_rate_decimal = null;
			if ( $item_total_net > 0 && $item_total_tax > 0 ) {
				// Get actual VAT rate from taxes applied to this item
				$taxes = $item->get_taxes();
				if ( ! empty( $taxes['total'] ) && class_exists( 'WC_Tax' ) ) {
					// Try to get rate from tax rates
					foreach ( $taxes['total'] as $tax_id => $tax_amount ) {
						if ( $tax_amount > 0 ) {
							// Get tax rate percent from WooCommerce (tax_id is tax rate ID)
							if ( method_exists( '\WC_Tax', 'get_rate_percent' ) ) {
								$rate_percent = \WC_Tax::get_rate_percent( $tax_id ); // e.g. "19.0000"
								$rate_percent = str_replace( '%', '', (string) $rate_percent );
								$rate_percent = str_replace( ',', '.', $rate_percent );
								if ( $rate_percent !== '' && is_numeric( $rate_percent ) ) {
									$vat_rate_decimal = floatval( $rate_percent ) / 100;
									break;
								}
							}
						}
					}
				}
				
				// Fallback: calculate from amounts if tax rate not found
				if ( $vat_rate_decimal === null ) {
					$vat_rate_decimal = $item_total_tax / $item_total_net;
				}

				// Snap to nearest 0.1% if we're very close (rounding differences like 2.00/10.55 = 18.957% -> 19.0%)
				$vat_percent = $vat_rate_decimal * 100;
				$vat_percent_snapped = round( $vat_percent, 1 );
				if ( abs( $vat_percent - $vat_percent_snapped ) < 0.051 ) {
					$vat_rate_decimal = $vat_percent_snapped / 100;
				}
				
				// Round to 4 decimal places for precision
				$vat_rate_decimal = floatval( number_format( $vat_rate_decimal, 4, '.', '' ) );
			} elseif ( $item_total_net > 0 && $item_total_tax == 0 ) {
				$vat_rate_decimal = 0.00;
			}
			
			// Get unit of measure from product or use default
			$unit = $default_unit ?: 'szt.';
			if ( $product ) {
				$product_unit = get_post_meta( $product->get_id(), '_ifirma_unit', true );
				if ( ! empty( $product_unit ) ) {
					$unit = $product_unit;
				}
			}
			
			$item_data = [
				'name'            => $item->get_name(),
				'quantity'        => floatval( $item->get_quantity() ),
				'price_net'       => $unit_price_net,
				'price_gross'     => $unit_price_gross,
				'unit'            => $unit,
				'vat'             => $vat_symbol,
				'vat_rate_decimal'=> $vat_rate_decimal, // Actual VAT rate from order (e.g., 0.19 for 19%)
			];

			// Lump sum (ryczałt) - additional to VAT
			if ( $lump_sum_enable && $product ) {
				$lump_sum_rate_raw = \Devikit\Ifirma\LumpSumProductFields::get_product_lump_sum( $product, $variation_id ?: null, $lump_sum_default_value );
				$lump_sum_rate_decimal = $this->prepare_lump_sum_rate_decimal( $lump_sum_rate_raw );
				if ( $lump_sum_rate_decimal !== null ) {
					$item_data['lump_sum_rate_decimal'] = $lump_sum_rate_decimal;
					$lump_sum_rates_for_shipping[] = $lump_sum_rate_decimal;
				}
			}
			
			// Add GTU if available (PRO)
			if ( $product ) {
				$gtu = get_post_meta( $product->get_id(), '_ifirma_gtu', true );
				if ( empty( $gtu ) && $vat_symbol !== 'zw' && $pro_features_enabled && ! empty( $default_gtu ) ) {
					$gtu = $default_gtu;
				}

				if ( ! empty( $gtu ) ) {
					$item_data['gtu'] = $gtu;
				}
				
				// Add PKWiU for ZW
				if ( $vat_symbol === 'zw' ) {
					$pkwiu = get_post_meta( $product->get_id(), '_ifirma_pkwiu', true );
					if ( empty( $pkwiu ) && $pro_features_enabled && ! empty( $default_pkwiu ) ) {
						$pkwiu = $default_pkwiu;
					}
					if ( ! empty( $pkwiu ) ) {
						$item_data['pkwiu'] = $pkwiu;
					}
				}
			}
			
			$items[] = $item_data;
		}

		// Add shipping
		$shipping_items = $order->get_items( 'shipping' );
		$lump_sum_for_shipping = null;
		if ( $lump_sum_enable && ! empty( $lump_sum_rates_for_shipping ) ) {
			$lump_sum_for_shipping = max( $lump_sum_rates_for_shipping );
		}
		foreach ( $shipping_items as $shipping_item ) {
			if ( $shipping_item->get_total() > 0 ) {
				$shipping_vat = $this->get_shipping_vat_symbol( $shipping_item, $settings, $items );
				$shipping_net = round( $shipping_item->get_total(), 2 );
				$shipping_tax = floatval( $shipping_item->get_total_tax() );
				$shipping_gross = round( $shipping_net + $shipping_tax, 2 );
				
				// Calculate actual VAT rate for shipping
				$shipping_vat_rate_decimal = null;
				if ( $shipping_net > 0 && $shipping_tax > 0 ) {
					$taxes = $shipping_item->get_taxes();
					if ( ! empty( $taxes['total'] ) && class_exists( 'WC_Tax' ) ) {
						foreach ( $taxes['total'] as $tax_id => $tax_amount ) {
							if ( $tax_amount > 0 ) {
								if ( method_exists( '\WC_Tax', 'get_rate_percent' ) ) {
									$rate_percent = \WC_Tax::get_rate_percent( $tax_id ); // e.g. "19.0000"
									$rate_percent = str_replace( '%', '', (string) $rate_percent );
									$rate_percent = str_replace( ',', '.', $rate_percent );
									if ( $rate_percent !== '' && is_numeric( $rate_percent ) ) {
										$shipping_vat_rate_decimal = floatval( $rate_percent ) / 100;
										break;
									}
								}
							}
						}
					}
					
					if ( $shipping_vat_rate_decimal === null ) {
						$shipping_vat_rate_decimal = $shipping_tax / $shipping_net;
					}

					$vat_percent = $shipping_vat_rate_decimal * 100;
					$vat_percent_snapped = round( $vat_percent, 1 );
					if ( abs( $vat_percent - $vat_percent_snapped ) < 0.051 ) {
						$shipping_vat_rate_decimal = $vat_percent_snapped / 100;
					}
					$shipping_vat_rate_decimal = floatval( number_format( $shipping_vat_rate_decimal, 4, '.', '' ) );
				} elseif ( $shipping_net > 0 && $shipping_tax == 0 ) {
					$shipping_vat_rate_decimal = 0.00;
				}
				
				$shipping_data = [
					'name'            => ! empty( $shipping_item->get_name() ) ? $shipping_item->get_name() : __( 'Shipping', 'invoicing-integration-for-ifirma-and-woocommerce' ),
					'quantity'        => 1,
					'price_net'       => $shipping_net,
					'price_gross'     => $shipping_gross,
					'unit'            => 'usł.',
					'vat'             => $shipping_vat,
					'vat_rate_decimal'=> $shipping_vat_rate_decimal, // Actual VAT rate from order
				];
				if ( $lump_sum_for_shipping !== null ) {
					$shipping_data['lump_sum_rate_decimal'] = $lump_sum_for_shipping;
				}
				$items[] = $shipping_data;
			}
		}

		$data = [
			'customer'       => $customer,
			'items'          => $items,
			'date'           => $invoice_date,
			'sale_date'      => $sale_date,
			'payment_date'   => $payment_date,
			'payment_method' => $wc_payment_method,
			'paid'           => $is_paid,
			'currency'       => $currency,
			'bank_account'   => $settings['bank_account'] ?? '',
			'series'         => $settings['invoice_series'] ?? '',
			'place_of_issue' => $settings['place_of_issue'] ?? '',
		];

		// Add VAT exemption reason if applicable
		$has_exempt = false;
		foreach ( $items as $item ) {
			if ( $item['vat'] === 'zw' ) {
				$has_exempt = true;
				break;
			}
		}
		if ( $has_exempt && ! empty( $settings['vat_exemption_reason'] ) ) {
			$data['vat_exemption_reason'] = $settings['vat_exemption_reason'];
		}

		// Global invoice notes (with placeholders) - PRO feature (PRO gates via filter)
		if ( (bool) apply_filters( 'devikit_ifirma_pro_features_enabled', false ) ) {
			$default_notes = isset( $settings['invoice_notes'] ) ? trim( (string) $settings['invoice_notes'] ) : '';
			if ( $default_notes !== '' ) {
				$data['notes'] = $this->replace_order_variables( $default_notes, $order );
			}
		}

		if ( $this->should_append_reverse_charge_note( $billing_country_code, $nip ) ) {
			$line = __( 'Reverse charge', 'invoicing-integration-for-ifirma-and-woocommerce' );
			if ( ! empty( $data['notes'] ) ) {
				$data['notes'] = trim( (string) $data['notes'] ) . "\n" . $line;
			} else {
				$data['notes'] = $line;
			}
		}

		return $data;
	}

	/**
	 * Whether to add "Reverse charge" to invoice notes: third country (not PL, not EU) and tax ID present.
	 *
	 * @param string $billing_country_code Woo billing country (ISO 3166-1 alpha-2).
	 * @param string $tax_id               Value from get_order_tax_id (NIP / EU VAT / foreign ID).
	 * @return bool
	 */
	private function should_append_reverse_charge_note( $billing_country_code, $tax_id ) {
		$country = strtoupper( trim( (string) $billing_country_code ) );
		if ( $country === '' || $country === 'PL' ) {
			return false;
		}
		if ( $this->api_client && method_exists( $this->api_client, 'is_eu_country' ) && $this->api_client->is_eu_country( $country ) ) {
			return false;
		}
		$tid = trim( preg_replace( '/\s+/', '', (string) $tax_id ) );
		return $tid !== '';
	}

	/**
	 * Prepare lump sum rate decimal for API payload (e.g., "8.5" => 0.0850).
	 *
	 * @param string $rate Raw rate string from settings/meta.
	 * @return float|null
	 */
	private function prepare_lump_sum_rate_decimal( $rate ) {
		$rate = trim( (string) $rate );
		if ( $rate === '' || $rate === 'empty' ) {
			return null;
		}

		$rate = str_replace( '%', '', $rate );
		$rate = str_replace( ',', '.', $rate );
		if ( ! is_numeric( $rate ) ) {
			return null;
		}

		$decimal = floatval( $rate ) / 100;
		if ( $decimal <= 0 ) {
			return null;
		}

		return floatval( number_format( $decimal, 4, '.', '' ) );
	}

	/**
	 * Replace order variables in text
	 *
	 * @param string   $text  Text with variables
	 * @param \WC_Order $order Order object
	 * @return string Text with variables replaced
	 */
	private function replace_order_variables( $text, $order ) {
		if ( ! $order ) {
			return $text;
		}

		$replacements = [
			'{order_id}'              => $order->get_id(),
			'{order_number}'          => $order->get_order_number(),
			'{order_date}'            => $order->get_date_created() ? $order->get_date_created()->date_i18n( get_option( 'date_format' ) ) : '',
			'{order_date_raw}'        => $order->get_date_created() ? $order->get_date_created()->date( 'Y-m-d' ) : '',
			'{customer_name}'         => trim( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() ),
			'{customer_first_name}'   => $order->get_billing_first_name(),
			'{customer_last_name}'    => $order->get_billing_last_name(),
			'{customer_email}'        => $order->get_billing_email(),
			'{customer_phone}'        => $order->get_billing_phone(),
			'{billing_company}'       => $order->get_billing_company(),
			'{billing_nip}'           => self::get_order_tax_id( $order ),
			'{billing_address}'       => $order->get_formatted_billing_address(),
			'{shipping_address}'      => $order->get_formatted_shipping_address(),
			'{order_total}'           => $order->get_total(),
			'{order_total_formatted}' => wc_price( $order->get_total(), [ 'currency' => $order->get_currency() ] ),
			'{payment_method}'        => $order->get_payment_method_title(),
			'{shipping_method}'       => $order->get_shipping_method(),
		];

		return str_replace( array_keys( $replacements ), array_values( $replacements ), $text );
	}

	/**
	 * Get VAT symbol for item
	 */
	private function get_item_vat_symbol( $item, $product, $settings ) {
		// Check if WooCommerce taxes are disabled
		if ( ! wc_tax_enabled() ) {
			return 'zw';
		}
		
		if ( ! $product ) {
			return '23';
		}
		
		$tax_class = $product->get_tax_class();
		
		if ( ! empty( $tax_class ) ) {
			if ( isset( $settings['tax_class_zw'] ) && $settings['tax_class_zw'] !== '_none_' && $settings['tax_class_zw'] === $tax_class ) {
				return 'zw';
			}
			
			if ( isset( $settings['tax_class_zero'] ) && $settings['tax_class_zero'] !== '_none_' && $settings['tax_class_zero'] === $tax_class ) {
				return '0';
			}
		}
		
		$total = $item->get_total();
		$tax = $item->get_total_tax();
		
		if ( $total > 0 && $tax > 0 ) {
			$rate = ( $tax / $total ) * 100;
			
			if ( $rate >= 22 && $rate <= 24 ) {
				return '23';
			}
			if ( $rate >= 7 && $rate <= 9 ) {
				return '8';
			}
			if ( $rate >= 4 && $rate <= 6 ) {
				return '5';
			}
			if ( $rate < 1 ) {
				return '0';
			}
		} elseif ( $total > 0 && $tax == 0 ) {
			return '0';
		}
		
		return '23';
	}

	/**
	 * Get VAT symbol for shipping
	 */
	private function get_shipping_vat_symbol( $item, $settings, $product_items ) {
		if ( ! empty( $product_items ) ) {
			$vat_symbols = [];
			$has_standard = false;
			
			foreach ( $product_items as $content ) {
				if ( isset( $content['vat'] ) ) {
					$vat = $content['vat'];
					$vat_symbols[] = $vat;
					
					if ( in_array( $vat, [ '23', '8', '5' ] ) ) {
						$has_standard = true;
					}
				}
			}
			
			if ( $has_standard ) {
				if ( in_array( '23', $vat_symbols ) ) {
					return '23';
				}
				if ( in_array( '8', $vat_symbols ) ) {
					return '8';
				}
				if ( in_array( '5', $vat_symbols ) ) {
					return '5';
				}
			}
			
			$unique = array_unique( $vat_symbols );
			if ( count( $unique ) === 1 ) {
				$rate = $unique[0];
				if ( in_array( $rate, [ 'zw', '0' ] ) ) {
					return $rate;
				}
			}
		}
		
		$total = $item->get_total();
		$tax = $item->get_total_tax();
		
		if ( $total > 0 && $tax > 0 ) {
			$rate = ( $tax / $total ) * 100;
			
			if ( $rate >= 22 && $rate <= 24 ) {
				return '23';
			}
			if ( $rate >= 7 && $rate <= 9 ) {
				return '8';
			}
			if ( $rate >= 4 && $rate <= 6 ) {
				return '5';
			}
			if ( $rate < 1 ) {
				return '0';
			}
		} elseif ( $total > 0 && $tax == 0 ) {
			return '0';
		}
		
		return '23';
	}

	/**
	 * Get country name in Polish
	 */
	private function get_country_name( $country_code ) {
		// Use WooCommerce's full country list (handles all ISO codes, respects site locale).
		if ( function_exists( 'WC' ) && WC()->countries ) {
			$wc_countries = WC()->countries->get_countries();
			if ( isset( $wc_countries[ $country_code ] ) ) {
				return html_entity_decode( $wc_countries[ $country_code ], ENT_QUOTES, 'UTF-8' );
			}
		}

		// Minimal fallback for environments where WC() is not yet available.
		$fallback = [
			'PL' => 'Polska',    'DE' => 'Niemcy',         'GB' => 'Wielka Brytania',
			'FR' => 'Francja',   'IT' => 'Włochy',         'ES' => 'Hiszpania',
			'NL' => 'Holandia',  'BE' => 'Belgia',         'AT' => 'Austria',
			'CZ' => 'Czechy',    'SK' => 'Słowacja',       'RO' => 'Romania',
			'HU' => 'Hungary',   'PT' => 'Portugal',       'SE' => 'Sweden',
			'DK' => 'Denmark',   'FI' => 'Finland',        'NO' => 'Norway',
			'CH' => 'Switzerland','US' => 'United States', 'CA' => 'Canada',
			'AU' => 'Australia', 'JP' => 'Japan',          'CN' => 'China',
			'BR' => 'Brazil',    'IN' => 'India',          'SG' => 'Singapore',
			'HR' => 'Croatia',   'BG' => 'Bulgaria',       'GR' => 'Greece',
			'IE' => 'Ireland',   'LT' => 'Lithuania',      'LV' => 'Latvia',
			'EE' => 'Estonia',   'LU' => 'Luxembourg',     'SI' => 'Slovenia',
			'CY' => 'Cyprus',    'MT' => 'Malta',
		];

		return $fallback[ $country_code ] ?? $country_code;
	}

	/**
	 * Display document download buttons on My Account order view (bottom, after addresses).
	 * Keep minimal UI: only buttons, no extra tables.
	 *
	 * @param \WC_Order $order
	 */
	public function display_document_download_buttons( $order ) {
		if ( ! $order || ! is_a( $order, 'WC_Order' ) ) {
			return;
		}

		$order_id = $order->get_id();

		if ( ! current_user_can( 'view_order', $order_id ) && get_current_user_id() !== $order->get_customer_id() ) {
			return;
		}

		$invoice_id = absint( $order->get_meta( '_ifirma_invoice_id' ) );
		$invoice_number = $order->get_meta( '_ifirma_invoice_number' );
		$proforma_id = absint( $order->get_meta( '_ifirma_proforma_id' ) );
		$proforma_number = $order->get_meta( '_ifirma_proforma_number' );
		$rachunek_id = absint( $order->get_meta( '_ifirma_rachunek_id' ) );
		$rachunek_number = $order->get_meta( '_ifirma_rachunek_number' );

		if ( ! $invoice_id && ! $proforma_id && ! $rachunek_id ) {
			return;
		}

		echo '<div class="ifirma-documents-download" style="margin-top: 15px;">';

		if ( $invoice_id ) {
			$download_url = add_query_arg(
				[
					'action'     => 'download_ifirma_invoice',
					'order_id'   => $order_id,
					'invoice_id' => $invoice_id,
					'_wpnonce'   => wp_create_nonce( 'download_ifirma_invoice_' . $order_id ),
				],
				home_url( '/' )
			);
			echo '<a href="' . esc_url( $download_url ) . '" class="button" target="_blank" style="margin-right:10px; margin-bottom:10px;">';
			echo esc_html__( 'Download Invoice', 'invoicing-integration-for-ifirma-and-woocommerce' );
			if ( $invoice_number ) {
				echo ' (' . esc_html( $invoice_number ) . ')';
			}
			echo '</a>';
		}

		if ( $proforma_id ) {
			$download_url = add_query_arg(
				[
					'action'      => 'download_ifirma_proforma',
					'order_id'    => $order_id,
					'proforma_id' => $proforma_id,
					'_wpnonce'    => wp_create_nonce( 'download_ifirma_proforma_' . $order_id ),
				],
				home_url( '/' )
			);
			echo '<a href="' . esc_url( $download_url ) . '" class="button" target="_blank" style="margin-right:10px; margin-bottom:10px;">';
			echo esc_html__( 'Download Proforma', 'invoicing-integration-for-ifirma-and-woocommerce' );
			if ( $proforma_number ) {
				echo ' (' . esc_html( $proforma_number ) . ')';
			}
			echo '</a>';
		}

		if ( $rachunek_id ) {
			$download_url = add_query_arg(
				[
					'action'      => 'download_ifirma_rachunek',
					'order_id'    => $order_id,
					'rachunek_id' => $rachunek_id,
					'_wpnonce'    => wp_create_nonce( 'download_ifirma_rachunek_' . $order_id ),
				],
				home_url( '/' )
			);
			echo '<a href="' . esc_url( $download_url ) . '" class="button" target="_blank" style="margin-right:10px; margin-bottom:10px;">';
			echo esc_html__( 'Download Rachunek', 'invoicing-integration-for-ifirma-and-woocommerce' );
			if ( $rachunek_number ) {
				echo ' (' . esc_html( $rachunek_number ) . ')';
			}
			echo '</a>';
		}

		echo '</div>';
	}

	/**
	 * Handle invoice download from frontend
	 */
	public function handle_invoice_download() {
		if ( ! isset( $_GET['action'] ) || $_GET['action'] !== 'download_ifirma_invoice' ) {
			return;
		}

		if ( ! isset( $_GET['order_id'], $_GET['invoice_id'], $_GET['_wpnonce'] ) ) {
			wp_die( esc_html__( 'Invalid request', 'invoicing-integration-for-ifirma-and-woocommerce' ) );
		}

		$order_id = absint( $_GET['order_id'] );
		$invoice_id = absint( $_GET['invoice_id'] );

		if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'download_ifirma_invoice_' . $order_id ) ) {
			wp_die( esc_html__( 'Invalid security token', 'invoicing-integration-for-ifirma-and-woocommerce' ) );
		}

		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			wp_die( esc_html__( 'Order not found', 'invoicing-integration-for-ifirma-and-woocommerce' ) );
		}

		if ( ! current_user_can( 'view_order', $order_id ) && get_current_user_id() !== $order->get_customer_id() ) {
			wp_die( esc_html__( 'You do not have permission to view this invoice', 'invoicing-integration-for-ifirma-and-woocommerce' ) );
		}

		$pdf_content = $this->api_client->download_pdf(
			$invoice_id,
			$this->order_invoice_type_to_download_pdf_type( $order )
		);

		if ( is_wp_error( $pdf_content ) ) {
			wp_die( esc_html( $pdf_content->get_error_message() ) );
		}

		$invoice_number = $order->get_meta( '_ifirma_invoice_number' );
		$filename = $invoice_number ? sanitize_file_name( $invoice_number ) . '.pdf' : 'invoice-' . $invoice_id . '.pdf';

		header( 'Content-Type: application/pdf' );
		header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
		header( 'Content-Length: ' . strlen( $pdf_content ) );
		header( 'Cache-Control: private, max-age=0, must-revalidate' );
		header( 'Pragma: public' );

		echo $pdf_content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		exit;
	}

	/**
	 * Handle proforma download from frontend
	 */
	public function handle_proforma_download() {
		if ( ! isset( $_GET['action'] ) || $_GET['action'] !== 'download_ifirma_proforma' ) {
			return;
		}

		if ( ! isset( $_GET['order_id'], $_GET['proforma_id'], $_GET['_wpnonce'] ) ) {
			wp_die( esc_html__( 'Invalid request', 'invoicing-integration-for-ifirma-and-woocommerce' ) );
		}

		$order_id = absint( $_GET['order_id'] );
		$proforma_id = absint( $_GET['proforma_id'] );

		if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'download_ifirma_proforma_' . $order_id ) ) {
			wp_die( esc_html__( 'Invalid security token', 'invoicing-integration-for-ifirma-and-woocommerce' ) );
		}

		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			wp_die( esc_html__( 'Order not found', 'invoicing-integration-for-ifirma-and-woocommerce' ) );
		}

		if ( ! current_user_can( 'view_order', $order_id ) && get_current_user_id() !== $order->get_customer_id() ) {
			wp_die( esc_html__( 'You do not have permission to view this invoice', 'invoicing-integration-for-ifirma-and-woocommerce' ) );
		}

		$stored_id = absint( $order->get_meta( '_ifirma_proforma_id' ) );
		if ( $stored_id !== $proforma_id ) {
			wp_die( esc_html__( 'Invalid request', 'invoicing-integration-for-ifirma-and-woocommerce' ) );
		}

		$pdf_content = $this->api_client->download_pdf( $proforma_id, 'proforma' );
		if ( is_wp_error( $pdf_content ) ) {
			wp_die( esc_html( $pdf_content->get_error_message() ) );
		}

		$number = $order->get_meta( '_ifirma_proforma_number' );
		$filename = $number ? sanitize_file_name( $number ) . '.pdf' : 'proforma-' . $proforma_id . '.pdf';

		header( 'Content-Type: application/pdf' );
		header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
		header( 'Content-Length: ' . strlen( $pdf_content ) );
		header( 'Cache-Control: private, max-age=0, must-revalidate' );
		header( 'Pragma: public' );

		echo $pdf_content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		exit;
	}

	/**
	 * Handle rachunek download from frontend
	 */
	public function handle_rachunek_download() {
		if ( ! isset( $_GET['action'] ) || $_GET['action'] !== 'download_ifirma_rachunek' ) {
			return;
		}

		if ( ! isset( $_GET['order_id'], $_GET['rachunek_id'], $_GET['_wpnonce'] ) ) {
			wp_die( esc_html__( 'Invalid request', 'invoicing-integration-for-ifirma-and-woocommerce' ) );
		}

		$order_id = absint( $_GET['order_id'] );
		$rachunek_id = absint( $_GET['rachunek_id'] );

		if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'download_ifirma_rachunek_' . $order_id ) ) {
			wp_die( esc_html__( 'Invalid security token', 'invoicing-integration-for-ifirma-and-woocommerce' ) );
		}

		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			wp_die( esc_html__( 'Order not found', 'invoicing-integration-for-ifirma-and-woocommerce' ) );
		}

		if ( ! current_user_can( 'view_order', $order_id ) && get_current_user_id() !== $order->get_customer_id() ) {
			wp_die( esc_html__( 'You do not have permission to view this invoice', 'invoicing-integration-for-ifirma-and-woocommerce' ) );
		}

		$stored_id = absint( $order->get_meta( '_ifirma_rachunek_id' ) );
		if ( $stored_id !== $rachunek_id ) {
			wp_die( esc_html__( 'Invalid request', 'invoicing-integration-for-ifirma-and-woocommerce' ) );
		}

		$pdf_content = $this->api_client->download_pdf( $rachunek_id, 'rachunek' );
		if ( is_wp_error( $pdf_content ) ) {
			wp_die( esc_html( $pdf_content->get_error_message() ) );
		}

		$number = $order->get_meta( '_ifirma_rachunek_number' );
		$filename = $number ? sanitize_file_name( $number ) . '.pdf' : 'rachunek-' . $rachunek_id . '.pdf';

		header( 'Content-Type: application/pdf' );
		header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
		header( 'Content-Length: ' . strlen( $pdf_content ) );
		header( 'Cache-Control: private, max-age=0, must-revalidate' );
		header( 'Pragma: public' );

		echo $pdf_content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		exit;
	}

	/**
	 * Map order meta _ifirma_invoice_type to Api\Client::download_pdf() type.
	 *
	 * @param \WC_Order $order Order.
	 * @return string invoice|wdt|foreign|oss
	 */
	private function order_invoice_type_to_download_pdf_type( \WC_Order $order ) {
		$meta = $order->get_meta( '_ifirma_invoice_type' );
		$meta = is_string( $meta ) ? strtolower( trim( $meta ) ) : '';

		if ( in_array( $meta, [ 'wdt', 'foreign', 'oss' ], true ) ) {
			return $meta;
		}

		return 'invoice';
	}
}
