<?php

defined( 'ABSPATH' ) || exit;
/**
 * Stamps orders at placement and displays the Tax Exempt badge
 * on the admin order edit screen.
 */
class Rankd_Tx_Order_Meta {
    public static function init() {
        // Classic (shortcode) checkout. Fires right after the order and its
        // meta are saved.
        add_action( 'woocommerce_checkout_order_created', array(__CLASS__, 'stamp_order') );
        // Block-based Checkout / Store API. This is NOT the same request
        // path as the classic hook above — woocommerce_checkout_order_created
        // is fired by WC_Checkout::create_order() specifically, which block
        // checkout never calls. Without this second hook, stamp_order()
        // silently never ran for any order placed through the Checkout
        // block (the modern default), even though the checkout-time
        // exemption filter (compute_customer_exemption(), a separate code
        // path) worked correctly the whole time — tax was genuinely
        // removed, but the order was never stamped and the badge never
        // appeared. Same $order argument shape as the classic hook, so
        // stamp_order() needs no changes to handle both.
        add_action( 'woocommerce_store_api_checkout_order_processed', array(__CLASS__, 'stamp_order') );
        add_action( 'woocommerce_admin_order_data_after_billing_address', array(__CLASS__, 'render_badge') );
    }

    /**
     * Records exemption status + active sources at time of purchase.
     * Survives future changes to the user's status.
     */
    public static function stamp_order( WC_Order $order ) {
        $user_id = $order->get_customer_id();
        $exempt = false;
        $sources = array();
        // Jurisdiction from the order itself — the address that actually
        // applied at purchase, shipping first.
        $dest_country = ( $order->get_shipping_country() ?: $order->get_billing_country() );
        $dest_state = ( $order->get_shipping_state() ?: $order->get_billing_state() );
        if ( $user_id && Rankd_Tx_Capabilities::is_in_scope( $user_id ) ) {
            $sources = Rankd_Tx_Exemption::get_active_sources( $user_id, $dest_country, $dest_state );
            $exempt = !empty( $sources );
        }
        $order->update_meta_data( RANKD_TX_ORDER_META, ( $exempt ? '1' : '0' ) );
        $order->update_meta_data( '_rankd_tx_sources', implode( ', ', $sources ) );
        // PRO: stamp which certificate covered this order (audit trail) and
        // build the detailed certificate note.
        $cert_note = '';
        if ( $exempt && $user_id && function_exists( 'rankd_tx_fs' ) && rankd_tx_fs()->can_use_premium_code__premium_only() ) {
            $cert_note = self::stamp_certificate__premium_only(
                $order,
                $user_id,
                $dest_country,
                $dest_state
            );
        }
        $order->save_meta_data();
        // Add a human-readable order note so the exemption is visible in the
        // order timeline without needing to inspect metadata.
        if ( $exempt && $user_id ) {
            if ( $cert_note ) {
                $note = $cert_note;
            } else {
                $note = sprintf( 
                    /* translators: %s = exemption source list, e.g. "admin_toggle, role" */
                    __( 'Tax exempt order. Source: %s.', 'rankd-tax-exemption-certificates-for-woocommerce' ),
                    implode( ', ', $sources )
                 );
            }
            $order->add_order_note( $note );
        }
    }

    /**
     * Shows a badge in the billing section of the admin order screen.
     */
    public static function render_badge( WC_Order $order ) {
        if ( '1' !== $order->get_meta( RANKD_TX_ORDER_META ) ) {
            return;
        }
        $sources = $order->get_meta( '_rankd_tx_sources' );
        echo '<p class="rankd-tx-order-badge">' . '<span class="rankd-tx-badge rankd-tx-badge--active">' . '&#10003; ' . esc_html__( 'Tax Exempt Order', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '</span>';
        if ( $sources ) {
            echo ' <span class="rankd-tx-order-source">' . esc_html( sprintf( 
                /* translators: %s = exemption source list */
                __( 'Source: %s', 'rankd-tax-exemption-certificates-for-woocommerce' ),
                $sources
             ) ) . '</span>';
        }
        echo '</p>';
    }

}
