<?php
/**
 * Branded Printable Invoice — standalone document.
 *
 * Rendered by StorefrontModule::maybe_render_invoice() on the
 * `template_redirect` hook, OUTSIDE the theme wrapper, so it emits its own
 * complete HTML document (own <head> + screen/print CSS). This guarantees a
 * clean, branded printout regardless of the active theme — unlike a raw
 * window.print() of the admin SPA, which dumps the whole admin chrome.
 *
 * Reached three ways (auth enforced by the dispatcher BEFORE this file loads):
 *   1. Admin "Print" button on the order detail     → /order-invoice/{number}/?print=1
 *   2. Customer account order view (logged-in owner) → /order-invoice/{number}/
 *   3. "View / print invoice" link in order emails   → /order-invoice/{number}/?key={order_key}
 *
 * Override: copy to {theme}/titancart/checkout/invoice.php — TemplateLoader is
 * NOT used here (we include directly for the standalone document), so a theme
 * override is intentionally not supported for this print view; customise via
 * the titancart_invoice_* filters / CSS instead.
 *
 * Variables provided by the dispatcher (all guaranteed set):
 *   @var array  $order                 Full tc_orders row (+ resolved status_label).
 *   @var array  $items                 tc_order_items rows (+ options_summary).
 *   @var string $currency              Currency symbol.
 *   @var string $status_label          Human-readable status.
 *   @var string $payment_method_title  Resolved payment method name ('' if none).
 *   @var string $shipping_method_title Resolved shipping method name ('' if none).
 *   @var array  $company               name/email/address/phone/phone_2/website/year.
 *   @var string $logo_url              Logo URL ('' → falls back to company/site name).
 *   @var string $accent_color          Brand accent colour.
 *   @var bool   $auto_print            Trigger window.print() on load.
 *
 * @package TitanCart
 */

defined( 'ABSPATH' ) || exit;

/* ── Local presentation helpers ─────────────────────────────────────────── */
$tc_money = static function ( $v ) use ( $currency ) {
    return $currency . number_format( (float) $v, 2 );
};

$tc_inv_number = $order['order_number'] ?? (string) ( $order['id'] ?? '' );
$tc_inv_date   = function_exists( 'titancart_format_date' )
    ? titancart_format_date( $order['created_at'] ?? 'now' )
    : date_i18n( get_option( 'date_format' ), strtotime( (string) ( $order['created_at'] ?? 'now' ) ) );

$tc_company_name = $company['name'] !== '' ? $company['name'] : get_bloginfo( 'name' );

/* Address line for the seller block (already comma-trimmed upstream). */
$tc_company_addr = $company['address'] ?? '';

/* Reduction lines to show (only when > 0); grand total stays authoritative. */
$tc_discount      = (float) ( $order['discount'] ?? 0 );
$tc_gift_card     = (float) ( $order['gift_card_discount'] ?? 0 );
$tc_points_disc   = (float) ( $order['points_discount'] ?? 0 );
$tc_shipping_cost = (float) ( $order['shipping_cost'] ?? 0 );
$tc_surcharge     = (float) ( $order['payment_surcharge'] ?? 0 );
$tc_tip           = (float) ( $order['tip_total'] ?? 0 );
$tc_tax           = (float) ( $order['tax_total'] ?? 0 );

$tc_has_shipping_addr = ! empty( $order['shipping_address_1'] )
    || ! empty( $order['shipping_first_name'] );

/* Allow extensions to append rows after the items table (e.g. vendor notes). */
?><!DOCTYPE html>
<html lang="<?php echo esc_attr( get_locale() ); ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="robots" content="noindex,nofollow">
    <title><?php echo esc_html( sprintf( /* translators: %s = order number */ __( 'Invoice %s', 'titancart-lite' ), $tc_inv_number ) ); ?></title>
    <?php
    // WP.org R3: document styles live in a static stylesheet registered and
    // printed through the core styles API. This is a standalone document (own
    // <!DOCTYPE html>, rendered outside the theme, no wp_head), so
    // wp_print_styles() is invoked directly at the point the <head> needs it —
    // same pipeline, explicit print. The brand accent is the only dynamic
    // value and travels as a CSS custom property via wp_add_inline_style().
    wp_register_style(
        'titancart-invoice-print',
        TITANCART_ASSETS_URL . 'css/invoice-print.css',
        [],
        TITANCART_VERSION
    );
    $tc_inv_accent = sanitize_hex_color( (string) $accent_color );
    if ( ! is_string( $tc_inv_accent ) || $tc_inv_accent === '' ) {
        $tc_inv_accent = '#2563EB';
    }
    wp_add_inline_style( 'titancart-invoice-print', ':root{--tc-accent:' . $tc_inv_accent . ';}' );
    wp_print_styles( [ 'titancart-invoice-print' ] );
    ?>
</head>
<body>

<div class="tc-inv-actions no-print">
    <a href="#" class="tc-inv-btn" onclick="window.close();return false;"><?php esc_html_e( 'Close', 'titancart-lite' ); ?></a>
    <a href="#" class="tc-inv-btn tc-inv-btn--primary" onclick="window.print();return false;">🖨 <?php esc_html_e( 'Print / Save as PDF', 'titancart-lite' ); ?></a>
</div>

<div class="tc-inv">

    <!-- ── Header ── -->
    <div class="tc-inv__head">
        <div class="tc-inv__brand">
            <?php if ( $logo_url ) : ?>
                <img src="<?php echo esc_url( $logo_url ); ?>" alt="<?php echo esc_attr( $tc_company_name ); ?>">
            <?php else : ?>
                <div class="tc-inv__brand-name"><?php echo esc_html( $tc_company_name ); ?></div>
            <?php endif; ?>
            <div class="tc-inv__seller">
                <?php if ( $logo_url && $tc_company_name ) : ?>
                    <strong style="color:#1c2430"><?php echo esc_html( $tc_company_name ); ?></strong><br>
                <?php endif; ?>
                <?php if ( $tc_company_addr ) : ?><?php echo esc_html( $tc_company_addr ); ?><br><?php endif; ?>
                <?php if ( ! empty( $company['phone'] ) ) : ?><?php echo esc_html( $company['phone'] ); ?><br><?php endif; ?>
                <?php if ( ! empty( $company['email'] ) ) : ?><?php echo esc_html( $company['email'] ); ?><br><?php endif; ?>
                <?php if ( ! empty( $company['website'] ) ) : ?><?php echo esc_html( preg_replace( '#^https?://#', '', (string) $company['website'] ) ); ?><?php endif; ?>
            </div>
        </div>
        <div class="tc-inv__wordmark">
            <h1><?php esc_html_e( 'Invoice', 'titancart-lite' ); ?></h1>
            <div class="tc-inv__meta">
                <?php esc_html_e( 'Invoice No.', 'titancart-lite' ); ?> <strong><?php echo esc_html( $tc_inv_number ); ?></strong><br>
                <?php esc_html_e( 'Date', 'titancart-lite' ); ?>: <strong><?php echo esc_html( $tc_inv_date ); ?></strong><br>
                <?php esc_html_e( 'Status', 'titancart-lite' ); ?>: <span class="tc-inv__status"><?php echo esc_html( $status_label ); ?></span>
            </div>
        </div>
    </div>

    <div class="tc-inv__body">

        <!-- ── Addresses ── -->
        <div class="tc-inv__addresses">
            <div class="tc-inv__addr">
                <h3><?php esc_html_e( 'Billed To', 'titancart-lite' ); ?></h3>
                <address>
                    <?php echo esc_html( trim( ( $order['billing_first_name'] ?? '' ) . ' ' . ( $order['billing_last_name'] ?? '' ) ) ); ?><br>
                    <?php if ( ! empty( $order['billing_company'] ) ) : ?><?php echo esc_html( $order['billing_company'] ); ?><br><?php endif; ?>
                    <?php echo esc_html( $order['billing_address_1'] ?? '' ); ?><br>
                    <?php if ( ! empty( $order['billing_address_2'] ) ) : ?><?php echo esc_html( $order['billing_address_2'] ); ?><br><?php endif; ?>
                    <?php
                        echo esc_html( $order['billing_city'] ?? '' );
                        if ( ! empty( $order['billing_state'] ) ) echo ', ' . esc_html( $order['billing_state'] );
                        echo ' ' . esc_html( $order['billing_postcode'] ?? '' );
                    ?><br>
                    <?php echo esc_html( $order['billing_country'] ?? '' ); ?><br>
                    <?php if ( ! empty( $order['billing_phone'] ) ) : ?><span class="tc-inv__addr-meta"><?php echo esc_html( $order['billing_phone'] ); ?></span><br><?php endif; ?>
                    <?php if ( ! empty( $order['billing_email'] ) ) : ?><span class="tc-inv__addr-meta"><?php echo esc_html( $order['billing_email'] ); ?></span><?php endif; ?>
                </address>
            </div>
            <?php if ( $tc_has_shipping_addr ) : ?>
            <div class="tc-inv__addr">
                <h3><?php esc_html_e( 'Shipped To', 'titancart-lite' ); ?></h3>
                <address>
                    <?php echo esc_html( trim( ( $order['shipping_first_name'] ?? '' ) . ' ' . ( $order['shipping_last_name'] ?? '' ) ) ); ?><br>
                    <?php if ( ! empty( $order['shipping_company'] ) ) : ?><?php echo esc_html( $order['shipping_company'] ); ?><br><?php endif; ?>
                    <?php echo esc_html( $order['shipping_address_1'] ?? '' ); ?><br>
                    <?php if ( ! empty( $order['shipping_address_2'] ) ) : ?><?php echo esc_html( $order['shipping_address_2'] ); ?><br><?php endif; ?>
                    <?php
                        echo esc_html( $order['shipping_city'] ?? '' );
                        if ( ! empty( $order['shipping_state'] ) ) echo ', ' . esc_html( $order['shipping_state'] );
                        echo ' ' . esc_html( $order['shipping_postcode'] ?? '' );
                    ?><br>
                    <?php echo esc_html( $order['shipping_country'] ?? '' ); ?>
                </address>
            </div>
            <?php endif; ?>
        </div>

        <!-- ── Items ── -->
        <table class="tc-inv__items">
            <thead>
                <tr>
                    <th><?php esc_html_e( 'Item', 'titancart-lite' ); ?></th>
                    <th class="tc-num"><?php esc_html_e( 'Qty', 'titancart-lite' ); ?></th>
                    <th class="tc-num"><?php esc_html_e( 'Unit Price', 'titancart-lite' ); ?></th>
                    <th class="tc-num"><?php esc_html_e( 'Amount', 'titancart-lite' ); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ( (array) $items as $item ) : ?>
                    <tr>
                        <td>
                            <span class="tc-inv__pname"><?php echo esc_html( $item['name'] ?? '' ); ?></span>
                            <?php if ( ! empty( $item['sku'] ) ) : ?><span class="tc-inv__psku"><?php echo esc_html( sprintf( /* translators: %s = SKU */ __( 'SKU: %s', 'titancart-lite' ), $item['sku'] ) ); ?></span><?php endif; ?>
                            <?php if ( ! empty( $item['options_summary'] ) ) : ?><span class="tc-inv__popts"><?php echo esc_html( $item['options_summary'] ); ?></span><?php endif; ?>
                        </td>
                        <td class="tc-num"><?php echo esc_html( (int) ( $item['quantity'] ?? 1 ) ); ?></td>
                        <td class="tc-num"><?php echo esc_html( $tc_money( $item['unit_price'] ?? 0 ) ); ?></td>
                        <td class="tc-num"><?php echo esc_html( $tc_money( $item['total'] ?? $item['subtotal'] ?? 0 ) ); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <!-- ── Totals ── -->
        <table class="tc-inv__totals">
            <tr>
                <td><?php esc_html_e( 'Subtotal', 'titancart-lite' ); ?></td>
                <td><?php echo esc_html( $tc_money( $order['subtotal'] ?? 0 ) ); ?></td>
            </tr>
            <?php if ( $tc_discount > 0 ) : ?>
            <tr>
                <td><?php echo esc_html( ! empty( $order['coupon_code'] )
                    ? sprintf( /* translators: %s = coupon code */ __( 'Discount (%s)', 'titancart-lite' ), $order['coupon_code'] )
                    : __( 'Discount', 'titancart-lite' ) ); ?></td>
                <td>&minus;<?php echo esc_html( $tc_money( $tc_discount ) ); ?></td>
            </tr>
            <?php endif; ?>
            <?php if ( $tc_gift_card > 0 ) : ?>
            <tr>
                <td><?php echo esc_html( ! empty( $order['gift_card_code'] )
                    ? sprintf( /* translators: %s = gift card code */ __( 'Gift Card (%s)', 'titancart-lite' ), $order['gift_card_code'] )
                    : __( 'Gift Card', 'titancart-lite' ) ); ?></td>
                <td>&minus;<?php echo esc_html( $tc_money( $tc_gift_card ) ); ?></td>
            </tr>
            <?php endif; ?>
            <?php if ( $tc_points_disc > 0 ) : ?>
            <tr>
                <td><?php echo esc_html( (int) ( $order['points_redeemed'] ?? 0 ) > 0
                    ? sprintf( /* translators: %d = points redeemed */ __( 'Loyalty Points (%d pts)', 'titancart-lite' ), (int) $order['points_redeemed'] )
                    : __( 'Loyalty Points', 'titancart-lite' ) ); ?></td>
                <td>&minus;<?php echo esc_html( $tc_money( $tc_points_disc ) ); ?></td>
            </tr>
            <?php endif; ?>
            <tr>
                <td><?php esc_html_e( 'Shipping', 'titancart-lite' ); ?></td>
                <td><?php echo $tc_shipping_cost > 0 ? esc_html( $tc_money( $tc_shipping_cost ) ) : esc_html__( 'Free', 'titancart-lite' ); ?></td>
            </tr>
            <?php if ( $tc_surcharge > 0 ) : ?>
            <tr>
                <td><?php esc_html_e( 'Payment surcharge', 'titancart-lite' ); ?></td>
                <td><?php echo esc_html( $tc_money( $tc_surcharge ) ); ?></td>
            </tr>
            <?php endif; ?>
            <?php if ( $tc_tax > 0 ) : ?>
            <tr>
                <td><?php esc_html_e( 'Tax', 'titancart-lite' ); ?></td>
                <td><?php echo esc_html( $tc_money( $tc_tax ) ); ?></td>
            </tr>
            <?php endif; ?>
            <?php if ( $tc_tip > 0 ) : ?>
            <tr>
                <td><?php echo esc_html( apply_filters( 'titancart_tip_line_label', __( 'Tip', 'titancart-lite' ), $order ) ); ?></td>
                <td><?php echo esc_html( $tc_money( $tc_tip ) ); ?></td>
            </tr>
            <?php endif; ?>
            <tr class="tc-inv__grand">
                <td><?php esc_html_e( 'Total', 'titancart-lite' ); ?></td>
                <td><?php echo esc_html( $tc_money( $order['total'] ?? 0 ) ); ?></td>
            </tr>
        </table>

        <!-- ── Payment / shipping method ── -->
        <?php if ( $payment_method_title !== '' || $shipping_method_title !== '' ) : ?>
        <div class="tc-inv__pay">
            <?php if ( $payment_method_title !== '' ) : ?>
                <?php esc_html_e( 'Payment method', 'titancart-lite' ); ?>: <strong><?php echo esc_html( $payment_method_title ); ?></strong><br>
            <?php endif; ?>
            <?php if ( $shipping_method_title !== '' ) : ?>
                <?php esc_html_e( 'Shipping method', 'titancart-lite' ); ?>: <strong><?php echo esc_html( $shipping_method_title ); ?></strong>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <!-- ── Customer note ── -->
        <?php if ( ! empty( $order['customer_note'] ) ) : ?>
        <div class="tc-inv__note">
            <strong><?php esc_html_e( 'Order note', 'titancart-lite' ); ?></strong>
            <?php echo esc_html( $order['customer_note'] ); ?>
        </div>
        <?php endif; ?>

        <!-- ── Footer ── -->
        <div class="tc-inv__foot">
            <?php esc_html_e( 'Thank you for your business.', 'titancart-lite' ); ?><br>
            &copy; <?php echo esc_html( ! empty( $company['year'] ) ? $company['year'] . '–' . gmdate( 'Y' ) : gmdate( 'Y' ) ); ?>
            <?php echo esc_html( $tc_company_name ); ?>
        </div>

    </div>
</div>

<?php if ( $auto_print ) : ?>
<?php
// WP.org R1 🅱1: standalone document — no footer to enqueue into, so use the
// core script-tag API directly.
wp_print_inline_script_tag( "window.addEventListener('load', function () { setTimeout(function () { window.print(); }, 250); });" );
?>
<?php endif; ?>

</body>
</html>
