<?php
/**
 * Public WooCommerce account integrations.
 *
 * @package PB_Invoicing_System
 */

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

class PBUAIV_Public {

    public function __construct() {
        add_filter( 'woocommerce_my_account_my_orders_actions', [ $this, 'add_order_download_actions' ], 20, 2 );
        add_action( 'wp_enqueue_scripts', [ $this, 'enqueue' ] );
    }

    /**
     * Add invoice / receipt download buttons directly to the normal WooCommerce
     * Orders table. No separate My Account page, because nobody asked for yet
     * another tab in humanity's already overstuffed account menus.
     *
     * @param array    $actions Existing WooCommerce order actions.
     * @param WC_Order $order   Order object.
     * @return array
     */
    public function add_order_download_actions( array $actions, $order ) : array {
        if ( ! $order instanceof WC_Order ) {
            return $actions;
        }

        if ( get_option( 'pbuaiv_customer_download', 'yes' ) !== 'yes' ) {
            return $actions;
        }

        $order_id  = $order->get_id();
        $doc_types = [
            'invoice' => __( 'Download Invoice', 'pb-invoicing-system' ),
            'receipt' => __( 'Download Receipt', 'pb-invoicing-system' ),
        ];

        foreach ( $doc_types as $doc_type => $label ) {
            $doc = PBUAIV_Email_Manager::factory( $doc_type, $order );
            if ( ! $doc || ! $doc->is_issued() ) {
                continue;
            }

            $actions[ 'pbuaiv_' . $doc_type ] = [
                'url'  => PBUAIV_Download_Handler::get_url( $order_id, $doc_type, 'download' ),
                'name' => $label,
            ];
        }

        return $actions;
    }

    public function enqueue() : void {
        if ( ! function_exists( 'is_account_page' ) || ! is_account_page() ) {
            return;
        }

        $css = '.woocommerce-orders-table .button.pbuaiv-order-download{margin-left:4px;}';
        wp_add_inline_style( 'woocommerce-general', $css );
    }
}
