<?php

defined( 'ABSPATH' ) || exit;
/**
 * Invoice plugin integrations.
 *
 * Adds tax exemption details to PDF invoices and packing slips for:
 *  1. WooCommerce PDF Invoices & Packing Slips by Ewout Fernhout (WP Overnight)
 *     Plugin slug: woocommerce-pdf-invoices-packing-slips
 *
 *  2. WooCommerce PDF Invoices by WP Overnight
 *     Plugin slug: woocommerce-pdf-invoices
 *
 * Order meta used:
 *  _rankd_tx_was_exempt      — '1' if order was placed under exemption
 *  _rankd_tx_sources   — comma-separated source list at time of purchase
 *
 * Developers can suppress the notice entirely:
 *   add_filter( 'rankd_tx_show_invoice_notice', '__return_false' );
 *
 * Or customise the output:
 *   add_filter( 'rankd_tx_invoice_notice_html', function( $html, $order ) { ... }, 10, 2 );
 */
class Rankd_Tx_Invoice {
    public static function init() {
        // WooCommerce PDF Invoices & Packing Slips (Fernhout / WP Overnight)
        add_action(
            'wpo_wcpdf_after_order_details',
            array(__CLASS__, 'render_fernhout'),
            10,
            2
        );
        // WooCommerce PDF Invoices (older WP Overnight plugin — chromeorange)
        add_action(
            'woocommerce_pdf_invoice_after_order_table',
            array(__CLASS__, 'render_wp_overnight'),
            10,
            1
        );
        // Frontend thank-you page and My Account order detail.
        add_action(
            'woocommerce_order_details_after_order_table',
            array(__CLASS__, 'render_frontend_receipt'),
            10,
            1
        );
        // Admin order edit screen — shown in the order notes / after order items area.
        add_action(
            'woocommerce_admin_order_data_after_order_details',
            array(__CLASS__, 'render_admin_order_page'),
            10,
            1
        );
    }

    // -------------------------------------------------------------------------
    // WooCommerce PDF Invoices & Packing Slips (Fernhout)
    // -------------------------------------------------------------------------
    /**
     * @param string          $document_type  'invoice', 'packing-slip', etc.
     * @param WC_Order|object $order          WC_Order object passed directly by the hook.
     */
    public static function render_fernhout( $document_type, $order ) {
        if ( !apply_filters( 'rankd_tx_show_invoice_notice', true ) ) {
            return;
        }
        $show_on = apply_filters( 'rankd_tx_invoice_document_types', array('invoice', 'proforma', 'credit-note') );
        if ( !in_array( $document_type, $show_on, true ) ) {
            return;
        }
        // The hook passes the WC_Order directly as the second argument.
        // In some versions it may be wrapped in a document object — handle both.
        if ( $order instanceof WC_Order ) {
            $wc_order = $order;
        } elseif ( is_object( $order ) && isset( $order->order ) && $order->order instanceof WC_Order ) {
            $wc_order = $order->order;
        } elseif ( is_object( $order ) && method_exists( $order, 'get_id' ) ) {
            $wc_order = wc_get_order( $order->get_id() );
        } else {
            return;
        }
        $html = self::build_notice_html( $wc_order );
        if ( $html ) {
            echo wp_kses_post( $html );
        }
    }

    // -------------------------------------------------------------------------
    // WooCommerce PDF Invoices (older WP Overnight / chromeorange plugin)
    // -------------------------------------------------------------------------
    public static function render_wp_overnight( $order ) {
        if ( !apply_filters( 'rankd_tx_show_invoice_notice', true ) ) {
            return;
        }
        if ( !$order instanceof WC_Order ) {
            return;
        }
        $html = self::build_notice_html( $order );
        if ( $html ) {
            echo wp_kses_post( $html );
        }
    }

    // -------------------------------------------------------------------------
    // Admin order edit screen
    // -------------------------------------------------------------------------
    /**
     * Shows the exemption notice on the WP admin order edit page.
     * Appears in the order data section so admins can see it at a glance.
     *
     * @param WC_Order $order
     */
    public static function render_admin_order_page( $order ) {
        if ( !apply_filters( 'rankd_tx_show_invoice_notice', true ) ) {
            return;
        }
        if ( !$order instanceof WC_Order ) {
            return;
        }
        if ( '1' !== $order->get_meta( RANKD_TX_ORDER_META ) ) {
            return;
        }
        $html = self::build_notice_html( $order, 'frontend' );
        if ( $html ) {
            echo wp_kses_post( $html );
        }
    }

    // -------------------------------------------------------------------------
    // Frontend order confirmation / receipt page
    // -------------------------------------------------------------------------
    /**
     * Shows the exemption notice on the thank-you page and My Account order
     * detail page. Useful confirmation for the customer.
     *
     * @param WC_Order $order
     */
    public static function render_frontend_receipt( $order ) {
        if ( !apply_filters( 'rankd_tx_show_invoice_notice', true ) ) {
            return;
        }
        if ( !$order instanceof WC_Order ) {
            return;
        }
        if ( '1' !== $order->get_meta( RANKD_TX_ORDER_META ) ) {
            return;
        }
        // Only show to the customer or an admin — not to other logged-in users.
        $user_id = get_current_user_id();
        if ( $user_id && $user_id !== $order->get_customer_id() && !current_user_can( Rankd_Tx_Capabilities::CAP ) ) {
            return;
        }
        $html = self::build_notice_html( $order, 'frontend' );
        if ( $html ) {
            echo wp_kses_post( $html );
        }
    }

    // -------------------------------------------------------------------------
    // HTML builder
    // -------------------------------------------------------------------------
    /**
     * Builds the exemption notice HTML for a given order.
     * Returns empty string if the order is not exempt.
     *
     * Developers can replace the entire output:
     *   add_filter( 'rankd_tx_invoice_notice_html', function( $html, $order ) {
     *       return '<p>Custom exemption notice</p>';
     *   }, 10, 2 );
     *
     * @param  WC_Order $order
     * @param  string   $context  'invoice' or 'frontend'
     * @return string
     */
    public static function build_notice_html( WC_Order $order, $context = 'invoice' ) {
        if ( '1' !== $order->get_meta( RANKD_TX_ORDER_META ) ) {
            return '';
        }
        // Prefer the exact certificate stamped on the order at purchase time
        // (audit accuracy — invoices reprinted later must show the cert that
        // actually covered the order, not whatever is active now).
        $user_id = $order->get_customer_id();
        $cert = null;
        // PRO: resolve the certificate that covered the order.
        if ( function_exists( 'rankd_tx_fs' ) && rankd_tx_fs()->can_use_premium_code__premium_only() ) {
            $cert = self::resolve_certificate__premium_only( $order, $user_id );
        }
        if ( 'frontend' === $context ) {
            $html = self::build_frontend_html( $order, $cert );
        } else {
            $html = self::build_pdf_html( $order, $cert );
        }
        return apply_filters( 'rankd_tx_invoice_notice_html', $html, $order );
    }

    /**
     * Builds PDF-optimised HTML (inline styles, no external classes).
     */
    private static function build_pdf_html( WC_Order $order, $cert = null ) {
        $lines = array();
        if ( $cert ) {
            $lines[] = sprintf( '<strong>%s:</strong> %s', esc_html__( 'Organization', 'rankd-tax-exemption-certificates-for-woocommerce' ), esc_html( $cert->org_name ) );
            if ( $cert->ein ) {
                $lines[] = sprintf( '<strong>%s:</strong> %s', esc_html__( 'Certificate Number', 'rankd-tax-exemption-certificates-for-woocommerce' ), esc_html( $cert->ein ) );
            }
            if ( $cert->country ) {
                $countries = WC()->countries->get_countries();
                $country_name = $countries[$cert->country] ?? $cert->country;
                $location = $country_name;
                if ( $cert->state ) {
                    $states = WC()->countries->get_states( $cert->country );
                    $state_name = ( $states && isset( $states[$cert->state] ) ? $states[$cert->state] : $cert->state );
                    $location = $state_name . ', ' . $country_name;
                }
                $lines[] = sprintf( '<strong>%s:</strong> %s', esc_html__( 'Jurisdiction', 'rankd-tax-exemption-certificates-for-woocommerce' ), esc_html( $location ) );
            }
            if ( $cert->expiry_date ) {
                $lines[] = sprintf( '<strong>%s:</strong> %s', esc_html__( 'Certificate Expiry', 'rankd-tax-exemption-certificates-for-woocommerce' ), esc_html( date_i18n( get_option( 'date_format' ), strtotime( $cert->expiry_date ) ) ) );
            }
        }
        $rows_html = ( $lines ? '<br>' . implode( '<br>', $lines ) : '' );
        return sprintf( '<div style="margin:16px 0;padding:10px 14px;border:1px solid #ccc;border-left:3px solid #555;font-size:12px;line-height:1.6;">
				<strong style="font-size:13px;">%s</strong>%s
			</div>', esc_html__( 'Tax Exempt Order', 'rankd-tax-exemption-certificates-for-woocommerce' ), $rows_html );
    }

    /**
     * Builds frontend HTML (uses plugin CSS classes).
     */
    private static function build_frontend_html( WC_Order $order, $cert = null ) {
        $lines = array();
        if ( $cert ) {
            if ( $cert->org_name ) {
                $lines[] = '<strong>' . esc_html__( 'Organization:', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '</strong> ' . esc_html( $cert->org_name );
            }
            if ( $cert->ein ) {
                $lines[] = '<strong>' . esc_html__( 'Certificate Number:', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '</strong> ' . esc_html( $cert->ein );
            }
            if ( $cert->expiry_date ) {
                $lines[] = '<strong>' . esc_html__( 'Expires:', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '</strong> ' . esc_html( date_i18n( get_option( 'date_format' ), strtotime( $cert->expiry_date ) ) );
            }
        }
        $detail = ( $lines ? '<br><small>' . implode( ' &nbsp;|&nbsp; ', $lines ) . '</small>' : '' );
        return '<div class="rankd-tx-status-box rankd-tx-exempt" style="margin:16px 0;">' . '<span class="rankd-tx-status-icon">&#10003;</span>' . '<span><strong>' . esc_html__( 'Tax Exempt Order', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '</strong>' . $detail . '</span>' . '</div>';
    }

}
