<?php
/**
 * Template: Single order detail — customer account view.
 *
 * Available variables:
 *   $order  — Full order row (status_handle, status_label, status_color included)
 *   $items  — Order line items with options
 *   $notes  — Customer-visible notes only
 *
 * Override: copy to your-theme/titancart/account/order-detail.php
 *
 * @package TitanCart
 */
defined( 'ABSPATH' ) || exit;

$currency      = $order['currency'] ?? 'USD';
$status_color  = $order['status_color'] ?? '#71797E';
$status_label  = $order['status_label'] ?? $order['status_handle'] ?? '—';
$my_orders_url = get_permalink() ?: home_url( '/my-orders/' );
?>
<div class="tc-order-detail">

    <!-- Back link -->
    <a href="<?php echo esc_url( $my_orders_url ); ?>" class="tc-back-link">
        ← <?php esc_html_e( 'Back to My Orders', 'titancart-lite' ); ?>
    </a>

    <!-- Order heading -->
    <div class="tc-order-header">
        <div>
            <h2 class="tc-order-title">
                <?php
                printf(
                    /* translators: %s: order number */
                    esc_html__( 'Order %s', 'titancart-lite' ),
                    esc_html( $order['order_number'] )
                );
                ?>
            </h2>
            <p class="tc-order-meta">
                <?php esc_html_e( 'Placed:', 'titancart-lite' ); ?>
                <?php echo esc_html( titancart_format_date( $order['created_at'] ) ); ?>
            </p>
        </div>
        <span class="tc-status-badge" style="--tc-status-color:<?php echo esc_attr( $status_color ); ?>;">
            <?php echo esc_html( $status_label ); ?>
        </span>
    </div>

    <?php
    // S267 (#7/KI-15): branded printable invoice. This order is already
    // owner-scoped (SELECT … WHERE customer_id = current customer), and the
    // /order-invoice/ route authorizes a logged-in owner without a key, so no
    // ?key= is needed here.
    $tc_inv_url = class_exists( '\TitanCart\Storefront\StorefrontModule' )
        ? \TitanCart\Storefront\StorefrontModule::invoice_url( $order )
        : '';
    if ( $tc_inv_url ) : ?>
    <p class="tc-order-actions" style="margin:6px 0 0;">
        <a href="<?php echo esc_url( $tc_inv_url ); ?>" target="_blank" rel="noopener" class="tc-back-link">
            🖨 <?php esc_html_e( 'Print Invoice', 'titancart-lite' ); ?>
        </a>
    </p>
    <?php endif; ?>

    <hr class="tc-divider">

    <!-- Items -->
    <h3><?php esc_html_e( 'Items Ordered', 'titancart-lite' ); ?></h3>
    <table class="tc-items-table">
        <thead>
            <tr>
                <th><?php esc_html_e( 'Product', 'titancart-lite' ); ?></th>
                <th style="text-align:center;"><?php esc_html_e( 'Qty', 'titancart-lite' ); ?></th>
                <th style="text-align:right;"><?php esc_html_e( 'Total', 'titancart-lite' ); ?></th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ( $items as $item ) :
                $line_total = isset( $item['total'] ) ? $item['total'] : ( $item['line_total'] ?? 0 );
            ?>
            <tr>
                <td>
                    <strong><?php echo esc_html( $item['name'] ); ?></strong>
                    <?php if ( ! empty( $item['sku'] ) ) : ?>
                        <br><small class="tc-muted">SKU: <?php echo esc_html( $item['sku'] ); ?></small>
                    <?php endif; ?>
                    <?php if ( ! empty( $item['options'] ) ) : ?>
                        <br><small class="tc-muted">
                            <?php echo esc_html( implode( ', ', array_map( fn( $o ) => $o['option_name'] . ': ' . $o['variant_name'], $item['options'] ) ) ); ?>
                        </small>
                    <?php endif; ?>
                </td>
                <td style="text-align:center;"><?php echo (int) $item['quantity']; ?></td>
                <td style="text-align:right;font-weight:600;">
                    <?php echo esc_html( number_format( (float) $line_total, 2 ) . ' ' . strtoupper( $currency ) ); ?>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <!-- Totals -->
    <div class="tc-totals-block">
        <?php if ( (float) ( $order['discount'] ?? 0 ) > 0 ) : ?>
        <div class="tc-total-row">
            <span><?php esc_html_e( 'Discount', 'titancart-lite' ); ?></span>
            <span>−<?php echo esc_html( number_format( (float) $order['discount'], 2 ) . ' ' . strtoupper( $currency ) ); ?></span>
        </div>
        <?php endif; ?>
        <div class="tc-total-row">
            <span><?php esc_html_e( 'Shipping', 'titancart-lite' ); ?></span>
            <span><?php echo esc_html( number_format( (float) ( $order['shipping_cost'] ?? 0 ), 2 ) . ' ' . strtoupper( $currency ) ); ?></span>
        </div>
        <?php if ( (float) ( $order['tax_total'] ?? 0 ) > 0 ) : ?>
        <div class="tc-total-row">
            <span><?php esc_html_e( 'Tax', 'titancart-lite' ); ?></span>
            <span><?php echo esc_html( number_format( (float) $order['tax_total'], 2 ) . ' ' . strtoupper( $currency ) ); ?></span>
        </div>
        <?php endif; ?>
        <?php if ( (float) ( $order['tip_total'] ?? 0 ) > 0 ) : ?>
        <div class="tc-total-row">
            <span><?php echo esc_html( apply_filters( 'titancart_tip_line_label', __( 'Tip', 'titancart-lite' ), $order ) ); ?></span>
            <span><?php echo esc_html( number_format( (float) $order['tip_total'], 2 ) . ' ' . strtoupper( $currency ) ); ?></span>
        </div>
        <?php endif; ?>
        <div class="tc-total-row tc-total-row--grand">
            <span><?php esc_html_e( 'Total', 'titancart-lite' ); ?></span>
            <strong><?php echo esc_html( number_format( (float) $order['total'], 2 ) . ' ' . strtoupper( $currency ) ); ?></strong>
        </div>
    </div>

    <?php
    // S282: customer-facing fulfillment/tracking. $shipments is enriched with a
    // per-carrier tracking_url upstream (OrdersModule). Defensive default so the
    // template never errors if rendered by a path that doesn't supply it.
    $shipments = $shipments ?? [];
    if ( ! empty( $shipments ) ) : ?>
    <hr class="tc-divider">
    <h3><?php esc_html_e( 'Shipments &amp; Tracking', 'titancart-lite' ); ?></h3>
    <div class="tc-shipments">
        <?php foreach ( $shipments as $sh ) :
            $sh_status_color = $sh['status_color'] ?? '#71797E';
            $sh_status_label = $sh['status_label'] ?? ( $sh['status_handle'] ?? __( 'Pending', 'titancart-lite' ) );
            $sh_carrier      = trim( (string) ( $sh['carrier'] ?? '' ) );
            $sh_tracking     = trim( (string) ( $sh['tracking_number'] ?? '' ) );
            $sh_track_url    = trim( (string) ( $sh['tracking_url'] ?? '' ) );
            // KI-22: only label a date "Shipped:" when shipped_at is actually set;
            // otherwise fall back to created_at under a neutral "Created:" label.
            $sh_shipped      = ! empty( $sh['shipped_at'] ) ? $sh['shipped_at'] : '';
            $sh_date         = $sh_shipped !== '' ? $sh_shipped : ( $sh['created_at'] ?? '' );
            $sh_date_lbl     = $sh_shipped !== '' ? __( 'Shipped:', 'titancart-lite' ) : __( 'Created:', 'titancart-lite' );
        ?>
        <div class="tc-shipment-card">
            <div class="tc-shipment-head">
                <span class="tc-status-badge" style="--tc-status-color:<?php echo esc_attr( $sh_status_color ); ?>;">
                    <?php echo esc_html( $sh_status_label ); ?>
                </span>
                <?php if ( $sh_date ) : ?>
                    <span class="tc-shipment-date">
                        <?php echo esc_html( $sh_date_lbl ); ?> <?php echo esc_html( titancart_format_date( $sh_date ) ); ?>
                    </span>
                <?php endif; ?>
            </div>
            <div class="tc-shipment-meta">
                <?php if ( $sh_carrier ) : ?>
                    <div><span class="tc-muted"><?php esc_html_e( 'Carrier:', 'titancart-lite' ); ?></span> <strong><?php echo esc_html( strtoupper( $sh_carrier ) ); ?></strong></div>
                <?php endif; ?>
                <?php if ( $sh_tracking ) : ?>
                    <div>
                        <span class="tc-muted"><?php esc_html_e( 'Tracking #:', 'titancart-lite' ); ?></span>
                        <?php if ( $sh_track_url ) : ?>
                            <a href="<?php echo esc_url( $sh_track_url ); ?>" target="_blank" rel="noopener" class="tc-track-link"><?php echo esc_html( $sh_tracking ); ?> ↗</a>
                        <?php else : ?>
                            <strong class="tc-track-num"><?php echo esc_html( $sh_tracking ); ?></strong>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
                <?php if ( ! $sh_carrier && ! $sh_tracking ) : ?>
                    <div class="tc-muted"><?php esc_html_e( 'Tracking details will appear here once added.', 'titancart-lite' ); ?></div>
                <?php endif; ?>
            </div>
            <?php if ( ! empty( $sh['items'] ) ) : ?>
            <ul class="tc-shipment-items">
                <?php foreach ( $sh['items'] as $sit ) : ?>
                <li>
                    <?php echo esc_html( $sit['product_name'] ?? ( $sit['product_code'] ?? __( 'Item', 'titancart-lite' ) ) ); ?>
                    <span class="tc-muted">&times; <?php echo (int) ( $sit['quantity'] ?? 0 ); ?></span>
                </li>
                <?php endforeach; ?>
            </ul>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <hr class="tc-divider">

    <!-- Addresses -->
    <div class="tc-address-grid">
        <div class="tc-address-card">
            <h3><?php esc_html_e( 'Billing Address', 'titancart-lite' ); ?></h3>
            <address><?php echo nl2br( esc_html( titancart_format_address( $order, 'billing' ) ) ); ?></address>
        </div>
        <div class="tc-address-card">
            <h3><?php esc_html_e( 'Shipping Address', 'titancart-lite' ); ?></h3>
            <address><?php echo nl2br( esc_html( titancart_format_address( $order, 'shipping' ) ) ); ?></address>
        </div>
    </div>

    <?php if ( ! empty( $notes ) ) : ?>
    <hr class="tc-divider">
    <h3><?php esc_html_e( 'Order Notes', 'titancart-lite' ); ?></h3>
    <ul class="tc-notes-list">
        <?php foreach ( $notes as $note ) : ?>
        <li class="tc-note">
            <p><?php echo wp_kses_post( $note['note'] ); ?></p>
            <small class="tc-muted">
                <?php echo esc_html( titancart_format_datetime( $note['created_at'] ) ); ?>
            </small>
        </li>
        <?php endforeach; ?>
    </ul>
    <?php endif; ?>

</div><!-- .tc-order-detail -->

<?php
// WP.org R2: inline CSS is built as a PHP string (no output buffering, no
// markup literals) and attached via wp_add_inline_style on a stub handle.
$tc_orderdetail_css = <<<'CSS'
/* S282: colors are driven by the titancart-theme design tokens (--tct-*) so the
   page follows light/dark mode automatically; each falls back to the original
   light value when the tokens aren't present (non-titancart themes). */
.tc-order-detail { font-family: inherit; max-width: 760px; }
.tc-back-link { display: inline-block; color: var(--tct-brand, #1F6AE1); text-decoration: none; font-size: 13px; font-weight: 500; margin-bottom: 20px; }
.tc-back-link:hover { text-decoration: underline; }
.tc-order-header { display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 12px; margin-bottom: 16px; }
.tc-order-title { font-size: 22px; font-weight: 700; margin: 0 0 4px; color: var(--tct-text, #0E2B53); }
.tc-order-meta { font-size: 13px; color: var(--tct-text-secondary, #5A6270); margin: 0; }
.tc-status-badge { display: inline-block; padding: 5px 14px; border-radius: 12px; font-size: 12px; font-weight: 600; background: color-mix(in srgb, var(--tc-status-color, #71797E) 12%, transparent); color: var(--tc-status-color, #71797E); }
.tc-divider { border: none; border-top: 1px solid var(--tct-border, #E1E5EA); margin: 24px 0; }
.tc-order-detail h3 { font-size: 15px; font-weight: 700; color: var(--tct-text, #0E2B53); margin: 0 0 12px; }
.tc-items-table { width: 100%; border-collapse: collapse; font-size: 14px; margin-bottom: 4px; }
.tc-items-table th { background: var(--tct-bg-tertiary, #F6F8FB); padding: 9px 12px; text-align: left; font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; color: var(--tct-text-secondary, #5A6270); border-bottom: 2px solid var(--tct-border, #E1E5EA); }
.tc-items-table td { padding: 12px; border-bottom: 1px solid var(--tct-border-subtle, #F0F2F5); vertical-align: top; color: var(--tct-text, inherit); }
.tc-items-table tr:last-child td { border-bottom: none; }
.tc-muted { color: var(--tct-text-secondary, #5A6270); }
.tc-totals-block { max-width: 280px; margin-left: auto; margin-top: 8px; }
.tc-total-row { display: flex; justify-content: space-between; padding: 5px 0; font-size: 13px; color: var(--tct-text, inherit); }
.tc-total-row--grand { border-top: 1px solid var(--tct-border, #E1E5EA); padding-top: 10px; margin-top: 4px; font-size: 15px; font-weight: 700; color: var(--tct-text, #0E2B53); }
.tc-address-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
.tc-address-card { background: var(--tct-bg-secondary, #F6F8FB); border: 1px solid var(--tct-border-subtle, transparent); border-radius: 10px; padding: 16px; font-size: 13px; line-height: 1.75; }
.tc-address-card address { font-style: normal; color: var(--tct-text, #1C2430); }
.tc-notes-list { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 10px; }
.tc-note { background: var(--tct-bg-secondary, #F6F8FB); border-left: 3px solid var(--tct-brand, #1F6AE1); padding: 12px 14px; border-radius: 0 8px 8px 0; color: var(--tct-text, inherit); }
.tc-note p { margin: 0 0 4px; font-size: 13px; }
/* Shipments / tracking */
.tc-shipments { display: flex; flex-direction: column; gap: 12px; }
.tc-shipment-card { background: var(--tct-bg-secondary, #F6F8FB); border: 1px solid var(--tct-border-subtle, #E1E5EA); border-radius: 10px; padding: 14px 16px; color: var(--tct-text, inherit); }
.tc-shipment-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 8px; flex-wrap: wrap; }
.tc-shipment-date { font-size: 12px; color: var(--tct-text-secondary, #5A6270); }
.tc-shipment-meta { font-size: 13px; line-height: 1.7; }
.tc-shipment-meta > div { margin-bottom: 2px; }
.tc-track-link { color: var(--tct-brand, #1F6AE1); text-decoration: none; font-weight: 600; }
.tc-track-link:hover { text-decoration: underline; }
.tc-track-num { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
.tc-shipment-items { list-style: none; padding: 0; margin: 8px 0 0; font-size: 13px; }
.tc-shipment-items li { padding: 2px 0; }
@media (max-width: 560px) { .tc-address-grid { grid-template-columns: 1fr; } }
CSS;
wp_register_style( 'titancart-orderdetail-inline', false, array(), TITANCART_VERSION );
wp_enqueue_style( 'titancart-orderdetail-inline' );
wp_add_inline_style( 'titancart-orderdetail-inline', $tc_orderdetail_css );
?>
