<?php
// ============================================================
//  MediCore — Customer Portal: Shop (browse products)
//  File: shop/index.php
//  Desktop: two-column layout — product grid + a sticky cart
//  sidebar docked to the right.
//  Mobile (≤900px, applied automatically by the browser based on
//  real viewport width, no user-agent sniffing): the sidebar
//  becomes a slide-up bottom sheet, opened via a floating
//  "N items · total — View Cart" bar pinned to the bottom of the
//  screen. Qty +/- buttons and Add to Cart buttons get larger
//  touch targets on mobile so ordering from a phone is comfortable.
//  Cart data/badge logic lives in includes/shop_footer.php and is
//  shared with every shop page; the sidebar VIEW itself
//  (renderCartSidebar) only exists here since this is the only
//  page that shows it.
//
//  Out-of-stock products can be added to cart and ordered when the
//  "Allow Out-of-Stock Ordering" toggle in Settings > Online
//  Ordering is ON (window.SHOP_ALLOW_BACKORDER, set in
//  includes/shop_header.php) — staff can adjust/backorder during
//  Sale Entry when approving. When OFF, the button is disabled for
//  out-of-stock items, same as before.
// ============================================================
require_once '../includes/customer_auth.php';
require_customer_login();

if (!portal_enabled()) {
    $shopPage = 'shop';
    $title    = 'Shop';
    require_once '../includes/shop_header.php';
    echo '<div class="al al-s" style="margin-top:20px">Online ordering is currently unavailable. Please check back later.</div>';
    require_once '../includes/shop_footer.php';
    exit;
}

$shopPage = 'shop';
$title    = 'Shop';
require_once '../includes/shop_header.php';

$cur = get_settings()['currency'];
?>
<style>
  .shop-grid { display:grid;grid-template-columns:minmax(0,1fr) 320px;gap:14px;align-items:start }

  /* Cart sheet drag-handle + close row — desktop hides it (sidebar is
     always visible there, no need to open/close anything) */
  .cart-sheet-handle { display:none; align-items:center; justify-content:center;
    padding:8px 0 2px; cursor:pointer; touch-action:none }
  .cart-sheet-handle .bar { width:38px;height:4px;border-radius:2px;background:var(--border) }

  /* Floating mobile summary bar — hidden on desktop, hidden on mobile
     too until JS reveals it (cart has items) */
  .mobile-cart-bar { display:none; }

  /* Backdrop behind the mobile cart sheet */
  #cart-backdrop { display:none; position:fixed; inset:0; background:rgba(20,20,20,.4);
    z-index:480; }
  #cart-backdrop.show { display:block; }

  @media (max-width: 900px) {
    .shop-grid { grid-template-columns:1fr }

    /* Product grid: comfortable 2-up cards on a phone instead of a
       single narrow column */
    #prod-grid { grid-template-columns:repeat(auto-fill,minmax(148px,1fr)) !important; gap:8px !important }

    /* Cart becomes a slide-up bottom sheet instead of a static block */
    #cart-sidebar {
      position:fixed !important; left:0; right:0; bottom:0; top:auto !important;
      z-index:490; max-height:85vh; overflow-y:auto;
      transform:translateY(100%); transition:transform .22s ease-out;
      -webkit-overflow-scrolling:touch;
    }
    #cart-sidebar.cart-open { transform:translateY(0); }
    #cart-sidebar .card { border-radius:16px 16px 0 0; padding-bottom:28px;
      box-shadow:0 -8px 28px rgba(0,0,0,.22); }
    .cart-sheet-handle { display:flex; }

    .mobile-cart-bar {
      position:fixed; left:10px; right:10px; bottom:12px; z-index:475;
      background:var(--brand); color:#fff; border-radius:var(--r);
      padding:13px 18px; align-items:center; justify-content:space-between;
      box-shadow:0 6px 22px rgba(0,0,0,.28); cursor:pointer; gap:10px;
    }
    .mobile-cart-bar:active { opacity:.92 }

    /* Bigger touch targets while shopping from a phone */
    .add-to-cart-btn { padding:12px 8px !important; font-size:13.5px !important;
      min-height:44px; }
    .cart-qty-btn { width:36px !important; height:36px !important;
      font-size:19px !important; padding:0 !important;
      display:inline-flex !important; align-items:center; justify-content:center; }
    .cart-qty-val { min-width:26px !important; font-size:14px !important; font-weight:700 }
    #cart-checkout-btn { padding:13px !important; font-size:14.5px !important; min-height:48px }
  }
</style>

<div class="shop-grid">
  <!-- ── LEFT: search + product grid ── -->
  <div style="min-width:0">
    <div style="margin-bottom:10px">
      <input type="text" id="f-search" placeholder="🔍 Search medicines, generics, brands…"
             oninput="delaySearch()"
             style="width:100%;padding:9px 12px;border:1px solid var(--border);
                    border-radius:var(--rsm);font-family:inherit;font-size:13px;outline:none">
    </div>
    <div style="display:flex;flex-wrap:wrap;gap:6px;margin-bottom:14px">
      <select id="f-category" onchange="page=1;loadProducts()"
              style="padding:6px 8px;border:1px solid var(--border);border-radius:var(--rsm);
                     font-family:inherit;font-size:12px;outline:none">
        <option value="">All Categories</option>
      </select>
      <select id="f-form" onchange="page=1;loadProducts()"
              style="padding:6px 8px;border:1px solid var(--border);border-radius:var(--rsm);
                     font-family:inherit;font-size:12px;outline:none">
        <option value="">All Forms</option>
      </select>
      <select id="f-stock" onchange="page=1;loadProducts()"
              style="padding:6px 8px;border:1px solid var(--border);border-radius:var(--rsm);
                     font-family:inherit;font-size:12px;outline:none">
        <option value="">All Stock</option>
        <option value="in">In Stock Only</option>
        <option value="out">Include Out of Stock</option>
      </select>
    </div>
    <div id="prod-grid" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:10px">
      <div class="empty-state loading-row" style="grid-column:1/-1"><span class="spin"></span>Loading…</div>
    </div>
    <div id="prod-footer" style="text-align:center;margin-top:14px"></div>
  </div>

  <!-- ── RIGHT (desktop) / BOTTOM SHEET (mobile): cart ── -->
  <div id="cart-sidebar" style="position:sticky;top:76px">
    <div class="card" style="padding:14px">
      <div class="cart-sheet-handle" onclick="toggleMobileCart(false)"><div class="bar"></div></div>
      <div style="font-weight:800;font-size:14px;margin-bottom:10px">🛒 Your Cart</div>
      <div id="cart-sidebar-body"></div>
    </div>
  </div>
</div>

<!-- ── Mobile-only floating summary bar — tap to open the cart sheet ── -->
<div id="mobile-cart-bar" class="mobile-cart-bar" onclick="toggleMobileCart(true)">
  <span>🛒 <strong id="mcb-count">0 items</strong></span>
  <span style="display:flex;align-items:center;gap:8px">
    <strong id="mcb-total" class="mono">0.00</strong>
    <span style="font-size:11px;opacity:.85">View Cart ▲</span>
  </span>
</div>
<div id="cart-backdrop" onclick="toggleMobileCart(false)"></div>

<script>
const CUR      = '<?= addslashes($cur) ?>';
const API_SHOP = '<?= base_url("api/customer-shop.php") ?>';
let srchTimer  = null;
let page       = 1;

function delaySearch() { clearTimeout(srchTimer); page = 1; srchTimer = setTimeout(loadProducts, 300); }

// ── Filter option lists (categories / forms) — populated once on load ──
async function loadFilterOptions() {
  const r = await apiPost(API_SHOP, { action: 'list_filters' });
  if (!r.success) return;

  const catSel = document.getElementById('f-category');
  (r.categories || []).forEach(c => {
    const opt = document.createElement('option');
    opt.value = c.id; opt.textContent = c.name;
    catSel.appendChild(opt);
  });

  const formSel = document.getElementById('f-form');
  (r.forms || []).forEach(f => {
    const opt = document.createElement('option');
    opt.value = f; opt.textContent = f;
    formSel.appendChild(opt);
  });
}

async function loadProducts() {
  const grid = document.getElementById('prod-grid');
  grid.innerHTML = '<div class="empty-state loading-row" style="grid-column:1/-1"><span class="spin"></span>Loading…</div>';

  const r = await apiPost(API_SHOP, {
    action: 'list_products',
    q: document.getElementById('f-search').value.trim(),
    category_id: document.getElementById('f-category')?.value || '',
    form:        document.getElementById('f-form')?.value     || '',
    stock_status:document.getElementById('f-stock')?.value    || '',
    page, page_size: 24,
  });

  if (!r.success) {
    grid.innerHTML = `<div class="empty-state" style="grid-column:1/-1;color:var(--danger)">⚠ ${esc(r.error || 'Failed to load products.')}</div>`;
    return;
  }
  if (!r.data.length) {
    grid.innerHTML = '<div class="empty-state" style="grid-column:1/-1">📭 No products found.</div>';
    document.getElementById('prod-footer').innerHTML = '';
    return;
  }

  grid.innerHTML = r.data.map(p => {
    const price = parseFloat(p.sale_price) || 0;
    const blocked = !p.in_stock && !window.SHOP_ALLOW_BACKORDER;
    return `<div class="card" style="padding:12px;display:flex;flex-direction:column;gap:6px">
      <div style="font-weight:700;font-size:13px;line-height:1.3">${formIconName(p.form, p.name)}</div>
      <div style="font-size:11px;color:var(--text3)">
        ${esc(p.strength||'')}${p.company_name ? ' · ' + esc(p.company_name) : ''}
      </div>
      <div style="display:flex;justify-content:space-between;align-items:center;margin-top:auto">
        <span class="mono" style="font-weight:800;color:var(--brand);font-size:14px">${CUR}${price.toFixed(2)}</span>
        <span class="badge" style="background:${p.in_stock?'#d4f0e6':'#fde8e8'};color:${p.in_stock?'var(--accent)':'var(--danger)'}">
          ${p.in_stock ? 'In Stock' : 'Out of Stock'}
        </span>
      </div>
      <button class="btn btn-sm btn-primary add-to-cart-btn" style="width:100%" ${blocked ? 'disabled' : ''}
              onclick='addToCart(${JSON.stringify(p).replace(/'/g,"&apos;")})'>
        ${blocked ? 'Unavailable' : '+ Add to Cart'}
      </button>
    </div>`;
  }).join('');

  const footer = document.getElementById('prod-footer');
  if (r.total_pages > 1) {
    footer.innerHTML = Array.from({length: r.total_pages}, (_, i) => i + 1).map(n =>
      `<button class="btn btn-sm ${n===page?'btn-primary':''}" style="margin:0 2px" onclick="page=${n};loadProducts()">${n}</button>`
    ).join('');
  } else {
    footer.innerHTML = '';
  }
}

// ── Cart panel — sticky sidebar on desktop, slide-up bottom sheet on
// mobile (toggled via toggleMobileCart()). Reads the shared cart from
// shop_footer.php (getCart/setCart/changeQty) and is called
// automatically whenever the cart changes (via setCart's typeof
// renderCartSidebar hook), plus once on page load below.
let _cartAddress   = '';
let _cartNotes     = '';
let _cartSheetOpen = false;

// Mobile breakpoint mirrors the CSS media query above — keep in sync.
const MOBILE_BP = 900;

function toggleMobileCart(forceState) {
  const sidebar = document.getElementById('cart-sidebar');
  const backdrop = document.getElementById('cart-backdrop');
  _cartSheetOpen = typeof forceState === 'boolean' ? forceState : !_cartSheetOpen;
  sidebar.classList.toggle('cart-open', _cartSheetOpen);
  backdrop.classList.toggle('show', _cartSheetOpen);
  if (_cartSheetOpen) document.body.style.overflow = 'hidden';
  else document.body.style.overflow = '';
}

function renderCartSidebar() {
  const body      = document.getElementById('cart-sidebar-body');
  const mobileBar = document.getElementById('mobile-cart-bar');
  if (!body) return;
  const cart = getCart();
  const ids  = Object.keys(cart);

  if (!ids.length) {
    body.innerHTML = `<div class="empty-state" style="padding:20px 0;text-align:center;font-size:12px">
      🛒 Your cart is empty.<br>Add products from the list.
    </div>`;
    if (mobileBar) mobileBar.style.display = 'none';
    toggleMobileCart(false); // auto-close the sheet once the cart empties
    return;
  }

  let subtotal = 0;
  const rows = ids.map(id => {
    const it = cart[id];
    const lineTotal = it.qty * it.price;
    subtotal += lineTotal;
    return `<div style="display:flex;justify-content:space-between;align-items:center;
                        gap:6px;padding:8px 0;border-bottom:1px solid var(--brand-light)">
      <div style="min-width:0;flex:1">
        <div style="font-weight:600;font-size:12.5px">${formIconName(it.form, it.name)}</div>
        <div style="font-size:10.5px;color:var(--text3)">${CUR}${it.price.toFixed(2)} each</div>
      </div>
      <div style="display:flex;align-items:center;gap:6px;flex-shrink:0">
        <button class="btn btn-sm cart-qty-btn" style="padding:1px 7px" onclick="changeQty('${id}',-1)">−</button>
        <span class="mono cart-qty-val" style="min-width:18px;text-align:center;font-size:12px">${it.qty}</span>
        <button class="btn btn-sm cart-qty-btn" style="padding:1px 7px" onclick="changeQty('${id}',1)">+</button>
      </div>
      <div class="mono" style="width:62px;text-align:right;font-weight:700;font-size:12px;flex-shrink:0">${CUR}${lineTotal.toFixed(2)}</div>
    </div>`;
  }).join('');

  body.innerHTML = `
    <div style="max-height:280px;overflow-y:auto">${rows}</div>
    <div style="display:flex;justify-content:space-between;font-weight:800;font-size:14px;
                padding:10px 0;border-top:2px solid var(--brand-light);margin-top:4px">
      <span>Subtotal</span><span class="mono">${CUR}${subtotal.toFixed(2)}</span>
    </div>
    <div class="fg" style="margin-bottom:8px">
      <label style="font-size:11px">Delivery / Pickup Address</label>
      <textarea id="cart-address" rows="2" placeholder="Where should we deliver, or leave blank for in-store pickup"
                style="width:100%;font-size:12px" oninput="_cartAddress=this.value">${esc(_cartAddress)}</textarea>
    </div>
    <div class="fg" style="margin-bottom:10px">
      <label style="font-size:11px">Notes (optional)</label>
      <input type="text" id="cart-notes" placeholder="Any special instructions" style="width:100%"
             value="${esc(_cartNotes)}" oninput="_cartNotes=this.value">
    </div>
    <button class="btn btn-primary" id="cart-checkout-btn" style="width:100%" onclick="placeOrder()">
      Place Order — Cash on Pickup
    </button>`;

  // Update the floating mobile bar (shown only on narrow screens, but
  // we keep its text current regardless so it's correct the instant
  // the viewport crosses the breakpoint, e.g. on device rotation).
  if (mobileBar) {
    const itemCount = ids.reduce((s, id) => s + cart[id].qty, 0);
    document.getElementById('mcb-count').textContent =
      itemCount + (itemCount === 1 ? ' item' : ' items');
    document.getElementById('mcb-total').textContent = CUR + subtotal.toFixed(2);
    mobileBar.style.display = (window.innerWidth <= MOBILE_BP) ? 'flex' : 'none';
  }
}

async function placeOrder() {
  const cart = getCart();
  const ids  = Object.keys(cart);
  if (!ids.length) return;

  const items = ids.map(id => ({ product_id: parseInt(id), qty: cart[id].qty }));
  const btn = document.getElementById('cart-checkout-btn');
  btn.disabled = true; btn.textContent = '⏳ Placing order…';

  const r = await apiPost(API_SHOP, {
    action: 'place_order',
    items,
    delivery_address: _cartAddress.trim(),
    notes: _cartNotes.trim(),
  });

  if (!r.success) {
    btn.disabled = false; btn.textContent = 'Place Order — Cash on Pickup';
    if (r.session_expired) { window.location.href = window.SHOP_BASE + 'shop/login.php'; return; }
    alert('⚠ ' + (r.error || 'Could not place order.'));
    return;
  }

  localStorage.removeItem(CART_KEY);
  updateCartBadge();
  _cartAddress = ''; _cartNotes = '';
  toggleMobileCart(false);
  alert(`✅ Order ${r.order_no} placed! Our team will review it shortly.`);
  window.location.href = window.SHOP_BASE + 'shop/orders.php';
}

// Keep the floating bar's visibility correct across viewport/orientation
// changes (e.g. rotating a phone), not just cart-content changes.
let _resizeTimer = null;
window.addEventListener('resize', () => {
  clearTimeout(_resizeTimer);
  _resizeTimer = setTimeout(renderCartSidebar, 150);
});

document.addEventListener('DOMContentLoaded', () => { loadFilterOptions(); loadProducts(); renderCartSidebar(); });
</script>

<?php require_once '../includes/shop_footer.php'; ?>
