<?php
/**
 * Class ReturnLabelDispatcher
 *
 * @package DhlPolska\Shipment
 */

namespace DhlPolska\Shipment;

use DhlPolskaVendor\WPDesk\PluginBuilder\Plugin\Hookable;

/**
 * Dispatch return label downloads.
 */
class ReturnLabelDispatcher implements Hookable {
	public const ACTION = 'dhl_polska_get_return_label';

	/**
	 * Hooks.
	 */
	public function hooks() {
		add_action( 'admin_post_' . self::ACTION, [ $this, 'dispatch_return_label' ] );
	}

	/**
	 * @return void
	 */
	public function dispatch_return_label(): void {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'Brak uprawnień.', 'dhl-polska' ) );
		}

		check_admin_referer( self::ACTION );

		$shipment_id = filter_input( INPUT_GET, 'shipment_id', FILTER_VALIDATE_INT );
		if ( ! $shipment_id ) {
			wp_die( esc_html__( 'Brak identyfikatora przesyłki.', 'dhl-polska' ) );
		}

		$shipment = fs_get_shipment( $shipment_id );
		if ( ! $shipment || ! method_exists( $shipment, 'get_return_label' ) ) { /** @phpstan-ignore-line */
			wp_die( esc_html__( 'Nie udało się pobrać etykiety zwrotnej.', 'dhl-polska' ) );
		}

		try {
			/** @var array{label_format: string, content: string, file_name: string} $label_data */
			$label_data = $shipment->get_return_label();
		} catch ( \Exception $exception ) {
			wp_die( esc_html( $exception->getMessage() ), esc_html__( 'Błąd etykiety zwrotnej', 'dhl-polska' ) );
		}

		header( 'Content-type: ' . $this->prepare_content_type( $label_data ) );
		header( 'Content-Disposition: attachment; filename=' . $label_data['file_name'] );
		echo $label_data['content']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		die();
	}

	/**
	 * @param array<string, string> $label_data .
	 *
	 * @return string
	 */
	private function prepare_content_type( array $label_data ): string {
		$label_format = strtolower( (string) ( $label_data['label_format'] ?? '' ) );
		if ( '' === $label_format ) {
			return 'application/octet-stream';
		}

		if ( 'html' === $label_format ) {
			return 'text/html';
		}

		return 'application/' . $label_format;
	}
}
