<?php

namespace Devikit\WFirma\Frontend;

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

/**
 * My Account integration - allow customers to download invoices
 */
class MyAccount {

	/**
	 * Constructor
	 */
	public function __construct() {
		// Add invoice download link to order details - disabled, handled by InvoiceManager
		// add_action( 'woocommerce_order_details_after_order_table', [ $this, 'display_invoice_link' ], 10, 1 );
		
		// Handle download action
		add_action( 'template_redirect', [ $this, 'handle_download' ] );
	}

	/**
	 * Display invoice download link on order details page
	 *
	 * @param \WC_Order $order
	 */
	public function display_invoice_link( $order ) {
		// Check if order object is valid
		if ( ! $order || ! is_a( $order, 'WC_Order' ) ) {
			return;
		}

		// Check if customer is viewing their own order
		if ( ! $this->can_customer_view_order( $order ) ) {
			return;
		}

		$invoice_id = $order->get_meta( '_wfirma_invoice_id' );
		$invoice_number = $order->get_meta( '_wfirma_invoice_number' );

		// Check if invoice exists
		if ( empty( $invoice_id ) || empty( $invoice_number ) ) {
			return;
		}

		// Build download URL
		$download_url = add_query_arg( [
			'wfirma_download_invoice' => $invoice_id,
			'order_id' => $order->get_id(),
			'order_key' => $order->get_order_key(),
		], wc_get_endpoint_url( 'view-order', $order->get_id(), wc_get_page_permalink( 'myaccount' ) ) );

		?>
		<section class="woocommerce-wfirma-invoice" style="margin-top: 20px; padding: 20px; background: #f9f9f9; border: 1px solid #ddd; border-radius: 4px;">
			<h2><?php esc_html_e( 'Invoice', 'invoicing-integration-for-wfirma-and-woocommerce' ); ?></h2>
			<p>
				<strong><?php esc_html_e( 'Invoice Number:', 'invoicing-integration-for-wfirma-and-woocommerce' ); ?></strong>
				<?php echo esc_html( $invoice_number ); ?>
			</p>
			<p>
				<a href="<?php echo esc_url( $download_url ); ?>" class="button" target="_blank">
					<?php esc_html_e( 'Download Invoice (PDF)', 'invoicing-integration-for-wfirma-and-woocommerce' ); ?>
				</a>
			</p>
		</section>
		<?php
	}

	/**
	 * Handle invoice download request
	 */
	public function handle_download() {
		// Check if download request exists
		// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Order key verification provides sufficient security
		if ( ! isset( $_GET['wfirma_download_invoice'], $_GET['order_id'], $_GET['order_key'] ) ) {
			return;
		}

		$invoice_id = sanitize_text_field( wp_unslash( $_GET['wfirma_download_invoice'] ) );
		$order_id = absint( $_GET['order_id'] );
		$order_key = sanitize_text_field( wp_unslash( $_GET['order_key'] ) );
		// phpcs:enable WordPress.Security.NonceVerification.Recommended

		// Get order
		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			wp_die( esc_html__( 'Invalid order.', 'invoicing-integration-for-wfirma-and-woocommerce' ) );
		}

		// Verify order key
		if ( $order->get_order_key() !== $order_key ) {
			wp_die( esc_html__( 'Invalid order key.', 'invoicing-integration-for-wfirma-and-woocommerce' ) );
		}

		// Check if customer is viewing their own order
		if ( ! $this->can_customer_view_order( $order ) ) {
			wp_die( esc_html__( 'You do not have permission to access this invoice.', 'invoicing-integration-for-wfirma-and-woocommerce' ) );
		}

		// Verify invoice ID matches order meta
		$stored_invoice_id = $order->get_meta( '_wfirma_invoice_id' );
		if ( $stored_invoice_id != $invoice_id ) {
			wp_die( esc_html__( 'Invoice not found for this order.', 'invoicing-integration-for-wfirma-and-woocommerce' ) );
		}

		// Get API client
		$plugin = \Devikit\WFirma\Plugin::instance();
		$api_client = $plugin->get_api_client();

		// Download PDF
		$pdf_content = $api_client->download_invoice_pdf( $invoice_id );

		if ( is_wp_error( $pdf_content ) ) {
			wp_die( esc_html( $pdf_content->get_error_message() ) );
		}

		// Send PDF to browser
		$invoice_number = $order->get_meta( '_wfirma_invoice_number' );
		$filename = sanitize_file_name( 'invoice-' . $invoice_number . '.pdf' );

		header( 'Content-Type: application/pdf' );
		header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
		header( 'Content-Length: ' . strlen( $pdf_content ) );
		header( 'Cache-Control: private, max-age=0, must-revalidate' );
		header( 'Pragma: public' );

		echo $pdf_content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		exit;
	}

	/**
	 * Check if customer can view this order
	 *
	 * @param \WC_Order $order
	 * @return bool
	 */
	private function can_customer_view_order( $order ) {
		$user = wp_get_current_user();

		// Admin can always view
		if ( current_user_can( 'manage_woocommerce' ) ) {
			return true;
		}

		// Check if logged in customer owns this order
		if ( $user->ID > 0 && $user->ID === $order->get_customer_id() ) {
			return true;
		}

		// Check if viewing as guest with valid order key
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Order key verification provides sufficient security
		if ( isset( $_GET['order_key'] ) && $order->get_order_key() === sanitize_text_field( wp_unslash( $_GET['order_key'] ) ) ) {
			return true;
		}

		return false;
	}
}

