<?php

namespace Devikit\Wfirma\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 wFirma 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['wfirma_invoice'] = __( 'wFirma', 'invoicing-integration-for-wfirma-and-woocommerce' );
			}
		}
		
		return $new_columns;
	}

	/**
	 * Render wFirma column content (CPT)
	 */
	public function render_order_column( $column, $post_id ) {
		if ( $column !== 'wfirma_invoice' ) {
			return;
		}

		$order = wc_get_order( $post_id );
		if ( ! $order ) {
			return;
		}

		$this->render_column_content( $order );
	}

	/**
	 * Render wFirma column content (HPOS)
	 */
	public function render_order_column_hpos( $column, $order ) {
		if ( $column !== 'wfirma_invoice' ) {
			return;
		}

		if ( ! $order instanceof \WC_Order ) {
			return;
		}

		$this->render_column_content( $order );
	}

	/**
	 * Render column content
	 */
	private function render_column_content( $order ) {
		$documents = [];
		
		// Check for invoice
		$invoice_id = $order->get_meta( '_wfirma_invoice_id' );
		$invoice_number = $order->get_meta( '_wfirma_invoice_number' );
		if ( $invoice_id ) {
			$documents[] = [
				'type' => 'invoice',
				'id' => $invoice_id,
				'number' => $invoice_number ?: __( 'Invoice', 'invoicing-integration-for-wfirma-and-woocommerce' ),
				'can_download' => true,
			];
		}
		
		// Check for proforma
		$proforma_id = $order->get_meta( '_wfirma_proforma_id' );
		$proforma_number = $order->get_meta( '_wfirma_proforma_number' );
		if ( $proforma_id ) {
			$documents[] = [
				'type' => 'proforma',
				'id' => $proforma_id,
				'number' => $proforma_number ?: __( 'Proforma', 'invoicing-integration-for-wfirma-and-woocommerce' ),
				'can_download' => true,
			];
		}
		
		// Check for receipt
		$receipt_id = $order->get_meta( '_wfirma_receipt_id' );
		$receipt_number = $order->get_meta( '_wfirma_receipt_number' );
		$receipt_type = $order->get_meta( '_wfirma_receipt_type' );
		if ( $receipt_id ) {
			$documents[] = [
				'type' => 'receipt',
				'id' => $receipt_id,
				'number' => $receipt_number ?: __( 'Receipt', 'invoicing-integration-for-wfirma-and-woocommerce' ),
				'can_download' => ( $receipt_type !== 'fiscal' && $receipt_type !== '' ), // Non-fiscal receipts (dowód sprzedaży) can be downloaded, fiscal cannot
			];
		}
		
		if ( empty( $documents ) ) {
			echo '<span style="color: #999;">—</span>';
			return;
		}
		
		// Display all documents
		$output = [];
		foreach ( $documents as $doc ) {
			$order_id = $order->get_id();
			$doc_output = '';
			
			if ( $doc['type'] === 'receipt' ) {
				// For receipts: only non-fiscal (dowód sprzedaży) can be downloaded
				if ( $doc['can_download'] ) {
					// Add download link for non-fiscal receipts (dowód sprzedaży)
					$doc_output .= '<a href="#" class="wfirma-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__( 'Download PDF', 'invoicing-integration-for-wfirma-and-woocommerce' ) . '">';
					$doc_output .= esc_html( $doc['number'] );
					$doc_output .= '</a>';
				} else {
					// Fiscal receipts are non-clickable (plain text)
					$doc_output .= '<span style="color: #000;">' . esc_html( $doc['number'] ) . '</span>';
				}
			} elseif ( $doc['can_download'] && ( $doc['type'] === 'invoice' || $doc['type'] === 'proforma' ) ) {
				// Add download link for invoices and proformas
				$doc_output .= '<a href="#" class="wfirma-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__( 'Download PDF', 'invoicing-integration-for-wfirma-and-woocommerce' ) . '">';
				$doc_output .= esc_html( $doc['number'] );
				$doc_output .= '</a>';
			} else {
				// For other non-downloadable documents, show as plain text
				$doc_output .= '<span style="color: #000;">' . esc_html( $doc['number'] ) . '</span>';
			}
			
			$output[] = $doc_output;
		}
		
		// Show total mismatch warning (invoice or proforma)
		$mismatch_lines = [];
		
		$invoice_mismatch = $order->get_meta( '_wfirma_invoice_total_mismatch' ) === 'yes';
		if ( $invoice_mismatch && $invoice_id ) {
			$order_total = floatval( $order->get_meta( '_wfirma_invoice_order_total' ) );
			$invoice_total = floatval( $order->get_meta( '_wfirma_invoice_wfirma_total' ) );
			$difference = floatval( $order->get_meta( '_wfirma_invoice_total_difference' ) );
			$mismatch_lines[] = sprintf(
				/* translators: 1: Order total, 2: Invoice total, 3: Difference */
				__( '⚠ FV: zam. %1$s | fv %2$s | diff. %3$s', 'invoicing-integration-for-wfirma-and-woocommerce' ),
				number_format( $order_total, 2, ',', ' ' ),
				number_format( $invoice_total, 2, ',', ' ' ),
				number_format( $difference, 2, ',', ' ' )
			);
		}
		
		$proforma_mismatch = $order->get_meta( '_wfirma_proforma_total_mismatch' ) === 'yes';
		if ( $proforma_mismatch && $proforma_id ) {
			$order_total = floatval( $order->get_meta( '_wfirma_proforma_order_total' ) );
			$proforma_total = floatval( $order->get_meta( '_wfirma_proforma_wfirma_total' ) );
			$difference = floatval( $order->get_meta( '_wfirma_proforma_total_difference' ) );
			$mismatch_lines[] = sprintf(
				/* translators: 1: Order total, 2: Proforma total, 3: Difference */
				__( '⚠ Proforma: zam. %1$s | proforma %2$s | diff. %3$s', 'invoicing-integration-for-wfirma-and-woocommerce' ),
				number_format( $order_total, 2, ',', ' ' ),
				number_format( $proforma_total, 2, ',', ' ' ),
				number_format( $difference, 2, ',', ' ' )
			);
		}
		
		$html = '<div style="line-height: 1.8;">' . wp_kses_post( implode( '<br>', $output ) ) . '</div>';
		if ( ! empty( $mismatch_lines ) ) {
			$html .= '<div style="margin-top: 4px; font-size: 11px; color: #856404; background: #fff3cd; padding: 4px 6px; border-left: 3px solid #ffc107; border-radius: 2px;" title="' . esc_attr__( 'Total Mismatch Detected – sums do not match', 'invoicing-integration-for-wfirma-and-woocommerce' ) . '">';
			$html .= wp_kses_post( implode( '<br>', $mismatch_lines ) );
			$html .= '</div>';
		}
		
		echo $html;
	}
	
	/**
	 * Enqueue scripts for orders list
	 */
	public function enqueue_scripts( $hook_suffix ) {
		// Only load on orders list pages
		if ( $hook_suffix !== 'edit.php' && $hook_suffix !== 'woocommerce_page_wc-orders' ) {
			return;
		}
		
		// Check if we're on orders page
		global $post_type;
		if ( $hook_suffix === 'edit.php' && $post_type !== 'shop_order' ) {
			return;
		}
		
		wp_register_script(
			'devikit-wfirma-order-columns',
			DEVIKIT_WFIRMA_URL . 'assets/js/admin-order-columns.js',
			[ 'jquery' ],
			DEVIKIT_WFIRMA_VERSION,
			true
		);

		wp_localize_script(
			'devikit-wfirma-order-columns',
			'devikitWfirmaOrderColumns',
			[
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'nonce'   => wp_create_nonce( 'wfirma_download_pdf' ),
				'i18n'    => [
					'downloading' => __( 'Downloading...', 'invoicing-integration-for-wfirma-and-woocommerce' ),
					'failed'      => __( 'Failed to download PDF', 'invoicing-integration-for-wfirma-and-woocommerce' ),
				],
			]
		);

		wp_enqueue_script( 'devikit-wfirma-order-columns' );
	}
}

