/**
 * Ragreen - Cart & checkout logic
 * Requires config.js + jQuery loaded first.
 */

const Cart = {
  init() {
    this.load();
    $('#checkoutBtn').on('click', () => this.checkout());
  },

  load() {
    $.get(`${API_BASE}/cart/list.php`)
      .done((res) => this.render(res.data.items, res.data.summary))
      .fail(() => {
        $('#cartItems').html('<div class="empty-state"><h3>Could not load your cart</h3></div>');
      });
  },

  render(items, summary) {
    const $list = $('#cartItems');
    const $summary = $('#cartSummary');

    if (!items.length) {
      $list.html(`
        <div class="empty-state">
          <h3>Your cart is empty</h3>
          <p>Browse the marketplace to find surplus food nearby.</p>
          <a href="marketplace.html" class="btn btn-primary" style="width:auto;padding:11px 20px;text-decoration:none;display:inline-flex;margin-top:12px;">Go to marketplace</a>
        </div>
      `);
      $summary.hide();
      return;
    }

    $summary.show();
    $list.html(items.map(item => `
      <div class="cart-line" data-product-id="${item.product_id}">
        <div class="thumb">${item.thumbnail_url ? `<img src="${item.thumbnail_url}" alt="">` : `<img src="${PLACEHOLDER_IMG}" alt="Ragreen" class="no-photo">`}</div>
        <div class="info">
          <div class="name">${escapeHtml(item.name)}</div>
          <div class="unit-price">$${item.unit_price.toFixed(2)} each</div>
          ${item.unavailable ? '<div class="warn">No longer available — remove to check out</div>' : ''}
          ${item.over_stock ? `<div class="warn">Only ${item.available_stock} left in stock</div>` : ''}
        </div>
        <div class="qty-stepper">
          <button class="qty-minus" ${item.unavailable ? 'disabled' : ''}>−</button>
          <span>${item.quantity}</span>
          <button class="qty-plus" ${item.unavailable ? 'disabled' : ''}>+</button>
        </div>
        <div style="display:flex; align-items:center; gap:6px;">
          <div class="line-total">$${item.line_total.toFixed(2)}</div>
          <button class="remove-line" title="Remove">×</button>
        </div>
      </div>
    `).join(''));

    $list.find('.qty-minus').on('click', function () {
      const $line = $(this).closest('.cart-line');
      const qty = parseInt($line.find('.qty-stepper span').text(), 10) - 1;
      Cart.updateQuantity($line.data('product-id'), qty);
    });
    $list.find('.qty-plus').on('click', function () {
      const $line = $(this).closest('.cart-line');
      const qty = parseInt($line.find('.qty-stepper span').text(), 10) + 1;
      Cart.updateQuantity($line.data('product-id'), qty);
    });
    $list.find('.remove-line').on('click', function () {
      Cart.updateQuantity($(this).closest('.cart-line').data('product-id'), 0);
    });

    $('#cartSubtotal').text(`$${summary.subtotal.toFixed(2)}`);
    $('#cartCount').text(summary.item_count);
    $('#checkoutBtn').prop('disabled', summary.has_issues);
    $('#checkoutIssueNote').toggle(summary.has_issues);
  },

  updateQuantity(productId, quantity) {
    $.ajax({
      url: `${API_BASE}/cart/update.php`, method: 'POST', contentType: 'application/json',
      data: JSON.stringify({ product_id: productId, quantity }),
    }).always(() => {
      this.load();
      if (typeof updateCartBadge === 'function') updateCartBadge();
    });
  },

  checkout() {
    const $alert = $('#cartAlert');
    hideAlert($alert);
    const $btn = $('#checkoutBtn');
    setLoading($btn, true, 'Confirm order', 'Placing order…');

    $.post(`${API_BASE}/orders/checkout.php`)
      .done((res) => {
        window.location.href = `order-confirmation.html?id=${res.data.order.id}`;
      })
      .fail((xhr) => {
        showAlert($alert, xhr.responseJSON?.message || 'Checkout failed. Please review your cart.');
        this.load();
      })
      .always(() => {
        setLoading($btn, false, 'Confirm order', 'Placing order…');
      });
  },
};

/* ---------- "Add to cart" button used on product-details.html ---------- */

function bindAddToCart(productId) {
  const $btn = $('#addToCartBtn');
  const $qty = $('#addToCartQty');

  $btn.on('click', function () {
    setLoading($btn, true, 'Add to cart', 'Adding…');
    $.ajax({
      url: `${API_BASE}/cart/add.php`, method: 'POST', contentType: 'application/json',
      data: JSON.stringify({ product_id: productId, quantity: parseInt($qty.val() || 1, 10) }),
    })
      .done(() => {
        $btn.text('Added ✓');
        if (typeof updateCartBadge === 'function') updateCartBadge();
        setTimeout(() => setLoading($btn, false, 'Add to cart', 'Adding…'), 1400);
      })
      .fail((xhr) => {
        alert(xhr.responseJSON?.message || 'Could not add to cart.');
        setLoading($btn, false, 'Add to cart', 'Adding…');
      });
  });
}
