<?php
/**
 * TitanCart — Shopping Cart page (ShopNest layout).
 *
 * Override: {theme}/titancart/cart/cart.php
 *
 * Two-column layout:
 *   Left  — Cart items list with qty spinners and remove buttons
 *   Right — Order Summary card + Promo Code card
 *
 * All AJAX mutations handled by assets/js/cart.js (loaded globally).
 *
 * @var array $cart  Fully hydrated cart from CartManager::get_cart().
 * @package TitanCart
 */

defined( 'ABSPATH' ) || exit;

$items      = $cart['items']       ?? [];
$totals     = $cart['totals']      ?? [];
$item_count = $cart['item_count']  ?? 0;
$currency   = apply_filters( 'titancart_currency_symbol', '$' );
$shop_url   = apply_filters( 'titancart_shop_url', titancart_shop_url() );
$show_shipping_estimate = \TitanCart\Services\SettingsService::bool( 'checkout', 'estimate_shipping_on_cart', true );
$show_tax_on_cart       = \TitanCart\Services\SettingsService::bool( 'appearance', 'show_tax_on_cart', false );
$qty_changer            = \TitanCart\Services\SettingsService::bool( 'appearance', 'use_qty_value_changer', true );
$qty_dropdown_count     = \TitanCart\Services\SettingsService::int( 'checkout', 'number_available_quantities', 0 );

if ( ! function_exists( 'get_header' ) ) return;
get_header();

$_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';
          // Dark-mode banner image: append --tc-banner-img-dark CSS variable
          // and add the dark-image class. Pairs with the rule in shop.css
          // that swaps background-image when [data-theme="dark"] is active.
          // Mirrors archive.php / single.php / dashboard.php exactly so all
          // pages share the same dark-banner customizer setting
          // (tct_shop_banner_image_dark). Pattern #97 from S150 R3.
          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">Shopping Cart</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">Shopping Cart</span>
    </nav>
  </div>
</section>
<?php endif; ?>

<div class="tc-cartpage" id="tc-cart">

  <?php if ( ! $_tc_is_theme ) : ?>
  <!-- ═══ Page Header (Plugin) ═══ -->
  <section class="tc-cartpage__header">
    <div class="tc-container">
      <h1 class="tc-cartpage__title">Shopping Cart</h1>
      <nav class="tc-breadcrumb tc-breadcrumb--centered">
        <a href="<?php echo esc_url( home_url( '/' ) ); ?>">Home</a>
        <span class="tc-breadcrumb__sep"><svg width="7" height="12" viewBox="0 0 7 12" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M1 1l5 5-5 5"/></svg></span>
        <span class="tc-breadcrumb__current">Shopping Cart</span>
      </nav>
    </div>
  </section>
  <?php endif; ?>

  <!-- ═══ Cart Content ═══ -->
  <section class="tc-cartpage__content">
    <div class="tc-container">

      <?php if ( empty( $items ) ) : ?>

        <!-- Empty Cart -->
        <div class="tc-cartpage__empty">
          <svg width="64" height="64" viewBox="0 0 64 64" fill="none" stroke="#ccc" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
            <path d="M8 8h6l3.6 24a4 4 0 004 3.5h19.4a4 4 0 004-2.9L49 18.7H16"/>
            <circle cx="22.7" cy="50.7" r="3.3"/><circle cx="44" cy="50.7" r="3.3"/>
          </svg>
          <h2>Your cart is empty</h2>
          <p>Looks like you haven't added anything yet.</p>
          <a href="<?php echo esc_url( $shop_url ); ?>" class="tc-cartpage__empty-btn">Continue Shopping</a>
        </div>

      <?php else : ?>

        <?php
        // Exchange credit banner — shown when customer was redirected from an RMA return request.
        $_ex_credit    = (float) ( $totals['exchange_credit']   ?? 0 );
        $_ex_return_id = (int)   ( $totals['exchange_return_id'] ?? 0 );
        if ( $_ex_credit > 0 && $_ex_return_id > 0 ) :
        ?>
        <div class="tc-cartpage__exchange-banner" style="background:#F0F9FF;border:1px solid #BAE6FD;border-left:4px solid #0284C7;border-radius:8px;padding:14px 18px;margin-bottom:20px;display:flex;align-items:center;gap:14px;">
          <i class="bi bi-arrow-left-right" style="font-size:24px;color:#0284C7;"></i>
          <div style="flex:1;">
            <strong style="display:block;color:#0C4A6E;">Completing exchange for Return #<?php echo (int) $_ex_return_id; ?></strong>
            <span style="color:#075985;font-size:14px;">A credit of <?php echo esc_html( $currency . number_format( $_ex_credit, 2 ) ); ?> has been applied — you only pay the difference for your replacement items.</span>
          </div>
        </div>
        <?php endif; ?>

        <div class="tc-cartpage__grid">

          <!-- ── LEFT COLUMN: Items ── -->
          <div class="tc-cartpage__items">

            <div class="tc-cartpage__items-header">
              <span class="tc-cartpage__items-count"><?php echo esc_html( $item_count ); ?> item<?php echo $item_count !== 1 ? 's' : ''; ?> in your cart</span>
              <a href="<?php echo esc_url( $shop_url ); ?>" class="tc-cartpage__continue-link">← Continue shopping</a>
            </div>

            <div class="tc-cartpage__list">
              <?php foreach ( $items as $item ) :
                $item_id     = (int) $item['item_id'];
                $product_id  = (int) $item['product_id'];
                $name        = $item['name']            ?? '';
                $sku         = $item['sku']             ?? '';
                $slug        = $item['slug']            ?? '';
                $image       = $item['image']           ?? null;
                $quantity    = (int) $item['quantity'];
                $eff_price   = (float) $item['effective_price'];
                $line_total  = (float) $item['line_total'];
                $options     = $item['options']         ?? [];
                $max_qty     = $item['max_quantity']    ?? '';
                $product_url = titancart_product_url( $slug );

                // Detect gift card items.
                $_gc_meta = $item['meta'] ?? null;
                if ( is_string( $_gc_meta ) ) { $_gc_meta = json_decode( $_gc_meta, true ); }
                $_is_gc = is_array( $_gc_meta ) && ( $_gc_meta['item_type'] ?? '' ) === 'gift_card';
              ?>

                <div class="tc-cartpage__item" data-item-id="<?php echo esc_attr( $item_id ); ?>">

                  <!-- Thumbnail -->
                  <?php if ( $_is_gc ) : ?>
                    <div class="tc-cartpage__item-img-link" style="display:flex;align-items:center;justify-content:center;width:80px;height:80px;background:linear-gradient(135deg,#2563EB,#3B82F6);border-radius:10px;color:#fff;font-size:32px;flex-shrink:0;text-decoration:none;">🎁</div>
                  <?php else : ?>
                  <a href="<?php echo esc_url( $product_url ); ?>" class="tc-cartpage__item-img-link">
                    <?php if ( $image && ! empty( $image['thumb'] ) ) : ?>
                      <img src="<?php echo esc_url( $image['thumb'] ); ?>"
                           alt="<?php echo esc_attr( $image['alt'] ?? $name ); ?>"
                           class="tc-cartpage__item-img" loading="lazy" />
                    <?php else : ?>
                      <div class="tc-cartpage__item-img tc-cartpage__item-img--placeholder">
                        <i class="bi bi-image" style="font-size:1.5rem;color:#ccc"></i>
                      </div>
                    <?php endif; ?>
                  </a>
                  <?php endif; ?>

                  <!-- Info: name, options, sku, unit price, remove link -->
                  <div class="tc-cartpage__item-info">
                    <?php if ( $_is_gc ) : ?>
                      <span class="tc-cartpage__item-name" style="font-weight:600;">
                        <?php echo esc_html( $name ); ?>
                      </span>
                      <?php if ( ! empty( $_gc_meta['recipient_name'] ) || ! empty( $_gc_meta['recipient_email'] ) ) : ?>
                        <span class="tc-cartpage__item-unit-price" style="color:#737373;font-size:13px;">
                          <?php
                          /* translators: %s: gift card recipient name or email address. */
                          printf( esc_html__( 'To: %s', 'titancart-lite' ), esc_html( $_gc_meta['recipient_name'] ?: $_gc_meta['recipient_email'] ) );
                          if ( ! empty( $_gc_meta['recipient_name'] ) && ! empty( $_gc_meta['recipient_email'] ) ) {
                              echo ' &lt;' . esc_html( $_gc_meta['recipient_email'] ) . '&gt;';
                          }
                          ?>
                        </span>
                      <?php endif; ?>
                      <?php if ( ! empty( $_gc_meta['sender_name'] ) ) : ?>
                        <span style="display:block;color:#737373;font-size:12px;">
                          <?php
                          /* translators: %s: gift card sender name. */
                          printf( esc_html__( 'From: %s', 'titancart-lite' ), esc_html( $_gc_meta['sender_name'] ) );
                          ?>
                        </span>
                      <?php endif; ?>
                      <?php if ( ! empty( $_gc_meta['message'] ) ) : ?>
                        <span style="display:block;color:#999;font-size:11px;font-style:italic;margin-top:2px;max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
                          "<?php echo esc_html( $_gc_meta['message'] ); ?>"
                        </span>
                      <?php endif; ?>
                    <?php else : ?>
                    <a href="<?php echo esc_url( $product_url ); ?>" class="tc-cartpage__item-name">
                      <?php echo esc_html( $name ); ?>
                    </a>
                    <span class="tc-cartpage__item-unit-price"><?php echo esc_html( $currency . number_format( $eff_price, 2 ) ); ?></span>
                    <?php if ( ! empty( $options ) ) : ?>
                      <div class="tc-cartpage__item-opts">
                        <?php foreach ( $options as $opt ) : ?>
                          <span class="tc-cartpage__item-opt">
                            <?php echo esc_html( ( $opt['option_name'] ?? '' ) . ': ' . ( $opt['variant_name'] ?? '' ) ); ?>
                          </span>
                        <?php endforeach; ?>
                      </div>
                    <?php endif; ?>
                    <?php if ( $sku ) : ?>
                      <span class="tc-cartpage__item-sku"><?php echo esc_html( $sku ); ?></span>
                    <?php endif; ?>
                    <?php endif; ?>
                    <button type="button"
                            class="tc-cartpage__item-remove-link tc-cart__remove-btn"
                            data-item-id="<?php echo esc_attr( $item_id ); ?>">
                      <i class="bi bi-trash3"></i> Remove
                    </button>
                  </div>

                  <!-- Quantity -->
                  <div class="tc-cartpage__item-qty">
                    <?php if ( $_is_gc ) : ?>
                      <span style="display:inline-block;text-align:center;width:100%;font-size:14px;padding:8px 0;">1</span>
                    <?php elseif ( $qty_dropdown_count > 0 ) :
                      $_cq_min  = max( 1, (int) ( $item['min_quantity'] ?? 1 ) );
                      $_cq_max  = (int) ( $item['max_quantity'] ?? 0 );
                      $_cq_step = max( 1, (int) ( $item['quantity_step'] ?? 1 ) );
                      $_cq_eff_max = ( $_cq_max > 0 ) ? $_cq_max : ( $_cq_min + ( $qty_dropdown_count - 1 ) * $_cq_step );
                      $_cq_opts = [];
                      for ( $_cq = $_cq_min; $_cq <= $_cq_eff_max && count( $_cq_opts ) < $qty_dropdown_count; $_cq += $_cq_step ) {
                          $_cq_opts[] = $_cq;
                      }
                    ?>
                    <select class="tc-cartpage__qty-select tc-qty-spinner" data-item-id="<?php echo esc_attr( $item_id ); ?>">
                      <?php foreach ( $_cq_opts as $_cqv ) : ?>
                        <option value="<?php echo esc_attr( $_cqv ); ?>"<?php selected( $_cqv, $quantity ); ?>><?php echo esc_html( $_cqv ); ?></option>
                      <?php endforeach; ?>
                    </select>
                    <?php else : ?>
                    <div class="tc-cartpage__qty-wrap">
                      <?php if ( $qty_changer ) : ?>
                      <button type="button" class="tc-cartpage__qty-btn tc-cartpage__qty-minus" data-item-id="<?php echo esc_attr( $item_id ); ?>">−</button>
                      <?php endif; ?>
                      <input type="number"
                             class="tc-cartpage__qty-input tc-qty-spinner"
                             value="<?php echo esc_attr( $quantity ); ?>"
                             min="1"
                             <?php if ( $max_qty ) : ?>max="<?php echo esc_attr( $max_qty ); ?>"<?php endif; ?>
                             data-item-id="<?php echo esc_attr( $item_id ); ?>" />
                      <?php if ( $qty_changer ) : ?>
                      <button type="button" class="tc-cartpage__qty-btn tc-cartpage__qty-plus" data-item-id="<?php echo esc_attr( $item_id ); ?>">+</button>
                      <?php endif; ?>
                    </div>
                    <?php endif; ?>
                  </div>

                  <!-- Line total -->
                  <div class="tc-cartpage__item-total">
                    <span class="tc-cart__line-total" data-item-id="<?php echo esc_attr( $item_id ); ?>">
                      <?php echo esc_html( $currency . number_format( $line_total, 2 ) ); ?>
                    </span>
                  </div>

                </div>

              <?php endforeach; ?>
            </div>

          </div>

          <!-- ── RIGHT COLUMN: Summary ── -->
          <div class="tc-cartpage__sidebar">

            <!-- Order Summary -->
            <div class="tc-cartpage__summary-card">
              <h3 class="tc-cartpage__summary-title">Order Summary</h3>

              <div class="tc-cartpage__summary-rows">
                <div class="tc-cartpage__summary-row">
                  <span>Subtotal</span>
                  <span id="tc-totals-subtotal"><?php echo esc_html( $currency . number_format( (float) ( $totals['subtotal'] ?? 0 ), 2 ) ); ?></span>
                </div>

                <?php if ( ( $totals['coupon_discount'] ?? 0 ) > 0 ) : ?>
                  <div class="tc-cartpage__summary-row tc-cartpage__summary-row--discount">
                    <span>Discount <?php if ( $cart['coupon_code'] ?? '' ) echo '<small>(' . esc_html( $cart['coupon_code'] ) . ')</small>'; ?></span>
                    <span class="tc-cartpage__discount" id="tc-totals-discount">−<?php echo esc_html( $currency . number_format( (float) $totals['coupon_discount'], 2 ) ); ?></span>
                  </div>
                <?php endif; ?>

                <?php if ( ( $totals['exchange_credit'] ?? 0 ) > 0 ) : ?>
                  <div class="tc-cartpage__summary-row tc-cartpage__summary-row--discount">
                    <span>Return credit <small>(Return #<?php echo (int) ( $totals['exchange_return_id'] ?? 0 ); ?>)</small></span>
                    <span class="tc-cartpage__discount" id="tc-totals-exchange-credit">Applied above</span>
                  </div>
                <?php endif; ?>

                <?php if ( $show_shipping_estimate ) : ?>
                <div class="tc-cartpage__summary-row">
                  <span>Shipping</span>
                  <span id="tc-totals-shipping"><em>Calculated at checkout</em></span>
                </div>
                <?php endif; ?>

                <?php if ( $show_tax_on_cart || ( $totals['tax_total'] ?? 0 ) > 0 ) : ?>
                  <div class="tc-cartpage__summary-row">
                    <span>Tax</span>
                    <span id="tc-totals-tax"><?php echo esc_html( $currency . number_format( (float) ( $totals['tax_total'] ?? 0 ), 2 ) ); ?></span>
                  </div>
                <?php endif; ?>
              </div>

              <div class="tc-cartpage__summary-total">
                <span>Total</span>
                <strong id="tc-totals-grand"><?php echo esc_html( $currency . number_format( (float) ( $totals['total'] ?? 0 ), 2 ) ); ?></strong>
              </div>

              <a href="<?php echo esc_url( apply_filters( 'titancart_checkout_url', home_url( '/checkout/' ) ) ); ?>"
                 class="tc-cartpage__checkout-btn">
                Proceed to Checkout
              </a>
            </div>

            <!-- Promo Code -->
            <div class="tc-cartpage__promo-card">
              <p class="tc-cartpage__promo-label"><i class="bi bi-percent"></i> Apply promo code</p>
              <div class="tc-cartpage__promo-row">
                <input type="text"
                       id="tc-coupon-code"
                       class="tc-cartpage__promo-input"
                       value="<?php echo esc_attr( $cart['coupon_code'] ?? '' ); ?>"
                       placeholder="Enter promo code" />
                <?php if ( ! empty( $cart['coupon_code'] ) ) : ?>
                  <button type="button" class="tc-cartpage__promo-btn tc-remove-coupon-btn">Remove</button>
                <?php else : ?>
                  <button type="button" class="tc-cartpage__promo-btn tc-apply-coupon-btn">Apply</button>
                <?php endif; ?>
              </div>
              <span class="tc-cart__msg" id="tc-coupon-msg" aria-live="polite" style="display:none"></span>
            </div>

            <!-- Order Notes -->
            <div class="tc-cartpage__notes-card">
              <label for="tc-order-notes" class="tc-cartpage__notes-label">Order notes <small>(optional)</small></label>
              <textarea id="tc-order-notes"
                        class="tc-cartpage__notes-input"
                        rows="3"
                        placeholder="Special instructions for your order…"><?php echo esc_textarea( $cart['notes'] ?? '' ); ?></textarea>
            </div>

          </div>

        </div>

      <?php endif; ?>

    </div>
  </section>

</div>

<?php
// WP.org R2: inline JS is built as a PHP string (no output buffering, no
// markup literals) and attached via wp_add_inline_script (stub handle, footer).
$tc_cart_inline_js = <<<'JS'
/* Inline: qty +/− buttons (the rest is handled by cart.js) */
document.addEventListener('click', function(e) {
    var btn = e.target.closest('.tc-cartpage__qty-minus, .tc-cartpage__qty-plus');
    if (!btn) return;
    var id    = btn.dataset.itemId;
    var input = document.querySelector('.tc-qty-spinner[data-item-id="' + id + '"]');
    if (!input) return;
    var val = parseInt(input.value, 10) || 1;
    var min = parseInt(input.min, 10) || 1;
    var max = input.max ? parseInt(input.max, 10) : 9999;
    if (btn.classList.contains('tc-cartpage__qty-minus')) val = Math.max(min, val - 1);
    else val = Math.min(max, val + 1);
    input.value = val;
    input.dispatchEvent(new Event('change', { bubbles: true }));
});
JS;
wp_register_script( 'titancart-cart-inline', false, array(), TITANCART_VERSION, true );
wp_enqueue_script( 'titancart-cart-inline' );
wp_add_inline_script( 'titancart-cart-inline', $tc_cart_inline_js );
?>

<?php get_footer(); ?>
