<?php

namespace Devikit\Sellsy\Admin;

use Devikit\Sellsy\Plugin;

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

class OrderColumns {

	public function __construct() {
		add_filter( 'manage_edit-shop_order_columns', [ $this, 'add_invoice_column' ] );
		add_action( 'manage_shop_order_posts_custom_column', [ $this, 'render_invoice_column' ], 10, 2 );

		add_filter( 'manage_woocommerce_page_wc-orders_columns', [ $this, 'add_invoice_column' ] );
		add_action( 'manage_woocommerce_page_wc-orders_custom_column', [ $this, 'render_invoice_column_hpos' ], 10, 2 );

		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_scripts' ] );
		add_action( 'wp_ajax_devikit_sellsy_column_download_pdf', [ $this, 'ajax_download_pdf' ] );
	}

	/**
	 * @param array $columns
	 * @return array
	 */
	public function add_invoice_column( $columns ) {
		$new_columns = [];

		foreach ( $columns as $key => $column ) {
			$new_columns[ $key ] = $column;
			if ( $key === 'order_status' || $key === 'order_total' ) {
				$new_columns['sellsy_invoice'] = __( 'sellsy Invoice', 'invoicing-integration-for-sellsy-and-woocommerce' );
			}
		}

		if ( ! isset( $new_columns['sellsy_invoice'] ) ) {
			$new_columns['sellsy_invoice'] = __( 'sellsy Invoice', 'invoicing-integration-for-sellsy-and-woocommerce' );
		}

		return $new_columns;
	}

	/**
	 * @param string $column
	 * @param int    $post_id
	 */
	public function render_invoice_column( $column, $post_id ) {
		if ( $column !== 'sellsy_invoice' ) {
			return;
		}

		$order = wc_get_order( $post_id );
		if ( $order ) {
			$this->render_column_content( $order );
		}
	}

	/**
	 * @param string    $column
	 * @param \WC_Order $order
	 */
	public function render_invoice_column_hpos( $column, $order ) {
		if ( $column !== 'sellsy_invoice' || ! $order instanceof \WC_Order ) {
			return;
		}

		$this->render_column_content( $order );
	}

	/**
	 * @param \WC_Order $order
	 */
	private function render_column_content( $order ) {
		$order_id  = $order->get_id();
		$documents = [];

		$invoice_id = $order->get_meta( '_sellsy_invoice_id' );
		if ( ! empty( $invoice_id ) ) {
			$invoice_number = $order->get_meta( '_sellsy_invoice_number' );
			$documents[]    = [
				'type'     => 'invoice',
				'id'       => (string) $invoice_id,
				'number'   => $invoice_number ? (string) $invoice_number : (string) $invoice_id,
				'label'    => __( 'Invoice', 'invoicing-integration-for-sellsy-and-woocommerce' ),
				'color'    => '#1a6fb0',
				'mismatch' => $order->get_meta( '_sellsy_invoice_total_mismatch' ) === 'yes',
			];
		}

		/**
		 * Add extra sellsy documents to the orders list column.
		 *
		 * @param array     $documents Document rows for the column.
		 * @param \WC_Order $order     Order being rendered.
		 */
		$documents = apply_filters( 'devikit_sellsy_order_column_documents', $documents, $order );

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

		echo '<div style="line-height: 1.8;">';
		foreach ( $documents as $index => $doc ) {
			if ( ! is_array( $doc ) || empty( $doc['id'] ) || empty( $doc['type'] ) ) {
				continue;
			}

			$display_text = isset( $doc['number'] ) ? (string) $doc['number'] : (string) $doc['id'];
			if ( strlen( $display_text ) > 20 ) {
				$display_text = substr( $display_text, 0, 17 ) . '...';
			}

			$label = isset( $doc['label'] ) ? (string) $doc['label'] : __( 'Document', 'invoicing-integration-for-sellsy-and-woocommerce' );
			$link_title = sprintf(
				/* translators: %s: document type label */
				__( 'Download %s PDF', 'invoicing-integration-for-sellsy-and-woocommerce' ),
				$label
			);
			if ( ! empty( $doc['mismatch'] ) ) {
				$link_title = sprintf(
					/* translators: %s: document type label */
					__( 'Download %s PDF (total mismatch)', 'invoicing-integration-for-sellsy-and-woocommerce' ),
					$label
				);
			}

			if ( $index > 0 ) {
				echo '<br>';
			}

			$color = isset( $doc['color'] ) ? (string) $doc['color'] : '#1a6fb0';
			$style = 'color: ' . ( ! empty( $doc['mismatch'] ) ? '#dc3232' : $color ) . '; text-decoration: none;';
			if ( isset( $doc['type'] ) && (string) $doc['type'] !== 'invoice' ) {
				$style .= ' font-size: 12px;';
			}

			echo '<a href="#" class="sellsy-download-pdf-link" ';
			echo 'data-document-id="' . esc_attr( (string) $doc['id'] ) . '" ';
			echo 'data-document-number="' . esc_attr( isset( $doc['number'] ) ? (string) $doc['number'] : '' ) . '" ';
			echo 'data-document-type="' . esc_attr( (string) $doc['type'] ) . '" ';
			echo 'data-order-id="' . esc_attr( (string) $order_id ) . '" ';
			echo 'title="' . esc_attr( $link_title ) . '" ';
			echo 'style="' . esc_attr( $style ) . '">';
			echo esc_html( $display_text );
			if ( ! empty( $doc['mismatch'] ) ) {
				echo ' !';
			}
			echo '</a>';
		}
		echo '</div>';
	}

	/**
	 * @param string $hook_suffix
	 */
	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_add_inline_script( 'jquery', $this->get_inline_script() );
	}

	/**
	 * @return string
	 */
	private function get_inline_script() {
		$downloading_text = esc_js( __( 'Downloading...', 'invoicing-integration-for-sellsy-and-woocommerce' ) );
		$download_error   = esc_js( __( 'Failed to download PDF', 'invoicing-integration-for-sellsy-and-woocommerce' ) );
		$nonce            = esc_js( wp_create_nonce( 'sellsy_column_download_pdf' ) );

		return "jQuery(function($){
			$(document).on('click', '.sellsy-download-pdf-link', function(e){
				e.preventDefault();
				var \$link = $(this);
				var documentId = \$link.data('document-id');
				var documentNumber = \$link.data('document-number');
				var documentType = \$link.data('document-type');
				var orderId = \$link.data('order-id');
				var originalText = \$link.text();

				\$link.css('opacity', '0.5').text('{$downloading_text}');

				$.post(ajaxurl, {
					action: 'devikit_sellsy_column_download_pdf',
					document_id: documentId,
					document_number: documentNumber,
					document_type: documentType,
					order_id: orderId,
					nonce: '{$nonce}'
				}, function(response){
					\$link.css('opacity', '1').text(originalText);

					if (response && response.success && response.data && 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 && response.data && response.data.message) ? response.data.message : '{$download_error}');
					}
				}).fail(function(){
					\$link.css('opacity', '1').text(originalText);
					alert('{$download_error}');
				});
			});
		});";
	}

	public function ajax_download_pdf() {
		check_ajax_referer( 'sellsy_column_download_pdf', 'nonce' );

		$document_id     = isset( $_POST['document_id'] ) ? sanitize_text_field( wp_unslash( $_POST['document_id'] ) ) : '';
		$document_number = isset( $_POST['document_number'] ) ? sanitize_text_field( wp_unslash( $_POST['document_number'] ) ) : '';
		$document_type   = isset( $_POST['document_type'] ) ? sanitize_key( wp_unslash( $_POST['document_type'] ) ) : 'invoice';
		$order_id        = isset( $_POST['order_id'] ) ? absint( $_POST['order_id'] ) : 0;

		if (
			! current_user_can( 'manage_woocommerce' )
			&& ! current_user_can( 'edit_shop_orders' )
			&& ! ( $order_id && current_user_can( 'edit_shop_order', $order_id ) )
		) {
			wp_send_json_error( [ 'message' => __( 'Unauthorized.', 'invoicing-integration-for-sellsy-and-woocommerce' ) ] );
		}

		if ( empty( $document_id ) || ! $order_id ) {
			wp_send_json_error( [ 'message' => __( 'Document ID is missing.', 'invoicing-integration-for-sellsy-and-woocommerce' ) ] );
		}

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

		if ( $document_type === 'invoice' ) {
			if ( (string) $order->get_meta( '_sellsy_invoice_id' ) !== (string) $document_id ) {
				wp_send_json_error( [ 'message' => __( 'Invoice does not belong to this order.', 'invoicing-integration-for-sellsy-and-woocommerce' ) ] );
			}
			$pdf = Plugin::instance()->get_invoice_manager()->fetch_invoice_pdf( $document_id, $order_id );
		} else {
			/**
			 * Resolve PDF binary for non-invoice sellsy documents in the orders list.
			 *
			 * @param null|string|\WP_Error $pdf           Default null.
			 * @param string                $document_type Document type key.
			 * @param string                $document_id   sellsy document id.
			 * @param int                   $order_id      WooCommerce order id.
			 */
			$pdf = apply_filters( 'devikit_sellsy_column_download_pdf', null, $document_type, $document_id, $order_id );
		}

		if ( $pdf === null ) {
			wp_send_json_error( [ 'message' => __( 'Invalid document type.', 'invoicing-integration-for-sellsy-and-woocommerce' ) ] );
		}

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

		$label = $document_number ? $document_number : $document_id;

		wp_send_json_success(
			[
				'pdf'      => base64_encode( $pdf ),
				'filename' => sanitize_file_name( (string) $label ) . '.pdf',
			]
		);
	}
}
