<?php
/**
 * My Account invoice download for customers.
 *
 * Adds an "Invoice" column to the orders table in My Account,
 * with a download link for each order that has an invoice.
 *
 * @package FacturX_For_WooCommerce
 */

defined( 'ABSPATH' ) || exit;

class GOFACTOX_My_Account {

    public static function init(): void {
        // Add "Invoice" column to My Account orders table.
        add_filter( 'woocommerce_my_account_my_orders_columns', [ __CLASS__, 'add_invoice_column' ] );
        add_action( 'woocommerce_my_account_my_orders_column_gofactox_invoice', [ __CLASS__, 'render_invoice_column' ] );
    }

    /**
     * Add "Invoice" column after "Actions" in My Account orders.
     */
    public static function add_invoice_column( array $columns ): array {
        $new = [];
        foreach ( $columns as $key => $label ) {
            $new[ $key ] = $label;
            if ( $key === 'order-total' ) {
                $new['gofactox_invoice'] = __( 'Invoice', 'gofactox-e-invoicing-for-woocommerce' );
            }
        }
        return $new;
    }

    /**
     * Render the invoice download link in My Account.
     */
    public static function render_invoice_column( \WC_Order $order ): void {
        $invoice_number = $order->get_meta( '_gofactox_invoice_number' );

        if ( ! $invoice_number ) {
            echo '<span style="color: #999;">&mdash;</span>';
            return;
        }

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

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

        $download_url = GOFACTOX_Download::get_download_url( $order );
        printf(
            '<a href="%s" class="woocommerce-button button" target="_blank" style="font-size: 0.85em; padding: 0.4em 0.8em;">%s %s</a>',
            esc_url( $download_url ),
            esc_html__( 'PDF', 'gofactox-e-invoicing-for-woocommerce' ),
            esc_html( $invoice_number )
        );
    }
}
