<?php
/**
 * "Download invoice" button on the WooCommerce order-received (Thank You) page.
 *
 * Renders only when the order already has an invoice attached. Reduces support
 * tickets like "where is my invoice?" right after checkout.
 *
 * @package FacturX_For_WooCommerce
 */

defined( 'ABSPATH' ) || exit;

class GOFACTOX_Thank_You {

    public static function init(): void {
        add_action( 'woocommerce_thankyou', [ __CLASS__, 'render_download_button' ], 5, 1 );
    }

    /**
     * Render the download button if an invoice exists for the order.
     *
     * @param int $order_id The order ID.
     */
    public static function render_download_button( $order_id ): void {
        $order = wc_get_order( $order_id );
        if ( ! $order instanceof \WC_Order ) {
            return;
        }

        $invoice_id = (int) $order->get_meta( '_gofactox_invoice_id' );
        if ( ! $invoice_id ) {
            return;
        }

        $pdf_path = GOFACTOX_Invoice::get_pdf_path( $invoice_id );
        if ( ! $pdf_path || ! file_exists( $pdf_path ) ) {
            return;
        }

        $url = GOFACTOX_Download::get_download_url( $order );
        ?>
        <p class="gofactox-thankyou-download" style="margin:16px 0;">
            <a href="<?php echo esc_url( $url ); ?>" class="button" target="_blank" rel="noopener">
                <?php esc_html_e( 'Download my Factur-X invoice', 'gofactox-e-invoicing-for-woocommerce' ); ?>
            </a>
        </p>
        <?php
    }
}
