<?php

namespace Devikit\Ifirma\Admin;

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

class OrderColumns {

	/**
	 * Constructor
	 */
	public function __construct() {
		// Add column to orders list
		add_filter( 'manage_edit-shop_order_columns', [ $this, 'add_order_column' ] );
		add_action( 'manage_shop_order_posts_custom_column', [ $this, 'render_order_column' ], 10, 2 );
		
		// HPOS support
		add_filter( 'manage_woocommerce_page_wc-orders_columns', [ $this, 'add_order_column' ] );
		add_action( 'manage_woocommerce_page_wc-orders_custom_column', [ $this, 'render_order_column_hpos' ], 10, 2 );
		
		// Enqueue scripts for orders list
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_scripts' ] );
	}

	/**
	 * Add iFirma column to orders list
	 */
	public function add_order_column( $columns ) {
		$new_columns = [];
		
		foreach ( $columns as $key => $column ) {
			$new_columns[ $key ] = $column;
			
			if ( $key === 'order_status' || $key === 'order_total' ) {
				$new_columns['ifirma_invoice'] = __( 'iFirma', 'invoicing-integration-for-ifirma-and-woocommerce' );
			}
		}
		
		return $new_columns;
	}

	/**
	 * Render iFirma column content (CPT)
	 */
	public function render_order_column( $column, $post_id ) {
		if ( $column !== 'ifirma_invoice' ) {
			return;
		}
		
		$order = wc_get_order( $post_id );
		if ( ! $order ) {
			return;
		}
		
		$this->render_column_content( $order );
	}

	/**
	 * Render iFirma column content (HPOS)
	 */
	public function render_order_column_hpos( $column, $order ) {
		if ( $column !== 'ifirma_invoice' ) {
			return;
		}
		
		if ( ! $order instanceof \WC_Order ) {
			return;
		}
		
		$this->render_column_content( $order );
	}

	/**
	 * Render column content
	 */
	private function render_column_content( $order ) {
		$documents = [];

		// Invoice
		$invoice_id = $order->get_meta( '_ifirma_invoice_id' );
		$invoice_number = $order->get_meta( '_ifirma_invoice_number' );
		if ( $invoice_id ) {
			$mismatch_type = $order->get_meta( '_ifirma_invoice_total_mismatch' );
			if ( $mismatch_type === 'yes' ) {
				$mismatch_type = 'minor';
			}
			$documents[] = [
				'type'     => 'invoice',
				'id'       => $invoice_id,
				'number'   => $invoice_number ?: __( 'Invoice', 'invoicing-integration-for-ifirma-and-woocommerce' ),
				'label'    => __( 'Invoice', 'invoicing-integration-for-ifirma-and-woocommerce' ),
				'can_download'       => true,
				'has_mismatch'       => ( $mismatch_type === 'minor' || $mismatch_type === 'major' ),
				'has_major_mismatch' => ( $mismatch_type === 'major' ),
				'order_total'        => floatval( $order->get_meta( '_ifirma_invoice_order_total' ) ),
				'doc_total'          => floatval( $order->get_meta( '_ifirma_invoice_ifirma_total' ) ),
				'difference'         => floatval( $order->get_meta( '_ifirma_invoice_total_difference' ) ),
			];
		}

		// Proforma
		$proforma_id = $order->get_meta( '_ifirma_proforma_id' );
		$proforma_number = $order->get_meta( '_ifirma_proforma_number' );
		if ( $proforma_id ) {
			$mismatch_type = $order->get_meta( '_ifirma_proforma_total_mismatch' );
			$difference = floatval( $order->get_meta( '_ifirma_proforma_total_difference' ) );
			if ( $mismatch_type === 'yes' ) {
				$mismatch_type = ( $difference > 0.01 ) ? 'major' : 'minor';
			}
			$documents[] = [
				'type'     => 'proforma',
				'id'       => $proforma_id,
				'number'   => $proforma_number ?: __( 'Proforma', 'invoicing-integration-for-ifirma-and-woocommerce' ),
				'label'    => __( 'Proforma', 'invoicing-integration-for-ifirma-and-woocommerce' ),
				'can_download'       => true,
				'has_mismatch'       => ( $mismatch_type === 'minor' || $mismatch_type === 'major' ),
				'has_major_mismatch' => ( $mismatch_type === 'major' ),
				'order_total'        => floatval( $order->get_meta( '_ifirma_proforma_order_total' ) ),
				'doc_total'          => floatval( $order->get_meta( '_ifirma_proforma_ifirma_total' ) ),
				'difference'         => $difference,
			];
		}

		// Rachunek
		$rachunek_id = $order->get_meta( '_ifirma_rachunek_id' );
		$rachunek_number = $order->get_meta( '_ifirma_rachunek_number' );
		if ( $rachunek_id ) {
			$mismatch_type = $order->get_meta( '_ifirma_rachunek_total_mismatch' );
			$difference = floatval( $order->get_meta( '_ifirma_rachunek_total_difference' ) );
			if ( $mismatch_type === 'yes' ) {
				$mismatch_type = ( $difference > 0.01 ) ? 'major' : 'minor';
			}
			$documents[] = [
				'type'     => 'rachunek',
				'id'       => $rachunek_id,
				'number'   => $rachunek_number ?: __( 'Rachunek', 'invoicing-integration-for-ifirma-and-woocommerce' ),
				'label'    => __( 'Rachunek', 'invoicing-integration-for-ifirma-and-woocommerce' ),
				'can_download'       => true,
				'has_mismatch'       => ( $mismatch_type === 'minor' || $mismatch_type === 'major' ),
				'has_major_mismatch' => ( $mismatch_type === 'major' ),
				'order_total'        => floatval( $order->get_meta( '_ifirma_rachunek_order_total' ) ),
				'doc_total'          => floatval( $order->get_meta( '_ifirma_rachunek_ifirma_total' ) ),
				'difference'         => $difference,
			];
		}

		if ( empty( $documents ) ) {
			echo '<span style="color: #999;">—</span>';
			return;
		}

		// Container: red background when any document has mismatch (like Fakturownia)
		$has_any_mismatch = false;
		foreach ( $documents as $doc ) {
			if ( ! empty( $doc['has_mismatch'] ) ) {
				$has_any_mismatch = true;
				break;
			}
		}
		$container_style = $has_any_mismatch
			? 'line-height: 1.8; background-color: #ffeaea; padding: 4px 6px; border-left: 3px solid #dc3232;'
			: 'line-height: 1.8;';

		$output = [];
		foreach ( $documents as $doc ) {
			$order_id = $order->get_id();
			$doc_output = '';

			$has_mismatch = ! empty( $doc['has_mismatch'] );
			$link_color = $has_mismatch ? '#dc3232' : '#2271b1';
			$link_weight = $has_mismatch ? 'bold' : 'normal';

			// Tooltip: include sum info when mismatch
			$tooltip = __( 'Download PDF', 'invoicing-integration-for-ifirma-and-woocommerce' );
			if ( $has_mismatch && $doc['order_total'] > 0 && $doc['doc_total'] > 0 ) {
				$tooltip = sprintf(
					/* translators: 1: Order total, 2: Document type label, 3: Document total, 4: Difference */
					__( 'Order total: %1$s | %2$s total: %3$s | Difference: %4$s', 'invoicing-integration-for-ifirma-and-woocommerce' ),
					number_format( $doc['order_total'], 2, ',', ' ' ),
					$doc['label'],
					number_format( $doc['doc_total'], 2, ',', ' ' ),
					number_format( $doc['difference'], 2, ',', ' ' )
				);
			} elseif ( $doc['has_major_mismatch'] ) {
				$tooltip .= ' — ' . __( 'Total mismatch! Email was not sent.', 'invoicing-integration-for-ifirma-and-woocommerce' );
			}

			$display_text = strlen( $doc['number'] ) > 20 ? substr( $doc['number'], 0, 17 ) . '...' : $doc['number'];
			$warning_icon = $has_mismatch ? '⚠️ ' : '';

			if ( $doc['can_download'] ) {
				$doc_output .= '<a href="#" class="ifirma-download-pdf-link" ';
				$doc_output .= 'data-invoice-id="' . esc_attr( $doc['id'] ) . '" ';
				$doc_output .= 'data-invoice-number="' . esc_attr( $doc['number'] ) . '" ';
				$doc_output .= 'data-document-type="' . esc_attr( $doc['type'] ) . '" ';
				$doc_output .= 'data-order-id="' . esc_attr( $order_id ) . '" ';
				$doc_output .= 'title="' . esc_attr( $tooltip ) . '" ';
				$doc_output .= 'style="color: ' . esc_attr( $link_color ) . '; text-decoration: none; font-weight: ' . esc_attr( $link_weight ) . ';">';
				$doc_output .= $warning_icon . esc_html( $display_text );
				$doc_output .= '</a>';
			} else {
				$doc_output .= '<span style="color: ' . esc_attr( $link_color ) . ';">' . $warning_icon . esc_html( $display_text ) . '</span>';
			}

			$output[] = $doc_output;
		}

		echo '<div style="' . esc_attr( $container_style ) . '">' . wp_kses_post( implode( '<br>', $output ) ) . '</div>';
	}
	
	/**
	 * Enqueue scripts for orders list
	 */
	public function enqueue_scripts( $hook_suffix ) {
		if ( $hook_suffix !== 'edit.php' && $hook_suffix !== 'woocommerce_page_wc-orders' ) {
			return;
		}
		
		global $post_type;
		if ( $hook_suffix === 'edit.php' && $post_type !== 'shop_order' ) {
			return;
		}
		
		wp_enqueue_script( 'jquery' );

		wp_localize_script( 'jquery', 'devikitIfirmaOrderColumns', [
			'nonce'             => wp_create_nonce( 'ifirma_download_pdf' ),
			'i18n_downloading'  => __( 'Downloading...', 'invoicing-integration-for-ifirma-and-woocommerce' ),
			'i18n_download_err' => __( 'Failed to download PDF', 'invoicing-integration-for-ifirma-and-woocommerce' ),
		] );

		$inline_js = "
			jQuery(document).ready(function($) {
				$(document).on('click', '.ifirma-download-pdf-link', function(e) {
					e.preventDefault();
					var \$link = $(this);
					var invoiceId = \$link.data('invoice-id');
					var invoiceNumber = \$link.data('invoice-number');
					var documentType = \$link.data('document-type') || 'invoice';
					var originalText = \$link.text();
					\$link.css('opacity', '0.5').text(devikitIfirmaOrderColumns.i18n_downloading);
					$.post(ajaxurl, {
						action: 'devikit_ifirma_download_pdf',
						invoice_id: invoiceId,
						invoice_number: invoiceNumber,
						document_type: documentType,
						nonce: devikitIfirmaOrderColumns.nonce
					}, function(response) {
						\$link.css('opacity', '1').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 || devikitIfirmaOrderColumns.i18n_download_err);
						}
					}).fail(function() {
						\$link.css('opacity', '1').text(originalText);
						alert(devikitIfirmaOrderColumns.i18n_download_err);
					});
				});
			});
		";
		wp_add_inline_script( 'jquery', $inline_js );
	}
}
