<?php
/**
 * Email template: Order Confirmation — Customer.
 *
 * Sent to the customer immediately after they place an order.
 *
 * Available variables (via Mailer::render()):
 *   $order     — Full order row
 *   $items     — Order line items
 *   $site_name — Blog name
 *   $site_url  — Home URL
 *   $mailer    — Mailer instance
 *
 * @package TitanCart
 */
defined( 'ABSPATH' ) || exit;

$currency      = $order['currency'] ?? 'USD';
$customer_name = trim( $order['billing_first_name'] . ' ' . $order['billing_last_name'] );
$my_orders_url = apply_filters( 'titancart_my_orders_url', home_url( '/my-orders/' ) );

// Phase 4: When download keys were issued in this same request (sync gateway
// path), the Mailer stash is consumed by send_order_confirmation() and the
// hydrated $download_groups array is passed through here. For async gateways
// (PayPal capture / Stripe webhook), this variable will be unset on the
// initial confirmation — the customer receives a separate downloads-ready.php
// email when keys actually issue later.
$has_downloads = ! empty( $download_groups ) && is_array( $download_groups );
?>

<h1 style="margin-bottom:4px;">
    <?php
    printf(
        /* translators: %s: customer first name */
        esc_html__( 'Thank you, %s!', 'titancart-lite' ),
        esc_html( $order['billing_first_name'] )
    );
    ?>
</h1>
<p style="color:#5A6270;font-size:13px;margin-bottom:8px;">
    <?php esc_html_e( 'Your order has been received and is being processed.', 'titancart-lite' ); ?>
</p>
<p style="margin-bottom:28px;">
    <strong><?php esc_html_e( 'Order Number:', 'titancart-lite' ); ?></strong>
    <?php echo esc_html( $order['order_number'] ); ?><br>
    <strong><?php esc_html_e( 'Date:', 'titancart-lite' ); ?></strong>
    <?php echo esc_html( titancart_format_date( $order['created_at'] ) ); ?><br>
    <strong><?php esc_html_e( 'Status:', 'titancart-lite' ); ?></strong>
    <span class="status-badge" style="background:<?php echo esc_attr( $order['status_color'] ?? '#E1E5EA' ); ?>22;color:<?php echo esc_attr( $order['status_color'] ?? '#5A6270' ); ?>;">
        <?php echo esc_html( $order['status_label'] ?? $order['status_handle'] ?? '' ); ?>
    </span>
</p>

<!-- CTA -->
<p style="margin-bottom:10px;">
    <a href="<?php echo esc_url( $my_orders_url ); ?>" class="btn">
        <?php esc_html_e( 'View Your Orders', 'titancart-lite' ); ?>
    </a>
</p>
<?php
// S267 (#7/KI-15): link to the branded printable invoice. ?key= is appended
// (order_key is on the order row via o.* ) so the link opens without login —
// the customer can view it and Save-as-PDF / print from their browser.
$tc_invoice_url = class_exists( '\TitanCart\Storefront\StorefrontModule' )
    ? \TitanCart\Storefront\StorefrontModule::invoice_url( $order, true )
    : '';
if ( $tc_invoice_url ) : ?>
<p style="margin:0 0 32px;font-size:13px;">
    <a href="<?php echo esc_url( $tc_invoice_url ); ?>" style="color:<?php echo esc_attr( $accent_color ?? '#1F6AE1' ); ?>;text-decoration:none;">
        <?php esc_html_e( 'View or print your invoice', 'titancart-lite' ); ?> &rarr;
    </a>
</p>
<?php endif; ?>

<hr class="divider">

<!-- Order items -->
<h2><?php esc_html_e( 'Your Order', 'titancart-lite' ); ?></h2>

<table class="order-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( 'Price', '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['options'] ) ) : ?>
                    <br><span style="font-size:11px;color:#5A6270;">
                        <?php echo esc_html( implode( ', ', array_map( fn( $o ) => $o['option_name'] . ': ' . $o['variant_name'], $item['options'] ) ) ); ?>
                    </span>
                <?php endif; ?>
            </td>
            <td style="text-align:center;"><?php echo (int) $item['quantity']; ?></td>
            <td style="text-align:right;"><?php echo esc_html( $mailer->format_money( $line_total, $currency ) ); ?></td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<!-- Totals -->
<table class="totals-table" style="max-width:280px;margin-left:auto;">
    <?php if ( (float) ( $order['discount'] ?? 0 ) > 0 ) : ?>
    <tr>
        <td><?php esc_html_e( 'Discount', 'titancart-lite' ); ?></td>
        <td>−<?php echo esc_html( $mailer->format_money( $order['discount'], $currency ) ); ?></td>
    </tr>
    <?php endif; ?>
    <tr>
        <td><?php esc_html_e( 'Shipping', 'titancart-lite' ); ?></td>
        <td><?php echo esc_html( $mailer->format_money( $order['shipping_cost'] ?? 0, $currency ) ); ?></td>
    </tr>
    <?php if ( (float) ( $order['tax_total'] ?? 0 ) > 0 ) : ?>
    <tr>
        <td><?php esc_html_e( 'Tax', 'titancart-lite' ); ?></td>
        <td><?php echo esc_html( $mailer->format_money( $order['tax_total'], $currency ) ); ?></td>
    </tr>
    <?php endif; ?>
    <?php if ( (float) ( $order['tip_total'] ?? 0 ) > 0 ) : ?>
    <tr>
        <td><?php echo esc_html( apply_filters( 'titancart_tip_line_label', __( 'Tip', 'titancart-lite' ), $order ) ); ?></td>
        <td><?php echo esc_html( $mailer->format_money( $order['tip_total'], $currency ) ); ?></td>
    </tr>
    <?php endif; ?>
    <tr class="totals-total">
        <td><strong><?php esc_html_e( 'Total', 'titancart-lite' ); ?></strong></td>
        <td><strong><?php echo esc_html( $mailer->format_money( $order['total'], $currency ) ); ?></strong></td>
    </tr>
</table>

<?php
// ── Phase 4: Inline downloads block (sync gateway path only) ───────────────
// When this customer's order included downloadable products AND their gateway
// is synchronous (Authorize.net / Square / COD-after-flag-as-paid), the
// Mailer stash will have been populated before this template renders and the
// $download_groups variable will be set with hydrated file/url metadata.
//
// Async gateway customers (PayPal / Stripe webhook) won't have $download_groups
// here — they receive a separate downloads-ready.php email when their
// payment captures.
if ( $has_downloads ) {
    \TitanCart\Storefront\TemplateLoader::get_template(
        'emails/parts/downloads-block.php',
        [ 'download_groups' => $download_groups ],
        false
    );
}
?>

<hr class="divider">

<!-- Addresses -->
<h2><?php esc_html_e( 'Shipping Details', 'titancart-lite' ); ?></h2>

<div class="address-grid">
    <div class="address-block">
        <strong><?php esc_html_e( 'Billing', 'titancart-lite' ); ?></strong><br>
        <?php echo nl2br( esc_html( titancart_format_address( $order, 'billing' ) ) ); ?>
    </div>
    <div class="address-block">
        <strong><?php esc_html_e( 'Shipping', 'titancart-lite' ); ?></strong><br>
        <?php echo nl2br( esc_html( titancart_format_address( $order, 'shipping' ) ) ); ?>
    </div>
</div>

<?php if ( ! empty( $order['customer_note'] ) ) : ?>
<hr class="divider">
<p style="background:#F6F8FB;padding:12px;border-radius:8px;font-size:13px;">
    <strong><?php esc_html_e( 'Your note:', 'titancart-lite' ); ?></strong><br>
    <?php echo esc_html( $order['customer_note'] ); ?>
</p>
<?php endif; ?>

<hr class="divider">
<p style="color:#5A6270;font-size:12px;text-align:center;">
    <?php
    printf(
        /* translators: %s: site name */
        esc_html__( 'Questions? Reply to this email or contact %s.', 'titancart-lite' ),
        esc_html( $site_name )
    );
    ?>
</p>
