<?php
/**
 * Order Received (Thank You) Page Template.
 *
 * Override: {theme}/titancart/checkout/order-received.php
 *
 * @var array $order  Order row from tc_orders (with resolved 'status' handle).
 * @var array $items  Order items from tc_order_items (with options_summary).
 * @package TitanCart
 */

defined( 'ABSPATH' ) || exit;

get_header();

/* ── Fallback: if template data is empty, try fetching directly ──── */
if ( empty( $order ) || empty( $order['id'] ) ) {
    $order_number = get_query_var( 'tc_order_received' );
    if ( ! $order_number ) {
        // Try extracting from URL path.
        $path = trim( (string) wp_parse_url( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ?? '' ) ), PHP_URL_PATH ), '/' );
        if ( preg_match( '/order-received\/([A-Za-z0-9\-]+)/', $path, $m ) ) {
            $order_number = $m[1];
        }
    }
    if ( $order_number ) {
        $db    = titancart_db();
        $order = $db->getRow(
            "SELECT * FROM {$db->table('orders')} WHERE order_number = ?s LIMIT 1",
            strtoupper( $order_number )
        );
        if ( $order ) {
            $items = $db->getArray(
                "SELECT oi.*, GROUP_CONCAT(
                    CONCAT(oio.option_name, ': ', oio.variant_name)
                    ORDER BY oio.id SEPARATOR ', '
                 ) AS options_summary
                 FROM {$db->table('order_items')} oi
                 LEFT JOIN {$db->table('order_item_options')} oio ON oio.order_item_id = oi.id
                 WHERE oi.order_id = ?i
                 GROUP BY oi.id
                 ORDER BY oi.id ASC",
                (int) $order['id']
            );

            // Resolve status.
            if ( ! empty( $order['status_id'] ) ) {
                $lang  = function_exists( 'titancart_get_current_language' ) ? titancart_get_current_language() : 'en';
                $srow  = $db->getRow(
                    "SELECT os.handle, COALESCE(ost.name, os.handle) AS status_name
                     FROM {$db->table('order_statuses')} os
                     LEFT JOIN {$db->table('order_status_translations')} ost
                       ON ost.status_id = os.id AND ost.language_code = ?s
                     WHERE os.id = ?i LIMIT 1",
                    $lang,
                    (int) $order['status_id']
                );
                $order['status']      = $srow['handle']      ?? 'pending';
                $order['status_name'] = $srow['status_name'] ?? ucfirst( $order['status'] );
            }
        }
    }
}

/* ── Access check ─────────────────────────────────────────────────────
 * order_number is enumerable (TC-YYYYMMDD-NNNN), so anyone who knows the
 * format could iterate guesses and read PII off any order. Three valid
 * access paths:
 *   1. WP admin (manage_options)
 *   2. Authenticated WP user whose tc_customers.id matches the order
 *   3. URL query ?key=... matches the row's order_key (constant-time)
 *
 * On failure we null out $order — the "still no order" guard below renders
 * the same UX as a genuinely-missing order so the page can't confirm
 * existence to an attacker. Old orders that predate migration 39 will have
 * their order_key backfilled when the migration runs; this gate becomes
 * effective the first time the migration fires.
 */
if ( ! empty( $order ) && ! empty( $order['id'] ) ) {
    $tc_or_is_admin = current_user_can( 'manage_options' );

    $tc_or_is_owner = false;
    if ( ! $tc_or_is_admin && is_user_logged_in() ) {
        if ( class_exists( '\TitanCart\Modules\Accounts\CustomerRepository' ) ) {
            $tc_or_repo = new \TitanCart\Modules\Accounts\CustomerRepository();
            $tc_or_row  = $tc_or_repo->find_by_wp_user( get_current_user_id() );
            if ( $tc_or_row && (int) $tc_or_row['id'] === (int) $order['customer_id'] ) {
                $tc_or_is_owner = true;
            }
        }
    }

    $tc_or_supplied_key = '';
    if ( isset( $_GET['key'] ) ) {
        // 32-char hex; constrain to safe charset before comparing. WP.org R2 item 5:
        // unslash+sanitize at the boundary, then the hex whitelist strip on top.
        $tc_or_supplied_key = preg_replace( '/[^a-f0-9A-F]/', '', sanitize_text_field( wp_unslash( (string) $_GET['key'] ) ) );
    }
    $tc_or_row_key = (string) ( $order['order_key'] ?? '' );
    $tc_or_key_ok  = ( $tc_or_supplied_key !== ''
                      && $tc_or_row_key !== ''
                      && hash_equals( $tc_or_row_key, $tc_or_supplied_key ) );

    if ( ! $tc_or_is_admin && ! $tc_or_is_owner && ! $tc_or_key_ok ) {
        // Indistinguishable from a missing order — don't leak existence.
        $order = null;
        $items = [];
    }
}

/* ── Guard: still no order ────────────────────────────────────────── */
if ( empty( $order ) || empty( $order['id'] ) ) {
    echo '<div class="tc-order-received"><div class="tc-order-received__banner">';
    echo '<div class="tc-order-received__check" aria-hidden="true" style="background:#fef2f2;color:#dc2626;border-color:#fecaca">!</div>';
    echo '<h1 class="tc-order-received__title">' . esc_html__( 'Order not found', 'titancart-lite' ) . '</h1>';
    echo '<p class="tc-order-received__subtitle">' . esc_html__( 'We could not locate this order. It may have been removed or the link is incorrect.', 'titancart-lite' ) . '</p>';
    echo '<div class="tc-order-received__actions" style="margin-top:24px"><a href="' . esc_url( titancart_shop_url() ) . '" class="tc-btn tc-btn--primary">' . esc_html__( 'Continue Shopping', 'titancart-lite' ) . '</a></div>';
    echo '</div></div>';
    get_footer();
    return;
}

/* ── Data setup ───────────────────────────────────────────────────── */
$currency = apply_filters( 'titancart_currency_symbol', '$' );
$status   = $order['status'] ?? 'pending';

$status_labels = [
    'pending'    => __( 'Pending payment', 'titancart-lite' ),
    'processing' => __( 'Processing', 'titancart-lite' ),
    'on_hold'    => __( 'On hold', 'titancart-lite' ),
    'paid'       => __( 'Paid', 'titancart-lite' ),
    'completed'  => __( 'Completed', 'titancart-lite' ),
    'shipped'    => __( 'Shipped', 'titancart-lite' ),
    'cancelled'  => __( 'Cancelled', 'titancart-lite' ),
    'refunded'   => __( 'Refunded', 'titancart-lite' ),
    'failed'     => __( 'Failed', 'titancart-lite' ),
];

$status_colors = [
    'pending'    => [ '#fff7ed', '#f97316', '#fed7aa' ],
    'processing' => [ '#eff6ff', '#2563eb', '#bfdbfe' ],
    'paid'       => [ '#f0fdf4', '#16a34a', '#bbf7d0' ],
    'on_hold'    => [ '#fff7ed', '#d97706', '#fed7aa' ],
    'completed'  => [ '#f0fdf4', '#16a34a', '#bbf7d0' ],
    'shipped'    => [ '#eff6ff', '#2563eb', '#bfdbfe' ],
    'cancelled'  => [ '#fef2f2', '#dc2626', '#fecaca' ],
    'refunded'   => [ '#fef2f2', '#dc2626', '#fecaca' ],
    'failed'     => [ '#fef2f2', '#dc2626', '#fecaca' ],
];

$sc = $status_colors[ $status ] ?? [ '#f5f5f5', '#737373', '#e5e5e5' ];

$_tc_is_theme = defined( 'TITANCART_THEME_ACTIVE' );
?>

<?php if ( $_tc_is_theme ) :
  $_b_cls = 'tc-shop__banner tc-shop__banner--theme';
  $_b_sty = ''; $_b_ov = '';
  $_b_img      = get_theme_mod( 'tct_shop_banner_image' );
  $_b_img_dark = get_theme_mod( 'tct_shop_banner_image_dark' );
  if ( $_b_img ) {
      $_b_url      = wp_get_attachment_image_url( (int) $_b_img, 'full' );
      $_b_url_dark = $_b_img_dark ? wp_get_attachment_image_url( (int) $_b_img_dark, 'full' ) : '';
      if ( $_b_url ) {
          $_b_pos = get_theme_mod( 'tct_shop_banner_position', 'center center' );
          $_b_ht  = get_theme_mod( 'tct_shop_banner_height', 280 );
          $_b_ov  = get_theme_mod( 'tct_shop_banner_overlay', 'rgba(0,0,0,0.45)' );
          $_b_sty = sprintf( 'background-image:url(%s);background-size:cover;background-position:%s;height:%dpx;',
              esc_url( $_b_url ), esc_attr( $_b_pos ), (int) $_b_ht );
          $_b_cls .= ' tc-shop__banner--has-image';
          // Pattern #97 — dark-mode banner image variable + class.
          if ( $_b_url_dark ) {
              $_b_sty .= sprintf( '--tc-banner-img-dark:url(%s);', esc_url( $_b_url_dark ) );
              $_b_cls .= ' tc-shop__banner--has-dark-image';
          }
      }
  }
?>
<!-- ═══ Full-Width Page Header Banner (Theme) ═══ -->
<section class="<?php echo esc_attr( $_b_cls ); ?>" style="<?php echo esc_attr( $_b_sty ); ?>">
  <?php if ( $_b_ov ) : ?><div class="tc-shop__banner-overlay" style="background:<?php echo esc_attr( $_b_ov ); ?>;position:absolute;top:0;left:0;right:0;bottom:0;"></div><?php endif; ?>
  <div class="tc-shop__banner-inner">
    <h2 class="tc-shop__banner-title"><?php esc_html_e( 'Order Received', 'titancart-lite' ); ?></h2>
    <nav class="tc-breadcrumb tc-breadcrumb--centered">
      <a href="<?php echo esc_url( home_url( '/' ) ); ?>">Home</a>
      <i class="bi bi-chevron-right"></i>
      <span class="tc-breadcrumb__current"><?php esc_html_e( 'Order Received', 'titancart-lite' ); ?></span>
    </nav>
  </div>
</section>
<?php endif; ?>

<div class="tc-order-received">

    <!-- ── Success Banner ──────────────────────────────────────────────── -->
    <div class="tc-order-received__banner">
        <div class="tc-order-received__check" aria-hidden="true">
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#16a34a" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>
        </div>
        <h1 class="tc-order-received__title">
            <?php esc_html_e( 'Thank you for your order!', 'titancart-lite' ); ?>
        </h1>
        <p class="tc-order-received__subtitle">
            <?php esc_html_e( 'Your order has been received and is being processed.', 'titancart-lite' ); ?>
        </p>
    </div>

    <?php
    /**
     * Gateway-specific post-checkout content slot.
     *
     * Offline gateways (Bank Transfer, Check) hook here to render their
     * payment instructions (account details, mailing address). Online
     * gateways and COD emit nothing. Wired in PaymentsModule (S210).
     */
    do_action( 'titancart_order_received_payment_section', $order );
    ?>

    <!-- ── Details Grid ────────────────────────────────────────────────── -->
    <div class="tc-order-received__details-grid">
        <div class="tc-order-received__detail">
            <span class="tc-order-received__detail-label"><?php esc_html_e( 'Order number', 'titancart-lite' ); ?></span>
            <strong class="tc-order-received__detail-value">
                <?php echo esc_html( $order['order_number'] ?? '—' ); ?>
            </strong>
        </div>
        <div class="tc-order-received__detail">
            <span class="tc-order-received__detail-label"><?php esc_html_e( 'Date', 'titancart-lite' ); ?></span>
            <strong class="tc-order-received__detail-value">
                <?php echo esc_html( titancart_format_date( $order['created_at'] ?? 'now' ) ); ?>
            </strong>
        </div>
        <div class="tc-order-received__detail">
            <span class="tc-order-received__detail-label"><?php esc_html_e( 'Status', 'titancart-lite' ); ?></span>
            <strong class="tc-order-received__detail-value">
                <span class="tc-order-received__status-badge"
                      style="background:<?php echo esc_attr( $sc[0] ); ?>;color:<?php echo esc_attr( $sc[1] ); ?>;border:1px solid <?php echo esc_attr( $sc[2] ); ?>;">
                    <?php echo esc_html( $status_labels[ $status ] ?? ucfirst( $status ) ); ?>
                </span>
            </strong>
        </div>
        <div class="tc-order-received__detail">
            <span class="tc-order-received__detail-label"><?php esc_html_e( 'Total', 'titancart-lite' ); ?></span>
            <strong class="tc-order-received__detail-value tc-order-received__detail-value--total">
                <?php echo esc_html( $currency . number_format( (float) ( $order['total'] ?? 0 ), 2 ) ); ?>
            </strong>
        </div>
    </div>

    <?php /* ── Order items table ─────────────────────────────────────────── */ ?>
    <?php if ( ! empty( $items ) ) : ?>
    <div class="tc-order-received__card">
        <h2 class="tc-order-received__card-title"><?php esc_html_e( 'Your order', 'titancart-lite' ); ?></h2>
        <div class="tc-order-received__items-wrap">
            <table class="tc-order-received__items-table">
                <thead>
                    <tr>
                        <th class="tc-ort__th-product"><?php esc_html_e( 'Product', 'titancart-lite' ); ?></th>
                        <th class="tc-ort__th-qty"><?php esc_html_e( 'Qty', 'titancart-lite' ); ?></th>
                        <th class="tc-ort__th-total"><?php esc_html_e( 'Total', 'titancart-lite' ); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ( $items as $item ) : ?>
                        <tr>
                            <td>
                                <span class="tc-ort__product-name"><?php echo esc_html( $item['name'] ?? '' ); ?></span>
                                <?php if ( ! empty( $item['sku'] ) ) : ?>
                                    <span class="tc-ort__sku"><?php echo esc_html( $item['sku'] ); ?></span>
                                <?php endif; ?>
                                <?php if ( ! empty( $item['options_summary'] ) ) : ?>
                                    <span class="tc-ort__options"><?php echo esc_html( $item['options_summary'] ); ?></span>
                                <?php endif; ?>
                            </td>
                            <td class="tc-ort__qty-val">&times;<?php echo esc_html( $item['quantity'] ?? 1 ); ?></td>
                            <td class="tc-ort__total-val"><?php echo esc_html( $currency . number_format( (float) ( $item['total'] ?? $item['subtotal'] ?? 0 ), 2 ) ); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <th colspan="2"><?php esc_html_e( 'Subtotal', 'titancart-lite' ); ?></th>
                        <td><?php echo esc_html( $currency . number_format( (float) ( $order['subtotal'] ?? 0 ), 2 ) ); ?></td>
                    </tr>
                    <?php if ( (float) ( $order['discount'] ?? 0 ) > 0 ) : ?>
                        <tr>
                            <th colspan="2"><?php esc_html_e( 'Discount', 'titancart-lite' ); ?></th>
                            <td>&minus;<?php echo esc_html( $currency . number_format( (float) $order['discount'], 2 ) ); ?></td>
                        </tr>
                    <?php endif; ?>
                    <?php if ( (float) ( $order['shipping_cost'] ?? 0 ) > 0 ) : ?>
                        <tr>
                            <th colspan="2"><?php esc_html_e( 'Shipping', 'titancart-lite' ); ?></th>
                            <td><?php echo esc_html( $currency . number_format( (float) $order['shipping_cost'], 2 ) ); ?></td>
                        </tr>
                    <?php endif; ?>
                    <?php if ( (float) ( $order['tax_total'] ?? 0 ) > 0 ) : ?>
                        <tr>
                            <th colspan="2"><?php esc_html_e( 'Tax', 'titancart-lite' ); ?></th>
                            <td><?php echo esc_html( $currency . number_format( (float) $order['tax_total'], 2 ) ); ?></td>
                        </tr>
                    <?php endif; ?>
                    <?php if ( (float) ( $order['tip_total'] ?? 0 ) > 0 ) : ?>
                        <tr>
                            <th colspan="2"><?php echo esc_html( apply_filters( 'titancart_tip_line_label', __( 'Tip', 'titancart-lite' ), $order ) ); ?></th>
                            <td><?php echo esc_html( $currency . number_format( (float) $order['tip_total'], 2 ) ); ?></td>
                        </tr>
                    <?php endif; ?>
                    <tr class="tc-ort__grand-total">
                        <th colspan="2"><?php esc_html_e( 'Total', 'titancart-lite' ); ?></th>
                        <td><strong><?php echo esc_html( $currency . number_format( (float) ( $order['total'] ?? 0 ), 2 ) ); ?></strong></td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <?php /* ── Addresses ──────────────────────────────────────────────────── */ ?>
    <div class="tc-order-received__addresses">
        <div class="tc-order-received__card">
            <h3 class="tc-order-received__card-title"><?php esc_html_e( 'Billing address', 'titancart-lite' ); ?></h3>
            <address class="tc-order-received__addr-body">
                <?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-order-received__addr-meta"><?php echo esc_html( $order['billing_phone'] ); ?></span><br>
                <?php endif; ?>
                <?php if ( ! empty( $order['billing_email'] ) ) : ?>
                    <span class="tc-order-received__addr-meta"><?php echo esc_html( $order['billing_email'] ); ?></span>
                <?php endif; ?>
            </address>
        </div>
        <div class="tc-order-received__card">
            <h3 class="tc-order-received__card-title"><?php esc_html_e( 'Shipping address', 'titancart-lite' ); ?></h3>
            <address class="tc-order-received__addr-body">
                <?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>
    </div>

    <?php
    // Offer guest to create an account after successful checkout.
    if ( ! is_user_logged_in()
         && \TitanCart\Services\SettingsService::bool( 'checkout', 'offer_guest_account', true )
         && ! empty( $order['billing_email'] )
         && ! email_exists( $order['billing_email'] )
    ) :
        // Bind the registration nonce to THIS specific email. The handler at
        // dashboard.php verifies the bound action — substituting a different
        // email at submit time fails the nonce check, closing the squat path
        // even if someone gets a leaked order URL+key.
        $tc_or_email_token = hash( 'sha256', strtolower( trim( (string) $order['billing_email'] ) ) );
        $tc_or_nonce_action = 'tc_register_for_' . $tc_or_email_token;
    ?>
    <div class="tc-order-received__card tc-order-received__create-account">
        <h3 class="tc-order-received__card-title"><?php esc_html_e( 'Save your details for next time', 'titancart-lite' ); ?></h3>
        <p class="tc-order-received__subtitle" style="margin:0 0 16px"><?php esc_html_e( 'Create an account with your order email to track orders, save addresses, and check out faster.', 'titancart-lite' ); ?></p>
        <form method="post" action="<?php echo esc_url( home_url( '/my-account/' ) ); ?>" class="tc-order-received__reg-form">
            <?php wp_nonce_field( $tc_or_nonce_action, 'tc_register_nonce' ); ?>
            <input type="hidden" name="tc_reg_email_token" value="<?php echo esc_attr( $tc_or_email_token ); ?>">
            <input type="hidden" name="tc_reg_email" value="<?php echo esc_attr( $order['billing_email'] ); ?>">
            <input type="hidden" name="tc_reg_first" value="<?php echo esc_attr( $order['billing_first_name'] ?? '' ); ?>">
            <input type="hidden" name="tc_reg_last" value="<?php echo esc_attr( $order['billing_last_name'] ?? '' ); ?>">
            <div class="tc-order-received__reg-fields">
                <div>
                    <label class="tc-order-received__reg-label"><?php esc_html_e( 'Choose a password', 'titancart-lite' ); ?></label>
                    <input type="password" name="tc_reg_password" required minlength="6" class="tc-order-received__reg-input">
                </div>
                <div>
                    <label class="tc-order-received__reg-label"><?php esc_html_e( 'Confirm password', 'titancart-lite' ); ?></label>
                    <input type="password" name="tc_reg_confirm" required minlength="6" class="tc-order-received__reg-input">
                </div>
                <button type="submit" class="tc-btn tc-btn--primary" style="white-space:nowrap;align-self:flex-end">
                    <?php esc_html_e( 'Create Account', 'titancart-lite' ); ?>
                </button>
            </div>
        </form>
    </div>
    <?php endif; ?>

    <div class="tc-order-received__actions">
        <a href="<?php echo esc_url( apply_filters( 'titancart_shop_url', titancart_shop_url() ) ); ?>"
           class="tc-btn tc-btn--primary">
            <?php esc_html_e( 'Continue Shopping', 'titancart-lite' ); ?>
        </a>
    </div>

</div>

<?php get_footer(); ?>
