<?php
defined( 'ABSPATH' ) || exit;

class W2PShopOrder {

	/**
	 * @var bool|WC_Order|WC_Order_Refund $woocommerce_order
	 */
	public mixed $woocommerce_order = false;

	public function __construct() {
	}

	/**
	 * Prepare order information.
	 *
	 * @param  $order_id int WooCommerce Order ID. Be sure not to pass the order number,
	 *                   as it can be different from the order ID in certain cases.
	 * @return array|bool
	 */
	public function prepare_order_info( int $order_id ): mixed {
		//get order object based on order ID
		$this->woocommerce_order = wc_get_order( $order_id );

		//case -1 : order not found
		if ( ! $this->woocommerce_order ) {
			return false;
		}

		//case -2 : order found - return array of order data
		$w2pshop_order = array();
		/**
		 * Order Data
		 */
		$w2pshop_order['order_id']       = $order_id;
		$w2pshop_order['order_number']   = $this->woocommerce_order->get_order_number();
		$w2pshop_order['date_created']   = $this->woocommerce_order->get_date_created();
		$w2pshop_order['date_completed'] = $this->woocommerce_order->get_date_completed();
		$w2pshop_order['order_status']   = $this->woocommerce_order->get_status();
		$w2pshop_order['currency']       = $this->woocommerce_order->get_currency();

		/**
		 * Billing Data
		 */
		$w2pshop_order['billing_address_1'] = $this->woocommerce_order->get_billing_address_1();
		$w2pshop_order['billing_address_2'] = $this->woocommerce_order->get_billing_address_2();
		$w2pshop_order['billing_city']      = $this->woocommerce_order->get_billing_city();
		$w2pshop_order['billing_state']     = $this->woocommerce_order->get_billing_state();
		$w2pshop_order['billing_postcode']  = $this->woocommerce_order->get_billing_postcode();
		$w2pshop_order['billing_country']   = $this->woocommerce_order->get_billing_country();
		$w2pshop_order['billing_email']     = $this->woocommerce_order->get_billing_email();

		/**
		 * Shipping Data
		 */
		$w2pshop_order['shipping_address_1'] = $this->woocommerce_order->get_shipping_address_1();
		$w2pshop_order['shipping_address_2'] = $this->woocommerce_order->get_shipping_address_2();
		$w2pshop_order['shipping_city']      = $this->woocommerce_order->get_shipping_city();
		$w2pshop_order['shipping_state']     = $this->woocommerce_order->get_shipping_state();
		$w2pshop_order['shipping_postcode']  = $this->woocommerce_order->get_shipping_postcode();
		$w2pshop_order['shipping_country']   = $this->woocommerce_order->get_shipping_country();

		/**
		 * Order Totals
		 */
		$w2pshop_order['order_total']          = $this->woocommerce_order->get_total(); //order total
		$w2pshop_order['order_discount-total'] = $this->woocommerce_order->get_discount_total();
		$w2pshop_order['cart_tax']             = $this->woocommerce_order->get_cart_tax();

		/**
		 * Refunds
		 */
		$w2pshop_order['refunds']             = $this->woocommerce_order->get_refunds(); //get order refunds
		$w2pshop_order['total_qty_refunded']  = $this->woocommerce_order->get_total_qty_refunded();
		$w2pshop_order['get_total_refunded']  = $this->woocommerce_order->get_total_refunded(); //get the amount already refunded
		$w2pshop_order['item_count_refunded'] = $this->woocommerce_order->get_item_count_refunded();// Gets the count of order items of a certain type that have been refunded.

		/**
		 * Order Items
		 */
		foreach ( $this->woocommerce_order->get_items() as $item ) {
			$w2pshop_order['order_items'][] = array(
				'item_name'           => $item->get_name(),
				'item_quantity'       => $item->get_quantity(),
				'item_subtotal_price' => $item->get_subtotal(),
				'item_price'          => $item->get_total(), //item total
				'item_id'             => $item->get_product_id(), //item id
				'item_type'           => $item->get_type(),
				'item_metadata'       => $item->get_meta_data(),
			);
		}

		return apply_filters( 'w2pshop_prepare_order', $w2pshop_order, $this->woocommerce_order );
	}

	/**
	 * Generates download PDF button HTML for an order item.
	 *
	 * @param WC_Order_Item $item
	 * @param string|null $pdf_url
	 *
	 * @return string
	 */
	public function generate_order_download_pdf_button( WC_Order_Item $item, ?string $pdf_url ): string {
		if ( empty( $pdf_url ) ) {
			return '';
		}

		// Get the item sequence number within the order
		$wc_order = new WC_Order( $item->get_order_id() );
		$default_pdf_file_name = W2PShopOrderUtil::getOrderName($item, $wc_order);

		$item_id               = $item->get_id();
		$default_pdf_file_name = apply_filters( 'w2pshop_pdf_artwork_filename', $default_pdf_file_name, $wc_order, $item_id );
		$pdf_file_name         = $default_pdf_file_name . '.pdf';

		// Allow plugins to override the download URL (e.g., for proxy downloads)
		$download_url = apply_filters( 'w2pshop_pdf_download_url', $pdf_url, $item, $pdf_file_name );

		// Generate download PDF button HTML
		return $this->generate_download_button_html( 'Download Design', $download_url, 'w2pshop-order-item-pdf', $pdf_file_name );
	}

	/**
	 * Generates download Artwork button HTML for an order item.
	 *
	 * @param string|null $artwork_url
	 * @param string $button_label
	 *
	 * @return string
	 */
	public function generate_order_download_artwork_button( WC_Order_Item $item, ?string $artwork_url, string $button_label = '' ): string {
		$button_label = ( ! empty( $button_label ) ) ? $button_label : 'Uploaded Artwork';

		return ( ! empty( $artwork_url ) ) ?
			$this->generate_download_button_html( $button_label, $artwork_url, 'w2pshop-order-item-artwork' )
			: '';
	}

	/**
	 * Generates order preview button HTML for an order item.
	 *
	 * @param array|string|null $thumbnail_urls
	 *
	 * @return string
	 */
	public function generate_order_preview_button( mixed $thumbnail_urls ) : string {
		if ( empty( $thumbnail_urls ) ) {
			return '';
		}

		// Ensure $thumbnail_urls is either an array or a string
		if ( ! is_array( $thumbnail_urls ) && ! is_string( $thumbnail_urls ) ) {
			return '';
		}
		if ( ! is_array( $thumbnail_urls ) ) {
			return $this->generate_preview_button_html( 'Customer Preview', $thumbnail_urls );
		}

		$button_html = '';
		foreach ( $thumbnail_urls as $index => $thumbnail_url ) {
			$button_html .= $this->generate_preview_button_html( 'Customer Preview ' . ( $index + 1 ), $thumbnail_url );
		}
		return $button_html;
	}

	/**
	 * Generates button HTML for a single thumbnail URL.
	 *
	 * @param string $button_text
	 * @param string $thumbnail_url
	 *
	 * @return string
	 */
    private function generate_preview_button_html( string $button_text, string $thumbnail_url ): string {
        return '<a href="#TB_inline?width=600&height=550&inlineId=w2pshop-order-item-preview-container"'
            . ' class="button button-small button-secondary w2pshop-order-item-preview thickbox"'
            . ' onclick="W2PShopAdminOrder.display_preview_image(\'' . esc_js( $button_text ) . '\', \'' . esc_url( $thumbnail_url ) . '\');"'
            . ' style="width: 150px; text-align: center;">' . esc_html( $button_text ) . '</a>';
    }

	/**
	 * Generates download button HTML.
	 *
	 * @param string $button_text
	 * @param string $download_url
	 * @param string $additional_class
	 * @param string $download_file_name
	 * @return string
	 */
    private function generate_download_button_html(
        string $button_text,
        string $download_url,
        string $additional_class = '',
        string $download_file_name = ''
    ): string {
        $allowed_tags = array(
            'br' => array(),
            'strong' => array(),
        );
        $download_attribute = '';
        if ( ! empty( $download_file_name ) ) {
            $download_attribute = ' download="' . esc_attr( $download_file_name ) . '"';
        }

        return '<a href="' . esc_url( $download_url ) . '"' . $download_attribute
            . ' class="button button-small button-secondary ' . esc_attr( $additional_class ) . ' w2pshop-order-item-download-button"'
            . ' style="width: 150px; text-align: center; margin-bottom: 3px;" target="_blank">'
            .  wp_kses($button_text, $allowed_tags) . '</a>';
    }
}//! class
