<?php

namespace BexioConnectorByHelvy;

/**
 * Handle backend scripts
 *
 * @since 0.1.0
 */

defined('ABSPATH') || exit;

class AdminPanelAssets
{
	public function __construct()
	{
		add_action('admin_enqueue_scripts', array(__CLASS__, 'admin_enqueue_scripts'), 10, 1);

		add_filter( 'manage_woocommerce_page_wc-orders_columns', array($this, 'add_order_admin_bexio_column') );
		add_action( 'woocommerce_shop_order_list_table_custom_column', array($this,'populate_order_admin_bexio_column'), 10, 2 );
		add_action( 'woocommerce_admin_order_data_after_order_details', array($this,'display_bexio_metadata_in_admin_order_details') );

		add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_scripts']);
        add_action('wp_ajax_bexio_get_pdf', [$this, 'get_resource_pdf']);
        add_action('wp_ajax_nopriv_bexio_get_pdf', [$this, 'get_resource_pdf']); // Optional: For guests
	}

	public function enqueue_admin_scripts() {
		$screen = get_current_screen();
	
		_bcbh_log("enqueue_admin_scripts screeN: " . $screen->id);
		if ($screen && ($screen->id === 'shop_order' || $screen->id === 'woocommerce_page_wc-orders')) { // Load only on order admin pages
			wp_add_inline_script('jquery', "
				jQuery(document).ready(function($) {
					$('body').on('click', '.bexio-download-btn', function(e) {
						e.preventDefault();
						e.stopPropagation();
						var button = $(this);
						var type = button.data('type');
						var id = button.data('id');
	
						$.post('" . admin_url('admin-ajax.php') . "', {
							action: 'bexio_get_pdf',
							type: type,
							id: id,
							nonce: '" . wp_create_nonce('bexio_get_pdf') . "'
						}, function(response) {
							if (response.success) {
								var data = response.data;
								var byteCharacters = atob(data.content); // Decode Base64
								var byteNumbers = new Array(byteCharacters.length);

								for (var i = 0; i < byteCharacters.length; i++) {
									byteNumbers[i] = byteCharacters.charCodeAt(i);
								}

								var byteArray = new Uint8Array(byteNumbers);
								var blob = new Blob([byteArray], { type: data.mime });
								var link = document.createElement('a');

								link.href = window.URL.createObjectURL(blob);
								link.download = data.name;
								document.body.appendChild(link);
								link.click();
								document.body.removeChild(link);
							} else {
								alert('Error: ' + response.data.message);
							}
						}).fail(function() {
							alert('Something went wrong.');
						});
					});
				});
			");
			_bcbh_log("enqueue_admin_scripts screen enqueued");
		}
	}

    /**
     * Retrieve the PDF of the given invoice
     */
    public function get_resource_pdf() {
        if (!isset($_POST['id'], $_POST['type']) || !wp_verify_nonce($_POST['nonce'], 'bexio_get_pdf')) {
            wp_send_json_error(['message' => 'Invalid request.']);
            exit;
        }

        $resource_id = sanitize_text_field($_POST['id']);
        $resource_type = sanitize_text_field($_POST['type']);
        
        $pdf = $resource_type == "invoice"
			? API::instance()->get_invoice_pdf($resource_id)
			: API::instance()->get_order_pdf($resource_id);
        if ($pdf instanceof \WP_Error) {
			wp_send_json_error(['message' => 'Failed to retrieve PDF.', 'error' => $pdf]);
			exit;
        }

		wp_send_json_success($pdf);
    }
	
	/**
	 * Display Bexio metadata in WooCommerce order details.
	 * 
	 * @param \WC_Order $order WooCommerce order
	 */
	public function display_bexio_metadata_in_admin_order_details($order) {
		$bexio_meta = [
			'invoice_id' => $order->get_meta(AdminAPISettings::$prefix . 'bexio_invoice_id') ?: get_post_meta($order->get_id(), AdminAPISettings::$prefix . 'bexio_invoice_id', true),
			'invoice_number' => $order->get_meta(AdminAPISettings::$prefix . 'bexio_invoice_number') ?: get_post_meta($order->get_id(), AdminAPISettings::$prefix . 'bexio_invoice_number', true),
			'order_id' => $order->get_meta(AdminAPISettings::$prefix . 'bexio_order_id') ?: get_post_meta($order->get_id(), AdminAPISettings::$prefix . 'bexio_order_id', true),
			'order_number' => $order->get_meta(AdminAPISettings::$prefix . 'bexio_order_number') ?: get_post_meta($order->get_id(), AdminAPISettings::$prefix . 'bexio_order_number', true),
			'payment_id' => $order->get_meta(AdminAPISettings::$prefix . 'bexio_payment_id') ?: get_post_meta($order->get_id(), AdminAPISettings::$prefix . 'bexio_payment_id', true),
			'fulfillment_id' => $order->get_meta(AdminAPISettings::$prefix . 'bexio_fulfillment_id') ?: get_post_meta($order->get_id(), AdminAPISettings::$prefix . 'bexio_fulfillment_id', true),
		];

		$order_html = $bexio_meta['order_id']
			? '<a href="#" class="bexio-download-btn" data-type="order" data-id="'.$bexio_meta['order_id'].'"><span class="dashicons dashicons-arrow-down-alt" style="font-size: 1em;vertical-align: baseline;text-decoration: none;"></span></a>'
				. '<a href="https://office.bexio.com/index.php/kb_order/show/id/'.$bexio_meta['order_id'].'" target="_blank">' . $bexio_meta['order_number'] . '</a>'
			: '/';

		$invoice_html = $bexio_meta['invoice_id']
			? '<a href="#" class="bexio-download-btn" data-type="invoice" data-id="'.$bexio_meta['invoice_id'].'"><span class="dashicons dashicons-arrow-down-alt" style="font-size: 1em;vertical-align: baseline;text-decoration: none;"></span></a>'
				. '<a href="https://office.bexio.com/index.php/kb_invoice/show/id/'.$bexio_meta['invoice_id'].'" target="_blank">' . $bexio_meta['invoice_number'] . '</a>'
			: '/';
	?>
		<div class="form-field form-field-wide">
			<h4>Bexio Resources</h4>
			<p>
				<?php 
					echo '<strong>Order:</strong> ' . $order_html . '<br />';
					echo '<strong>Invoice:</strong> ' . $invoice_html;
				?>
			</p>
		</div>
	<?php
	}

	/**
	 * Populate bexio column in WooCommerce Orders list.
	 * 
	 * @param string $column Column name
	 * @param \WC_Order $order WooCommerce order
	 */
	public function populate_order_admin_bexio_column( $column, $order ) {
		if ( 'bexio' !== $column ) {
			return;
		}

		$bexio_meta = [
			'invoice_id' => $order->get_meta(AdminAPISettings::$prefix . 'bexio_invoice_id') ?: get_post_meta($order->get_id(), AdminAPISettings::$prefix . 'bexio_invoice_id', true),
			'invoice_number' => $order->get_meta(AdminAPISettings::$prefix . 'bexio_invoice_number') ?: get_post_meta($order->get_id(), AdminAPISettings::$prefix . 'bexio_invoice_number', true),
			'order_id' => $order->get_meta(AdminAPISettings::$prefix . 'bexio_order_id') ?: get_post_meta($order->get_id(), AdminAPISettings::$prefix . 'bexio_order_id', true),
			'order_number' => $order->get_meta(AdminAPISettings::$prefix . 'bexio_order_number') ?: get_post_meta($order->get_id(), AdminAPISettings::$prefix . 'bexio_order_number', true),
			'payment_id' => $order->get_meta(AdminAPISettings::$prefix . 'bexio_payment_id') ?: get_post_meta($order->get_id(), AdminAPISettings::$prefix . 'bexio_payment_id', true),
			'fulfillment_id' => $order->get_meta(AdminAPISettings::$prefix . 'bexio_fulfillment_id') ?: get_post_meta($order->get_id(), AdminAPISettings::$prefix . 'bexio_fulfillment_id', true),
		];

		if (empty($bexio_meta['invoice_id']) && empty($bexio_meta['order_id'])) {
			echo '/';
			return;
		}
		
		$html = '';
		if ($bexio_meta['order_id']) {
			$html .= '<a href="#" class="bexio-download-btn" data-type="order" data-id="'.$bexio_meta['order_id'].'"><span class="dashicons dashicons-arrow-down-alt" style="font-size: 1em;vertical-align: bottom;"></span></a>';
			$html .= '<a href="https://office.bexio.com/index.php/kb_order/show/id/'.$bexio_meta['order_id'].'" target="_blank">' . $bexio_meta['order_number'] . '</a>';
		}
		if ($bexio_meta['invoice_id']) {
			$html .= "<br>";
			$html .= '<a href="#" class="bexio-download-btn" data-type="invoice" data-id="'.$bexio_meta['invoice_id'].'"><span class="dashicons dashicons-arrow-down-alt" style="font-size: 1em;vertical-align: bottom;"></span></a>';
			$html .= '<a href="https://office.bexio.com/index.php/kb_invoice/show/id/'.$bexio_meta['invoice_id'].'" target="_blank">' . $bexio_meta['invoice_number'] . '</a>';
		}

		echo $html;
	}

	/**
	 * Add bexio column to WooCommerce Orders list.
	 *
	 * @param array $columns Columns.
	 * @return array
	 */
	public function add_order_admin_bexio_column( $columns ) {
		$new_columns = array();
		foreach ($columns as $column_name => $column_info) {
			$new_columns[$column_name] = $column_info;
			if ('order_total' === $column_name) {
				$new_columns['bexio'] = 'Bexio';
			}
		}
		return $new_columns;
	}

	/**
	 * Enqueue Backend Scripts
	 *
	 * @since 0.1.0
	 */
	public static function admin_enqueue_scripts($hook)
	{
		if (!empty( $hook ) && substr( $hook, -strlen( 'bexio-connector-by-helvy' ) ) === 'bexio-connector-by-helvy') {
			$apiNonce = wp_create_nonce('wp_rest');
			$root = rest_url(BEXIO_CONNECTOR_BY_HELVY_REST_API_ROUTE . '/');
			$baseUrl = BEXIO_CONNECTOR_BY_HELVY_URL; // can be used for assets

			if (defined('BEXIO_CONNECTOR_BY_HELVY_ENV') && BEXIO_CONNECTOR_BY_HELVY_ENV == "dev") {
				include_once plugin_dir_path( __FILE__ ) . "../../includes_dev/enqueue_front.php";
			} else {
				wp_enqueue_script('bexio-connector-by-helvy-backend', BEXIO_CONNECTOR_BY_HELVY_URL . 'assets/js/index.js', array('wp-i18n'), BEXIO_CONNECTOR_BY_HELVY_VERSION, true);
				wp_localize_script(
					'bexio-connector-by-helvy-backend',
					'bexioConnectorByHelvy',
					array(
						'apiNonce'     => $apiNonce,
						'root'          => $root,
						'baseUrl'   => $baseUrl,
						'adminUrl' => admin_url(),
						'userLocale' => get_user_locale(),
						'version' => BEXIO_CONNECTOR_BY_HELVY_VERSION,
					)
				);
			}
		}
	}
}
