<?php
// ============================================================
//  MediCore — Customer Portal Layout Footer
//  File: includes/shop_footer.php
//  Pairs with includes/shop_header.php — always include at the
//  bottom of every shop/*.php page.
//
//  Cart state (localStorage) lives HERE so it's shared/consistent
//  across every shop page (badge count, reorder-from-history, etc).
//  The actual cart VIEW is a sticky sidebar on shop/index.php itself
//  (see renderCartSidebar() there) — this file calls it generically
//  via a typeof check whenever the cart changes, so shop_footer.php
//  doesn't need to know that page exists.
// ============================================================
?>
</div><!-- /shop-wrap -->

<div id="mroot"></div>

<script>
// ── Modal helpers (same shape as the staff app's) ────────────
// Not closeable by clicking the overlay — only Esc, the × button, or
// a Cancel/Save button inside the modal itself (matches the staff
// app; see includes/footer.php for the full rationale).
function showModal(html, title, size) {
  document.getElementById('mroot').innerHTML =
    `<div class="moverlay">
       <div class="mbox${size==='lg'?' mbox-lg':size==='xl'?' mbox-xl':''}">
         <div class="mtitle">${title}<button class="mclose" onclick="closeModal()">×</button></div>
         ${html}
       </div>
     </div>`;
}
function closeModal() { document.getElementById('mroot').innerHTML = ''; }

document.addEventListener('keydown', (e) => {
  if (e.key !== 'Escape') return;
  const root = document.getElementById('mroot');
  if (root && root.innerHTML.trim() !== '') closeModal();
});

function esc(s) {
  return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;')
                      .replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
function fmt(n, cur = '') {
  return cur + parseFloat(n||0).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

// ── AJAX helper — POST JSON to api/ endpoints ────────────────
async function apiPost(url, data) {
  let r;
  try {
    r = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
      body: JSON.stringify(data)
    });
  } catch (netErr) {
    return { success: false, error: 'Network error — could not reach server.' };
  }
  if (r.status === 401) {
    return { success: false, error: 'Please log in to continue.', session_expired: true };
  }
  if (!r.ok) {
    return { success: false, error: 'Server error (HTTP ' + r.status + ').' };
  }
  const text = await r.text();
  try {
    const v = JSON.parse(text);
    if (v && typeof v === 'object') return v;
  } catch {}
  const firstBrace = text.search(/[{[]/);
  if (firstBrace >= 0) {
    try {
      const v = JSON.parse(text.slice(firstBrace));
      if (v && typeof v === 'object') return v;
    } catch {}
  }
  return { success: false, error: 'Server returned an unexpected response.' };
}

// ── Cart — shared across every shop page via localStorage ────
// Shape: { [product_id]: { name, form, price, qty } }
const CART_KEY = 'medicore_shop_cart';

function getCart() {
  try { return JSON.parse(localStorage.getItem(CART_KEY) || '{}'); } catch { return {}; }
}
function setCart(cart) {
  localStorage.setItem(CART_KEY, JSON.stringify(cart));
  updateCartBadge();
  // shop/index.php defines renderCartSidebar() when its sticky cart
  // panel is on the page — call it if present, no-op elsewhere.
  if (typeof renderCartSidebar === 'function') renderCartSidebar();
}
function addToCart(p) {
  const cart = getCart();
  const id = String(p.id);
  if (cart[id]) cart[id].qty += 1;
  else cart[id] = { name: p.name, form: p.form || '', price: parseFloat(p.sale_price) || 0, qty: 1 };
  setCart(cart);
}
function changeQty(id, delta) {
  const cart = getCart();
  if (!cart[id]) return;
  cart[id].qty = Math.max(0, cart[id].qty + delta);
  if (cart[id].qty === 0) delete cart[id];
  setCart(cart);
}
function cartItemCount() { return Object.keys(getCart()).length; }

// Badge shows the number of DISTINCT products in the cart, not the
// total piece count across them (2 products × 10pcs each = "2", not "20").
function updateCartBadge() {
  const badge = document.getElementById('topbar-cart-count');
  if (!badge) return;
  const count = cartItemCount();
  if (count > 0) { badge.textContent = count; badge.style.display = ''; }
  else badge.style.display = 'none';
}
document.addEventListener('DOMContentLoaded', updateCartBadge);

// ── Logout ────────────────────────────────────────────────────
async function shopLogout() {
  await apiPost(window.SHOP_API + 'customer-auth.php', { action: 'logout' });
  window.location.href = window.SHOP_BASE + 'shop/login.php';
}
</script>
</body>
</html>
