<!DOCTYPE html>
<html lang="ur" dir="ltr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
<meta name="theme-color" content="#12372a">
<link rel="manifest" href="manifest.php">
<link rel="stylesheet" href="store-app.css?v=20261104a">
<title>Mr Cash &amp; Carry — Online Shopping</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Noto+Nastaliq+Urdu:wght@400;600;700&display=swap" rel="stylesheet" media="print" onload="this.media='all'"><noscript><link href="https://fonts.googleapis.com/css2?family=Noto+Nastaliq+Urdu:wght@400;600;700&display=swap" rel="stylesheet"></noscript>
<link href="https://fonts.googleapis.com/css2?family=Baloo+2:wght@500;600;700;800&family=Nunito:wght@400;600;700;800&display=swap" rel="stylesheet" media="print" onload="this.media='all'"><noscript><link href="https://fonts.googleapis.com/css2?family=Baloo+2:wght@500;600;700;800&family=Nunito:wght@400;600;700;800&display=swap" rel="stylesheet"></noscript>
<style>
  :root {
    --brand: #0f7a52;
    --brand-dark: #0a5c3d;
    --accent: #f5a623;
    --bg: #f4f7f5;
    --text: #1c2b23;
    --muted: #6b7a70;
    --border: #dfe8e2;
    --danger: #c0392b;
  }
  * { box-sizing: border-box; }
  body { margin: 0; font-family: 'Nunito', 'Segoe UI', Tahoma, Arial, sans-serif; background: var(--bg); color: var(--text); }
  a { text-decoration: none; color: inherit; }
  .brand h1, .hero h2, .cat-chip span:last-child, .product-name, .store-name { font-family: 'Baloo 2', 'Nunito', sans-serif; }

  /* ---------- Header ---------- */
  header.site-header {
    background: linear-gradient(135deg, var(--brand), var(--brand-dark));
    color: #fff; padding: 10px 20px; position: sticky; top: 0; z-index: 50;
    box-shadow: 0 3px 10px rgba(0,0,0,0.15);
  }
  .header-inner { max-width: 1200px; margin: 0 auto; display: flex; align-items: center; justify-content: space-between; gap: 14px; flex-wrap: wrap; }
  .header-subbar {
    max-width: 1200px; margin: 8px auto 0; padding: 6px 4px 0; border-top: 1px solid rgba(255,255,255,0.18);
    font-size: 12px; font-weight: 600; color: #eafff2; opacity: 0.95;
    white-space: nowrap; overflow-x: auto; scrollbar-width: none;
  }
  .header-subbar::-webkit-scrollbar { display: none; }
  .header-subbar b { color: #ffd873; font-weight: 700; }
  .brand { display: flex; align-items: center; gap: 10px; }
  @font-face { font-family: 'JameelNoori'; src: local('Jameel Noori Nastaleeq'), local('JameelNooriNastaleeq'), url('admin/assets/fonts/JameelNooriNastaleeq.ttf') format('truetype'); font-display: swap; }
  html.ur-mode body, html.ur-mode button, html.ur-mode input, html.ur-mode textarea, html.ur-mode select { font-family: 'JameelNoori', 'Noto Nastaliq Urdu', 'Jameel Noori Nastaleeq', serif !important; line-height: 2; }
  html.ur-mode .brand h1, html.ur-mode .hero h2, html.ur-mode .product-name, html.ur-mode .store-name { font-family: 'JameelNoori', 'Noto Nastaliq Urdu', serif !important; line-height: 1.9; }
  .product-name.ur { font-size: 17px; direction: rtl; }
  .pol-ur { display: none; direction: rtl; text-align: right; }
  html.ur-mode .pol-ur { display: block; } html.ur-mode .pol-en { display: none; }
  .brand-logo { height: 92px; width: auto; max-width: 62vw; display: block; background: #fff; border-radius: 14px; padding: 6px 16px; box-shadow: 0 3px 12px rgba(0,0,0,0.22); border-bottom: 3px solid #ffd873; flex-shrink: 0; }
  .brand span.tag { font-size: 13px !important; max-width: 230px; line-height: 1.5; }
  @media (max-width: 700px) { .brand-logo { height: 76px; } }
  .footer-logo { height: 92px; width: auto; max-width: 80vw; margin: 0 auto 10px; display: block; background: #fff; border-radius: 16px; padding: 8px 22px; border-bottom: 4px solid #ffd873; }
  .policy-box h4 { margin: 12px 0 4px; color: var(--primary, #0f7a52); }
  .policy-box li { margin: 3px 0; line-height: 1.5; font-size: 14px; }
  .brand .logo { font-size: 44px; }
  .brand h1 {
    font-size: 21px; margin: 0; line-height: 1.25; text-transform: uppercase; letter-spacing: .6px;
    color: #ffd873;
    text-shadow: 0 1px 0 rgba(0,0,0,0.3), 0 3px 6px rgba(0,0,0,0.35), 0 0 1px rgba(255,255,255,0.4);
  }
  .brand span.tag { display: block; font-size: 11.5px; font-weight: 600; opacity: 0.92; letter-spacing: .2px; margin-top: 2px; }
  .header-actions { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
  .header-btn {
    background: rgba(255,255,255,0.15); border: 1px solid rgba(255,255,255,0.4); color: #fff;
    padding: 8px 14px; border-radius: 8px; font-size: 13px; font-weight: 600; cursor: pointer;
    display: flex; align-items: center; gap: 6px;
  }
  .header-btn:hover { background: rgba(255,255,255,0.28); }
  .admin-link { font-size: 11.5px; opacity: 0.8; border: 1px solid rgba(255,255,255,0.35); padding: 6px 10px; border-radius: 6px; }
  .cart-badge { background: var(--accent); color: #1c2b23; border-radius: 999px; padding: 1px 7px; font-size: 11px; font-weight: 800; margin-left: 4px; }

  /* ---------- Hero ---------- */
  .hero {
    background: linear-gradient(180deg, #ffffff 0%, #eef6f1 100%);
    padding: 14px 16px; text-align: center; border-bottom: 1px solid var(--border);
  }
  .hero h2 { margin: 0 0 4px; font-size: 20px; color: var(--brand-dark); }
  .hero p { margin: 0; color: var(--muted); font-size: 13px; }

  /* ---------- Search ---------- */
  .search-bar { max-width: 1200px; margin: 18px auto 0; padding: 0 20px; }
  .search-bar input {
    width: 100%; padding: 12px 16px; border: 1.5px solid var(--border); border-radius: 10px;
    font-size: 14px; background: #fff; box-shadow: 0 2px 6px rgba(0,0,0,0.04);
  }
  .search-bar input:focus { outline: none; border-color: var(--brand); }

  /* ---------- Category tiles (bade square boxes, home-screen jaisa) ---------- */
  .cat-bar {
    max-width: 1300px; margin: 20px auto 0; padding: 0 20px;
    display: flex; flex-wrap: wrap; justify-content: center; gap: 16px;
  }
  .cat-chip {
    background: linear-gradient(160deg, #ffffff, #f3f7f5);
    border: 1px solid #ffffff; border-radius: 18px; padding: 14px 20px;
    font-size: 14.5px; font-weight: 700; cursor: pointer; color: var(--text); transition: all .18s;
    display: flex; flex-direction: row; align-items: center; gap: 16px; text-align: left;
    letter-spacing: .2px; flex: 1 1 210px; max-width: 320px;
    box-shadow:
      6px 6px 14px rgba(148, 170, 158, 0.35),
      -6px -6px 14px rgba(255, 255, 255, 0.9);
  }
  .cat-chip .cat-chip-icon {
    font-size: 34px; width: 62px; height: 62px; flex: none; display: flex; align-items: center; justify-content: center;
    background: linear-gradient(160deg, #f3faf6, #dcefe4); border-radius: 16px;
    box-shadow:
      inset 3px 3px 6px rgba(148, 170, 158, 0.35),
      inset -3px -3px 6px rgba(255, 255, 255, 0.85),
      0 3px 6px rgba(15, 122, 82, 0.08);
  }
  .cat-chip:hover {
    transform: translateY(-4px);
    box-shadow:
      8px 8px 18px rgba(148, 170, 158, 0.4),
      -8px -8px 18px rgba(255, 255, 255, 0.95);
  }
  .cat-chip.active {
    background: linear-gradient(160deg, var(--brand), var(--brand-dark)); border-color: var(--brand); color: #fff;
    box-shadow:
      6px 6px 14px rgba(10, 92, 61, 0.4),
      -4px -4px 10px rgba(255, 255, 255, 0.25);
  }
  .cat-chip.active .cat-chip-icon {
    background: rgba(255,255,255,0.16);
    box-shadow: inset 2px 2px 5px rgba(0,0,0,0.15), inset -2px -2px 5px rgba(255,255,255,0.15);
  }

  /* ---------- Product grid ---------- */
  main { max-width: 1300px; margin: 0 auto; padding: 18px 20px 60px; }
  .product-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 12px; margin-top: 12px; }
  .product-card {
    background: #fff; border: 1px solid var(--border); border-radius: 12px; padding: 0 0 10px;
    display: flex; flex-direction: column; gap: 4px; overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05); transition: transform .15s, box-shadow .15s;
  }
  .product-card:hover { transform: translateY(-4px); box-shadow: 0 14px 28px rgba(15,122,82,0.15); border-color: var(--brand); }
  .product-icon {
    font-size: 36px; text-align: center; background: linear-gradient(160deg, #eef6f1, #dcefe4);
    padding: 12px 0; margin-bottom: 2px;
  }
  .product-img { background:#fff; height: 110px; display:flex; align-items:center; justify-content:center; border-bottom:1px solid var(--border); }
  .product-img img { max-width:100%; max-height:100%; object-fit:contain; }
  .product-body { padding: 0 10px; display: flex; flex-direction: column; gap: 3px; flex: 1; }
  .product-name { font-weight: 700; font-size: 13px; line-height: 1.25; margin-top: 2px; }
  .product-urdu { font-size: 11.5px; color: var(--muted); direction: rtl; }
  .product-cat { font-size: 10px; color: var(--muted); background: var(--bg); display: inline-block; padding: 2px 8px; border-radius: 999px; }
  .product-price { font-size: 15px; font-weight: 800; color: var(--brand-dark); margin-top: 3px; }
  .out-of-stock { font-size: 11.5px; color: var(--danger); font-weight: 700; }
  .add-btn {
    margin: 6px 10px 0; background: var(--brand); color: #fff; border: none; border-radius: 8px;
    padding: 8px; font-size: 12.5px; font-weight: 700; cursor: pointer; transition: background .15s;
  }
  .add-btn:hover:not(:disabled) { background: var(--brand-dark); }
  .add-btn:disabled { background: #b7c2bc; cursor: not-allowed; }
  .empty-state { text-align: center; color: var(--muted); padding: 50px 0; font-size: 14.5px; grid-column: 1 / -1; }

  /* ---------- Modal ---------- */
  .modal-overlay {
    display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 100;
    align-items: center; justify-content: center; padding: 16px;
  }
  .modal-overlay.show { display: flex; }
  .modal-box { background: #fff; border-radius: 14px; padding: 22px; width: 460px; max-width: 100%; max-height: 90vh; overflow-y: auto; }
  .modal-box h3 { margin: 0 0 14px; color: var(--brand-dark); }
  .form-group { margin-bottom: 12px; }
  .form-group label { display: block; font-size: 12.5px; font-weight: 600; margin-bottom: 4px; }
  .form-group input, .form-group textarea {
    width: 100%; padding: 9px 11px; border: 1.5px solid var(--border); border-radius: 7px; font-size: 14px;
  }
  .modal-actions { display: flex; gap: 10px; margin-top: 16px; }
  .btn { flex: 1; padding: 10px; border-radius: 8px; border: none; font-weight: 700; font-size: 14px; cursor: pointer; }
  .btn-primary { background: var(--brand); color: #fff; }
  .btn-outline { background: #fff; border: 1.5px solid var(--border); color: var(--text); }
  .form-error { background: #fdecea; color: var(--danger); padding: 8px 10px; border-radius: 7px; font-size: 12.5px; margin-bottom: 10px; display: none; }
  .auth-tabs { display: flex; gap: 8px; margin-bottom: 14px; }
  .auth-tab { flex: 1; text-align: center; padding: 8px; border-radius: 8px; background: var(--bg); cursor: pointer; font-weight: 700; font-size: 13px; }
  .auth-tab.active { background: var(--brand); color: #fff; }

  /* ---------- Cart ---------- */
  .cart-item { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 10px 0; border-bottom: 1px dashed var(--border); }
  .cart-item-name { font-size: 13.5px; font-weight: 600; }
  .cart-item-sub { font-size: 11.5px; color: var(--muted); }
  .qty-ctrl { display: flex; align-items: center; gap: 8px; }
  .qty-ctrl button { width: 26px; height: 26px; border-radius: 6px; border: 1px solid var(--border); background: #fff; font-weight: 800; cursor: pointer; }
  .cart-total-row { display: flex; justify-content: space-between; font-size: 16px; font-weight: 800; margin-top: 14px; padding-top: 12px; border-top: 2px solid var(--border); }
  .order-badge { display: inline-block; padding: 3px 10px; border-radius: 999px; font-size: 11px; font-weight: 700; }
  .badge-pending { background: #fff3cd; color: #8a6d1e; }
  .badge-confirmed { background: #e3f2fd; color: #1565c0; }
  .badge-dispatched { background: #ede7f6; color: #5e35b1; }
  .badge-delivered { background: #e6f9ee; color: #1e824c; }
  .badge-cancelled { background: #fdecea; color: var(--danger); }
  .order-card { border: 1px solid var(--border); border-radius: 10px; padding: 12px; margin-bottom: 10px; }

  /* ---------- Footer (GraceSoft signature) ---------- */
  footer.site-footer { background: #10261c; color: #cfe3d7; padding: 30px 20px 20px; margin-top: 30px; }
  .footer-inner { max-width: 1200px; margin: 0 auto; text-align: center; }
  .footer-inner .store-name {
    font-weight: 800; color: #ffd873; font-size: 17px; margin-bottom: 6px; text-transform: uppercase; letter-spacing: .6px;
    text-shadow: 0 1px 0 rgba(0,0,0,0.3), 0 3px 6px rgba(0,0,0,0.4);
  }
  .grace-credit { margin-top: 18px; padding-top: 16px; border-top: 1px solid rgba(255,255,255,0.12); font-size: 12px; color: #9fb6a8; }
  .grace-credit b { color: #fff; }
  .grace-credit a { color: var(--accent); font-weight: 600; }


  /* ---------- Layout: left = categories (chhoti scroll bar), right = products ---------- */
  main { max-width: 1400px; }
  .shop-layout { display: grid; grid-template-columns: 230px 1fr; gap: 16px; align-items: start; margin-top: 8px; }
  .cat-side { position: sticky; top: 8px; background: #fff; border: 1px solid var(--border); border-radius: 12px; padding: 10px; max-height: calc(100vh - 24px); display: flex; flex-direction: column; }
  .cat-side input { width: 100%; padding: 8px 10px; border: 1.5px solid var(--border); border-radius: 8px; font-size: 13px; margin-bottom: 8px; }
  .cat-side input:focus { outline: none; border-color: var(--brand); }
  .cat-side .cat-bar { max-width: none; margin: 0; padding: 0; display: flex; flex-direction: column; flex-wrap: nowrap; justify-content: flex-start; gap: 4px; overflow-y: auto; }
  .cat-side .cat-chip { flex: none; max-width: none; width: 100%; padding: 7px 9px; gap: 9px; border-radius: 10px; font-size: 13px; background: #fff; border: 1px solid transparent; box-shadow: none; }
  .cat-side .cat-chip:hover { transform: none; background: #f1f8f4; box-shadow: none; }
  .cat-side .cat-chip .cat-chip-icon { font-size: 18px; width: 30px; height: 30px; border-radius: 8px; box-shadow: none; }
  .cat-side .cat-chip.active { background: var(--brand); color: #fff; border-color: var(--brand); box-shadow: none; }
  .shop-layout > * { min-width: 0; }
  .shop-right .search-bar { margin: 0 0 6px; }
  .delivery-note { max-width: 1400px; margin: 10px auto 0; padding: 9px 16px; background: #fff7e0; border: 1.5px solid #f0cf6b; border-radius: 10px; font-size: 13.5px; font-weight: 700; color: #6b4e00; text-align: center; }
  @media (max-width: 800px) {
    /* Header chhota + sath sath scroll na kare (upar ki faltu jagah khatam) */
    header.site-header { position: static; padding: 6px 8px; }
    .brand-logo { height: 46px; padding: 3px 10px; border-radius: 10px; }
    .brand span.tag { display: none; }
    .header-inner { gap: 6px; }
    .header-actions { gap: 5px; }
    .header-btn { padding: 6px 8px; font-size: 11px; }
    .admin-link { padding: 5px 7px; font-size: 10px; }
    .header-subbar { margin-top: 4px; padding-top: 4px; font-size: 10.5px; white-space: normal; line-height: 1.4; }
    .hero { padding: 8px 10px; }
    .hero h2 { font-size: 15px; margin: 0; }
    .hero p { display: none; }
    .delivery-note { margin: 6px 6px 0; padding: 6px 8px; font-size: 11.5px; }
    /* Mobile par bhi computer jaisa: left mein categories ki sidebar, right mein products */
    .shop-layout { grid-template-columns: 92px 1fr; gap: 8px; }
    .cat-side { position: sticky; top: 4px; max-height: calc(100vh - 12px); padding: 6px 4px; border-radius: 10px; }
    .cat-side input { font-size: 11px; padding: 6px 6px; margin-bottom: 6px; }
    .cat-side .cat-bar { flex-direction: column; overflow-y: auto; overflow-x: hidden; gap: 3px; }
    .cat-side .cat-chip { flex-direction: column; align-items: center; text-align: center; width: 100%; white-space: normal; padding: 6px 2px; gap: 3px; font-size: 10.5px; line-height: 1.15; }
    .cat-side .cat-chip .cat-chip-icon { width: 30px; height: 30px; font-size: 17px; }
    .product-grid { grid-template-columns: repeat(2, 1fr); gap: 8px; }
    .product-img { height: 80px; }
    .product-icon { font-size: 28px; padding: 8px 0; }
    .product-name { font-size: 12px; }
    .product-price { font-size: 14px; }
    .add-btn { font-size: 11.5px; padding: 7px 4px; margin: 5px 6px 0; }
    .product-body { padding: 0 6px; }
    main { padding: 8px 6px 50px; }
  }

  @media (max-width: 640px) {
    .brand h1 { font-size: 16px; }
    .header-actions { width: 100%; justify-content: space-between; }
  }

.fb-wa{display:flex;justify-content:space-between;align-items:center;gap:8px;margin-top:10px;padding:12px 14px;background:#25d366;color:#fff;border-radius:10px;font-weight:800;text-decoration:none;font-size:14px}
.fb-wa small{font-weight:600;opacity:.95;direction:ltr}
.fb-float{position:fixed;left:14px;bottom:14px;z-index:900;background:#25d366;color:#fff;border:none;border-radius:30px;padding:11px 16px;font-weight:800;font-size:14px;box-shadow:0 4px 14px rgba(0,0,0,.28);cursor:pointer}
</style>
</head>
<body>

<header class="site-header">
  <div class="header-inner">
    <div class="brand">
      <img class="brand-logo" src="uploads/mart_logo.png" alt="Mr Cash &amp; Carry">
      <div>
        <h1>Mr Cash &amp; Carry</h1>
        <span class="tag">Online Shopping — Order from home</span>
      </div>
    </div>
    <div class="header-actions">
      <button class="header-btn" id="langBtn" onclick="toggleLang()">🌐 اردو</button>
      <button class="header-btn" onclick="openQuickListModal()">📝 Send Your List</button>
      <button class="header-btn" onclick="openFeedback('')">💬 Feedback</button>
      <button class="header-btn" onclick="openCartModal()">🛍️ Cart <span class="cart-badge" id="cartCount">0</span></button>
      <button class="header-btn" id="accountBtn" onclick="onAccountBtnClick()">👤 Login / Register</button>
      <a class="admin-link" href="admin/">🔐 Staff Login</a>
    </div>
  </div>
  <div class="header-subbar"></div>
</header>

<div class="hero">
  <h2>Order Your Daily Grocery Needs From Home</h2>
  <p>Browse our products, add them to your cart, and place your order — we'll deliver it right to your doorstep.</p>
</div>

<div class="delivery-note">🚚 Home Delivery Available — place your order and we will deliver to your door.</div>
<main>
  <div class="shop-layout">
    <aside class="cat-side">
      <input type="text" id="catSearch" placeholder="🔍 Search categories..." oninput="renderCategoryBar()">
      <div class="cat-bar" id="catBar"></div>
    </aside>
    <div class="shop-right">
      <div class="search-bar"><input type="text" id="productSearch" placeholder="🔍 Search products..." oninput="renderProducts()"></div>
      <div class="product-grid" id="productGrid"><div class="empty-state">Loading products...</div></div>
    </div>
  </div>
</main>

<footer class="site-footer">
  <div class="footer-inner">
    <img class="footer-logo" src="uploads/mart_logo.png" alt="Mr Cash &amp; Carry"><div class="store-name">Mr Cash &amp; Carry</div>
    <div></div>
    <div style="margin-top:8px;"><a href="#" style="color:var(--accent);font-weight:700;" onclick="openModal('policyModal');return false;">↩️ Return Policy</a> &nbsp;·&nbsp; <a href="#" style="color:var(--accent);font-weight:700;" onclick="openFeedback('');return false;">💬 Feedback</a></div>
    <div class="grace-credit">
      <b>GraceSoft Inc</b> — Professional Accounting Solution<br>
      GraceSoft Mart — Software for Shopping Malls &amp; Cash &amp; Carry<br>
      📞 0307-9153674 &nbsp;·&nbsp; 🌐 <a href="https://www.gracesoft.world" target="_blank" style="font-size:16px;font-weight:900">www.gracesoft.world</a> &nbsp;·&nbsp; Admin: H.M Nadeem<br>
      &copy; <span id="yearNow"></span> GraceSoft Inc. All rights reserved.
    </div>
  </div>
</footer>
<button class="fb-float" onclick="openFeedback('')">💬 Feedback</button>

<!-- Login / Register Modal -->
<div class="modal-overlay" id="authModal">
  <div class="modal-box">
    <div class="auth-tabs">
      <div class="auth-tab active" id="tabLogin" onclick="switchAuthTab('login')">Login</div>
      <div class="auth-tab" id="tabRegister" onclick="switchAuthTab('register')">New Account</div>
    </div>
    <div class="form-error" id="authError"></div>

    <form id="loginForm">
      <div class="form-group"><label>Phone Number</label><input type="text" id="loginPhone" required></div>
      <div class="form-group"><label>Password</label><input type="password" id="loginPassword" required></div>
      <div class="modal-actions">
        <button type="button" class="btn btn-outline" onclick="closeModal('authModal')">Cancel</button>
        <button type="submit" class="btn btn-primary">Login</button>
      </div>
    </form>

    <form id="registerForm" style="display:none;">
      <div class="form-group"><label>Aapka Naam</label><input type="text" id="regName" required></div>
      <div class="form-group"><label>Phone Number</label><input type="text" id="regPhone" required></div>
      <div class="form-group"><label>Password</label><input type="password" id="regPassword" required></div>
      <div class="form-group"><label>Address</label><input type="text" id="regAddress"></div>
      <div class="form-group"><label>Area</label><input type="text" id="regArea"></div>
      <div class="modal-actions">
        <button type="button" class="btn btn-outline" onclick="closeModal('authModal')">Cancel</button>
        <button type="submit" class="btn btn-primary">Account Banayen</button>
      </div>
    </form>
  </div>
</div>

<!-- Feedback (WhatsApp) Modal -->
<div class="modal-overlay" id="feedbackModal">
  <div class="modal-box" style="width:420px;">
    <h3>💬 Feedback</h3>
    <p style="font-size:13.5px;color:var(--muted);margin-bottom:10px;">Send your opinion, complaint or suggestion directly on WhatsApp — we will reply soon.</p>
    <textarea id="fbText" rows="3" style="width:100%;padding:9px;border:1.5px solid var(--border,#ddd);border-radius:8px;font:inherit;" placeholder="Write your feedback (optional)..."></textarea>
    <a class="fb-wa" id="fbFaisal" href="#" target="_blank" rel="noopener" onclick="return fbGo(SHOP_WA)">💬 WhatsApp<small></small></a>
    <div class="modal-actions"><button class="btn-secondary" onclick="closeModal('feedbackModal')">Close</button></div>
  </div>
</div>

<!-- Return Policy Modal -->
<div class="modal-overlay" id="policyModal">
  <div class="modal-box" style="width:520px; max-height:88vh; overflow:auto;">
    <h3>↩️ Return Policy</h3>
    <div class="policy-box pol-en">
      <h4>When can an item be returned?</h4>
      <ul>
        <li>Request a return within <b>48 hours (2 days)</b> of delivery.</li>
        <li>If the item is damaged/broken/leaking, expired, wrong or missing — you get a return or replacement.</li>
        <li>The item packing must be sealed and the bill/order number available.</li>
      </ul>
      <h4>Which items cannot be returned?</h4>
      <ul>
        <li>Fresh vegetables, fruit, milk/yogurt, and opened or weighed (loose) items.</li>
        <li>Items damaged by the customer or already used.</li>
      </ul>
      <h4>How to return</h4>
      <ul>
        <li>Login, open <b>My Orders</b>, press <b>"Return Request"</b> on a delivered order, and select the item and reason.</li>
        <li>Our team will contact you by phone and collect the item; after approval you get a refund/replacement (cash or adjusted in your next bill).</li>
      </ul>
      <p style="font-size:12.5px; color:var(--muted); margin-top:10px;">For help: </p>
    </div>
    <div class="policy-box pol-ur">
      <h4>ریٹرن کب ہو سکتا ہے؟</h4>
      <ul>
        <li>سامان ملنے کے <b>48 گھنٹے (2 دن)</b> کے اندر ریٹرن ریکوئسٹ کریں۔</li>
        <li>آئٹم خراب/ٹوٹا ہوا/لیک ہو، ایکسپائری گزر چکی ہو، غلط آئٹم آیا ہو یا آئٹم کم ہو تو ریٹرن یا تبدیلی ملے گی۔</li>
        <li>آئٹم کی پیکنگ سیل بند ہو اور بل/آرڈر نمبر موجود ہو۔</li>
      </ul>
      <h4>کون سی چیزیں ریٹرن نہیں ہوں گی؟</h4>
      <ul>
        <li>تازہ سبزی، پھل، دودھ/دہی، کھلا یا تولا ہوا سامان۔</li>
        <li>گاہک کی طرف سے خراب ہوا یا استعمال شدہ سامان۔</li>
      </ul>
      <h4>طریقہ</h4>
      <ul>
        <li>لاگ ان کر کے <b>میرے آرڈرز</b> میں ڈیلیور شدہ آرڈر پر <b>"ریٹرن ریکوئسٹ"</b> دبائیں، آئٹم اور وجہ منتخب کریں۔</li>
        <li>ہماری ٹیم آپ سے فون پر رابطہ کرے گی، سامان واپس اٹھا لے گی اور منظوری کے بعد رقم واپس/تبدیلی ہو گی (کیش یا اگلے بل میں ایڈجسٹ)۔</li>
      </ul>
      <p style="font-size:12.5px; margin-top:10px;">مدد کے لیے: </p>
    </div>
    <div class="modal-actions"><button type="button" class="btn btn-primary" onclick="closeModal('policyModal')">Theek Hai</button></div>
  </div>
</div>

<!-- Return Request Modal -->
<div class="modal-overlay" id="returnModal">
  <div class="modal-box" style="width:480px;">
    <h3>↩️ Return Request <span id="rtOrderNo" style="font-size:13px;color:var(--muted)"></span></h3>
    <div class="form-error" id="returnError"></div>
    <div id="rtItems"></div>
    <div class="form-group"><label>Wajah</label>
      <select id="rtReason">
        <option value="damaged">Kharab / toota hua</option>
        <option value="expired">Expiry guzar chuki</option>
        <option value="wrong_item">Ghalat item aaya</option>
        <option value="missing_item">Item kam aaya</option>
        <option value="quality">Quality theek nahi</option>
        <option value="other">Aur wajah</option>
      </select></div>
    <div class="form-group"><label>Tafseel (optional)</label><input type="text" id="rtDetails" maxlength="500"></div>
    <div style="font-size:12px;color:var(--muted);">Policy: <a href="#" onclick="closeModal('returnModal');openModal('policyModal');return false;">Return Policy parhen</a></div>
    <div class="modal-actions">
      <button type="button" class="btn btn-outline" onclick="closeModal('returnModal')">Cancel</button>
      <button type="button" class="btn btn-primary" onclick="submitReturn()">Request Bhejen</button>
    </div>
  </div>
</div>

<!-- Cart Modal -->
<div class="modal-overlay" id="cartModal">
  <div class="modal-box" style="width:480px;">
    <h3>🛍️ Aapki Cart</h3>
    <div id="cartItemsBox"><div class="empty-state">Cart khaali hai</div></div>
    <div class="cart-total-row"><span>Total</span><span id="cartTotalVal">Rs. 0</span></div>
    <div class="modal-actions">
      <button type="button" class="btn btn-outline" onclick="closeModal('cartModal')">Shopping Jari Rakhen</button>
      <button type="button" class="btn btn-primary" onclick="proceedToCheckout()">Checkout</button>
    </div>
  </div>
</div>

<!-- Checkout Modal -->
<div class="modal-overlay" id="checkoutModal">
  <div class="modal-box">
    <h3>📦 Order Confirm Karen</h3>
    <div class="form-error" id="checkoutError"></div>
    <form id="checkoutForm">
      <div class="form-group"><label>Delivery Address</label><textarea id="coAddress" rows="2" required></textarea></div>
      <div class="form-group"><label>Note (optional)</label><input type="text" id="coNotes" placeholder="e.g. deliver in the evening"></div>
      <div class="form-group"><label>💳 Payment Method</label>
        <select id="coPayMethod" onchange="coPayChanged()"><option value="">💵 Cash on Delivery (pay when you receive the goods)</option></select>
        <div id="coPayInfo" style="display:none;margin-top:8px;padding:10px;border:1px dashed var(--accent);border-radius:8px;font-size:13px;background:#f3fbf5;">
          <div>Is account mein payment bhejen: <b id="coPayAcc"></b></div>
          <input type="text" id="coPayRef" placeholder="Transaction ID / reference (optional)" style="margin-top:6px;width:100%;">
          <div style="font-size:11.5px;color:var(--muted);margin-top:4px;">After sending the payment, enter the Transaction ID here. The order will be processed once payment is confirmed.</div>
        </div>
      </div>
      <div style="font-size:12px;color:var(--muted);margin-bottom:8px;">Return facility within 48 hours of delivery — <a href="#" onclick="openModal('policyModal');return false;">Return Policy</a></div>
      <div class="cart-total-row"><span>Total Payable</span><span id="coTotalVal">Rs. 0</span></div>
      <div class="modal-actions">
        <button type="button" class="btn btn-outline" onclick="closeModal('checkoutModal')">Cancel</button>
        <button type="submit" class="btn btn-primary">Order Place Karen</button>
      </div>
    </form>
  </div>
</div>

<!-- Order Confirmation Modal -->
<div class="modal-overlay" id="confirmModal">
  <div class="modal-box" style="text-align:center;">
    <div style="font-size:44px;">✅</div>
    <h3 style="margin-top:4px;">Order Mil Gaya!</h3>
    <p>Aapka order number: <b id="confirmOrderNo"></b></p>
    <p style="color:var(--muted); font-size:13px;">Hum jald hi aap se rabta karenge.</p>
    <button type="button" class="btn btn-primary" style="background:#25d366; border-color:#25d366; margin-bottom:10px;" onclick="sendLastWa()">💬 Send order on WhatsApp</button>
    <div class="modal-actions">
      <button type="button" class="btn btn-outline" onclick="closeModal('confirmModal')">Shopping Jari Rakhen</button>
      <button type="button" class="btn btn-primary" onclick="closeModal('confirmModal'); openMyOrders();">Mere Orders Dekhen</button>
    </div>
  </div>
</div>

<!-- My Orders Modal -->
<div class="modal-overlay" id="ordersModal">
  <div class="modal-box" style="width:520px;">
    <h3>📜 Mere Orders</h3>
    <div id="myOrdersBox"><div class="empty-state">Loading...</div></div>
    <div class="modal-actions">
      <button type="button" class="btn btn-outline" onclick="closeModal('ordersModal')">Close</button>
    </div>
  </div>
</div>

<!-- Quick List Modal: product ek-ek select karne ki bajaye seedha apni
     list TYPE karke ya TASVEER (photo) bhej dena (2026-10-03) -->
<div class="modal-overlay" id="quickListModal">
  <div class="modal-box" style="width:480px;">
    <h3>📝 Send Your List</h3>
    <p style="color:var(--muted); font-size:13px; margin-top:-6px;">No need to select every item — just write your grocery list or attach a photo. We will contact you.</p>
    <div class="form-error" id="quickListError"></div>
    <form id="quickListForm">
      <div class="form-group">
        <label>Write Your List (optional)</label>
        <textarea id="qlText" rows="5" placeholder="Masalan: 5 KG Atta, 1 KG Chini, 2 Cooking Oil..."></textarea>
      </div>
      <div class="form-group">
        <label>Ya List ki Tasveer Lagayen (optional)</label>
        <input type="file" id="qlImage" accept="image/*">
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-outline" onclick="closeModal('quickListModal')">Cancel</button>
        <button type="submit" class="btn btn-primary">List Bhej Den</button>
      </div>
    </form>
  </div>
</div>

<script>
document.getElementById('yearNow').textContent = new Date().getFullYear();

let PRODUCTS = [];
let CATEGORIES = [];
let ACTIVE_CAT = 'all';
let CART = JSON.parse(localStorage.getItem('store_cart') || '[]');
// ---------- Shop WhatsApp notification (order / list / return -> shop owner's WhatsApp) ----------
const SHOP_WA_NUMBER = '923213185633';
let LAST_WA_URL = '';
function shopWaUrl(msg) { return 'https://wa.me/' + SHOP_WA_NUMBER + '?text=' + encodeURIComponent(msg); }
// Browser popup blockers allow window.open only inside a click/submit; so open a blank tab FIRST
// (synchronously), then point it to WhatsApp after the server confirms. Returns the tab (or null if blocked).
function preOpenWa() { try { return window.open('', '_blank'); } catch (e) { return null; } }
function finishWa(tab, msg) {
  LAST_WA_URL = shopWaUrl(msg);
  if (tab && !tab.closed) { tab.location.href = LAST_WA_URL; return true; }
  return false;
}
function cancelWa(tab) { try { if (tab && !tab.closed) tab.close(); } catch (e) {} }
function sendLastWa() { if (LAST_WA_URL) window.open(LAST_WA_URL, '_blank'); }
function waCustomerLine() { return CUSTOMER ? ('Customer: ' + (CUSTOMER.name || '') + ' (' + (CUSTOMER.phone || '') + ')') : ''; }

let CUSTOMER = null;

function esc(str) {
  return String(str ?? '').replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));
}
function num(n) { return parseFloat(n || 0).toLocaleString('en-PK', { minimumFractionDigits: 0, maximumFractionDigits: 2 }); }

function openModal(id) { document.getElementById(id).classList.add('show'); }
function closeModal(id) { document.getElementById(id).classList.remove('show'); }

async function apiGet(url) {
  const res = await fetch(url, { credentials: 'include' });
  return res.json();
}
async function apiPost(url, body) {
  const res = await fetch(url, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
  return res.json();
}
async function apiPut(url, body) {
  const res = await fetch(url, { method: 'PUT', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
  return res.json();
}

function saveCart() { localStorage.setItem('store_cart', JSON.stringify(CART)); renderCartBadge(); }
function renderCartBadge() {
  const count = CART.reduce((s, i) => s + i.qty, 0);
  document.getElementById('cartCount').textContent = count;
}

// ---------- Load products ----------
async function loadStore() {
  const data = await apiGet('api/store_products.php');
  if (!data.success) {
    document.getElementById('productGrid').innerHTML = '<div class="empty-state">Failed to load products. Please try again later.<br><small style="opacity:.7;">' + esc(data.error || '') + '</small></div>';
    return;
  }
  PRODUCTS = data.products;
  CATEGORIES = data.categories;
  renderCategoryBar();
  renderProducts();
  if (!PRODUCTS.length) {
    console.warn('Store: API returned 0 products. Check that products exist with active=1 in the admin panel.');
  }
}

function renderCategoryBar() {
  const bar = document.getElementById('catBar');
  const ct = (document.getElementById('catSearch')?.value || '').trim().toLowerCase();
  let html = `<div class="cat-chip ${ACTIVE_CAT === 'all' ? 'active' : ''}" onclick="filterCategory('all')"><span class="cat-chip-icon">🛒</span><span>All Items</span></div>`;
  CATEGORIES.filter(c => !ct || (c.name || '').toLowerCase().includes(ct)).forEach(c => {
    html += `<div class="cat-chip ${ACTIVE_CAT == c.id ? 'active' : ''}" onclick="filterCategory(${c.id})"><span class="cat-chip-icon">${esc(c.icon || '📦')}</span><span>${esc(c.name)}</span></div>`;
  });
  bar.innerHTML = html;
}

function filterCategory(catId) {
  ACTIVE_CAT = catId;
  renderCategoryBar();
  renderProducts();
}

function renderProducts() {
  const grid = document.getElementById('productGrid');
  const term = (document.getElementById('productSearch')?.value || '').trim().toLowerCase();
  let list = ACTIVE_CAT === 'all' ? PRODUCTS : PRODUCTS.filter(p => p.category_id == ACTIVE_CAT);
  if (term) {
    list = list.filter(p =>
      (p.name || '').toLowerCase().includes(term) ||
      (p.urdu_name || '').toLowerCase().includes(term) ||
      (p.brand || '').toLowerCase().includes(term)
    );
  }
  if (!list.length) {
    grid.innerHTML = '<div class="empty-state">' + (PRODUCTS.length ? 'No products found.' : 'No products available yet.') + '</div>';
    return;
  }
  grid.innerHTML = list.map(p => `
    <div class="product-card">
      ${p.image
        ? `<div class="product-img"><img src="${esc(p.image)}" alt="${esc(p.name)}" loading="lazy" onerror="this.parentNode.outerHTML='<div class=&quot;product-icon&quot;>${esc(p.category_icon || '🛒')}</div>'"></div>`
        : `<div class="product-icon">${esc(p.category_icon || '🛒')}</div>`}
      <div class="product-body">
        ${(LANG === 'ur' && p.urdu_name)
          ? `<div class="product-name ur">${esc(p.urdu_name)}</div><div class="product-urdu" style="direction:ltr;">${esc(p.name)}</div>`
          : `<div class="product-name">${esc(p.name)}</div>${p.urdu_name ? `<div class="product-urdu">${esc(p.urdu_name)}</div>` : ''}`}
        <div><span class="product-cat">${esc(p.category_name || 'General')}${p.brand ? ' · ' + esc(p.brand) : ''}</span></div>
        <div class="product-price">Rs. ${num(p.price)}</div>
        ${p.in_stock ? '' : '<div class="out-of-stock">Out of Stock</div>'}
      </div>
      <button class="add-btn" ${p.in_stock ? '' : 'disabled'} onclick="addToCart(${p.id})">${p.in_stock ? '➕ Add to Cart' : 'Out of Stock'}</button>
    </div>`).join('');
}

function addToCart(productId) {
  const p = PRODUCTS.find(x => x.id === productId);
  if (!p) return;
  const existing = CART.find(c => c.product_id === productId);
  if (existing) existing.qty += 1;
  else CART.push({ product_id: p.id, name: p.name, price: p.price, qty: 1 });
  saveCart();
  openCartModal();
}

function changeCartQty(productId, delta) {
  const item = CART.find(c => c.product_id === productId);
  if (!item) return;
  item.qty += delta;
  if (item.qty <= 0) CART = CART.filter(c => c.product_id !== productId);
  saveCart();
  renderCart();
}

function removeFromCart(productId) {
  CART = CART.filter(c => c.product_id !== productId);
  saveCart();
  renderCart();
}

function cartTotal() { return CART.reduce((s, i) => s + i.price * i.qty, 0); }

function renderCart() {
  const box = document.getElementById('cartItemsBox');
  if (!CART.length) {
    box.innerHTML = '<div class="empty-state">Cart khaali hai</div>';
  } else {
    box.innerHTML = CART.map(c => `
      <div class="cart-item">
        <div>
          <div class="cart-item-name">${esc(c.name)}</div>
          <div class="cart-item-sub">Rs. ${num(c.price)} x ${c.qty} = Rs. ${num(c.price * c.qty)}</div>
        </div>
        <div class="qty-ctrl">
          <button onclick="changeCartQty(${c.product_id}, -1)">−</button>
          <span>${c.qty}</span>
          <button onclick="changeCartQty(${c.product_id}, 1)">+</button>
          <button onclick="removeFromCart(${c.product_id})" style="color:var(--danger); border:none; background:none; font-size:16px; cursor:pointer;">🗑️</button>
        </div>
      </div>`).join('');
  }
  document.getElementById('cartTotalVal').textContent = 'Rs. ' + num(cartTotal());
}

function openCartModal() { renderCart(); openModal('cartModal'); }

function proceedToCheckout() {
  if (!CART.length) return;
  closeModal('cartModal');
  if (!CUSTOMER) {
    document.getElementById('authError').style.display = 'none';
    switchAuthTab('login');
    openModal('authModal');
    return;
  }
  document.getElementById('coAddress').value = CUSTOMER.address || '';
  document.getElementById('coTotalVal').textContent = 'Rs. ' + num(cartTotal());
  document.getElementById('checkoutError').style.display = 'none';
  loadPayMethods();
  openModal('checkoutModal');
}

let PAY_ACCOUNTS = [];
async function loadPayMethods() {
  const sel = document.getElementById('coPayMethod');
  sel.innerHTML = '<option value="">💵 Cash on Delivery (pay when you receive the goods)</option>';
  document.getElementById('coPayInfo').style.display = 'none';
  try {
    const d = await apiGet('api/store_payment_methods.php');
    PAY_ACCOUNTS = d.success ? d.accounts : [];
  } catch (e) { PAY_ACCOUNTS = []; }
  PAY_ACCOUNTS.forEach(a => {
    const o = document.createElement('option');
    o.value = a.id;
    o.textContent = (a.type === 'bank' ? '🏦 ' : '📱 ') + a.name;
    sel.appendChild(o);
  });
}
function coPayChanged() {
  const id = document.getElementById('coPayMethod').value;
  const a = PAY_ACCOUNTS.find(x => String(x.id) === String(id));
  const box = document.getElementById('coPayInfo');
  if (!a) { box.style.display = 'none'; return; }
  document.getElementById('coPayAcc').textContent = a.name + ' — ' + a.account_number;
  box.style.display = 'block';
}

// ---------- Auth ----------
function switchAuthTab(tab) {
  document.getElementById('tabLogin').classList.toggle('active', tab === 'login');
  document.getElementById('tabRegister').classList.toggle('active', tab === 'register');
  document.getElementById('loginForm').style.display = tab === 'login' ? 'block' : 'none';
  document.getElementById('registerForm').style.display = tab === 'register' ? 'block' : 'none';
}

function updateAccountBtn() {
  const btn = document.getElementById('accountBtn');
  if (CUSTOMER) {
    btn.textContent = '👤 ' + CUSTOMER.name + ' (Orders)';
  } else {
    btn.textContent = '👤 Login / Register';
  }
}

function onAccountBtnClick() {
  if (CUSTOMER) openMyOrders();
  else openModal('authModal');
}

async function checkSession() {
  const data = await apiGet('api/store_auth.php?action=me');
  if (data.success && data.logged_in) {
    CUSTOMER = data.customer;
  }
  updateAccountBtn();
}

document.getElementById('loginForm').addEventListener('submit', async (e) => {
  e.preventDefault();
  const phone = document.getElementById('loginPhone').value.trim();
  const password = document.getElementById('loginPassword').value;
  const data = await apiPost('api/store_auth.php?action=login', { phone, password });
  const errBox = document.getElementById('authError');
  if (data.success) {
    CUSTOMER = data.customer;
    updateAccountBtn();
    closeModal('authModal');
    if (CART.length) proceedToCheckout();
  } else {
    errBox.textContent = data.error;
    errBox.style.display = 'block';
  }
});

document.getElementById('registerForm').addEventListener('submit', async (e) => {
  e.preventDefault();
  const payload = {
    name: document.getElementById('regName').value.trim(),
    phone: document.getElementById('regPhone').value.trim(),
    password: document.getElementById('regPassword').value,
    address: document.getElementById('regAddress').value.trim(),
    area: document.getElementById('regArea').value.trim(),
  };
  const data = await apiPost('api/store_auth.php?action=register', payload);
  const errBox = document.getElementById('authError');
  if (data.success) {
    CUSTOMER = data.customer;
    updateAccountBtn();
    closeModal('authModal');
    if (CART.length) proceedToCheckout();
  } else {
    errBox.textContent = data.error;
    errBox.style.display = 'block';
  }
});

document.getElementById('checkoutForm').addEventListener('submit', async (e) => {
  e.preventDefault();
  const payload = {
    delivery_address: document.getElementById('coAddress').value.trim(),
    notes: document.getElementById('coNotes').value.trim(),
    payment_account_id: document.getElementById('coPayMethod').value || null,
    payment_ref: (document.getElementById('coPayRef') ? document.getElementById('coPayRef').value.trim() : ''),
    items: CART.map(c => ({ product_id: c.product_id, name: c.name, price: c.price, qty: c.qty })),
  };
  const waTab = preOpenWa();
  const cartSnapshot = CART.map(c => ({ ...c }));
  const data = await apiPost('api/store_orders.php', payload);
  const errBox = document.getElementById('checkoutError');
  if (data.success) {
    let total = 0;
    const lines = cartSnapshot.map((c, i) => { const t = c.price * c.qty; total += t; return (i + 1) + '. ' + c.name + ' x ' + c.qty + ' @ Rs. ' + c.price + ' = Rs. ' + t; });
    const waMsg = '*NEW ONLINE ORDER* - ' + SHOP_NAME + '\nOrder #: ' + data.order_no + '\n' + waCustomerLine() + '\nAddress: ' + payload.delivery_address + '\n\n' + lines.join('\n') + '\n\n*Total: Rs. ' + total + '*' + (payload.notes ? '\nNote: ' + payload.notes : '');
    finishWa(waTab, waMsg);
    CART = [];
    saveCart();
    closeModal('checkoutModal');
    document.getElementById('confirmOrderNo').textContent = data.order_no;
    openModal('confirmModal');
  } else {
    cancelWa(waTab);
    errBox.textContent = data.error;
    errBox.style.display = 'block';
  }
});

// ---------- My Orders ----------
async function openMyOrders() {
  openModal('ordersModal');
  const box = document.getElementById('myOrdersBox');
  box.innerHTML = '<div class="empty-state">Loading...</div>';
  const data = await apiGet('api/store_orders.php');
  if (!data.success) {
    box.innerHTML = `<div class="empty-state">${esc(data.error || 'Could not load orders')}</div>`;
    return;
  }
  if (!data.orders.length) {
    box.innerHTML = '<div class="empty-state">No orders yet.</div>';
    return;
  }
  MY_ORDERS_CACHE = data.orders;
  const rd = await apiGet('api/store_returns.php');
  const rets = rd.success ? rd.returns : [];
  if (rd.success) RETURN_WINDOW_H = rd.window_hours;
  const statusLabel = { pending: 'Pending', confirmed: 'Confirmed', dispatched: 'Dispatched', delivered: 'Delivered', cancelled: 'Cancelled' };
  box.innerHTML = data.orders.map(o => `
    <div class="order-card">
      <div style="display:flex; justify-content:space-between; align-items:center;">
        <b>${esc(o.order_no)}</b>
        <span class="order-badge badge-${o.status}">${statusLabel[o.status] || o.status}</span>
      </div>
      <div style="font-size:12px; color:var(--muted); margin:4px 0 8px;">${new Date(o.created_at).toLocaleString()}</div>
      ${o.items.map(it => `<div style="font-size:13px;">${esc(it.product_name)} x${it.qty} — Rs. ${num(it.line_total)}</div>`).join('')}
      <div style="text-align:right; font-weight:800; margin-top:6px;">Total: Rs. ${num(o.total_amount)}</div>
      <div style="text-align:right; font-size:12px; color:var(--muted);">${o.payment_account_name ? '💳 ' + esc(o.payment_account_name) : '💵 Cash on Delivery'} · ${o.payment_status === 'paid' ? '✅ Payment mil gayi' : '⏳ Payment baqi'}</div>
      ${returnActionHtml(o, rets)}
      <button class="header-btn" style="background:#25d366;color:#fff;border:none;margin-top:8px;" onclick="openFeedback('${esc(o.order_no)}')">💬 Feedback</button>
    </div>`).join('');
}

const RETURN_STATUS_LABEL = { pending: 'Return: Pending', approved: 'Return: Approved', rejected: 'Return: Rejected', picked_up: 'Return: Saman utha liya', refunded: 'Return: Refunded' };
let RETURN_WINDOW_H = 48;
let MY_ORDERS_CACHE = [];
function returnActionHtml(o, rets) {
  if (o.status !== 'delivered') return '';
  const r = rets.filter(x => x.store_order_id == o.id)[0];
  if (r) return `<div style="margin-top:8px;font-size:12.5px;"><b>${RETURN_STATUS_LABEL[r.status]}</b>${r.admin_note ? ' — ' + esc(r.admin_note) : ''}</div>`;
  const hrs = (Date.now() - new Date(String(o.updated_at).replace(' ', 'T')).getTime()) / 3600000;
  if (hrs > RETURN_WINDOW_H) return '<div style="margin-top:8px;font-size:12px;color:var(--muted);">Return period over</div>';
  return `<div style="margin-top:8px;"><button class="btn btn-outline" style="padding:6px 12px;font-size:12.5px;" onclick="openReturnModal(${o.id})">↩️ Return Request</button></div>`;
}
let RETURN_ORDER = null;
function openReturnModal(orderId) {
  RETURN_ORDER = MY_ORDERS_CACHE.find(o => o.id == orderId);
  if (!RETURN_ORDER) return;
  document.getElementById('rtOrderNo').textContent = RETURN_ORDER.order_no;
  document.getElementById('returnError').style.display = 'none';
  document.getElementById('rtDetails').value = '';
  document.getElementById('rtItems').innerHTML = RETURN_ORDER.items.map((it, i) => `
    <div style="display:flex;align-items:center;gap:8px;margin-bottom:6px;font-size:13px;">
      <input type="checkbox" id="rtChk${i}">
      <label for="rtChk${i}" style="flex:1;">${esc(it.product_name)} (x${it.qty})</label>
      <input type="number" id="rtQty${i}" min="1" max="${it.qty}" value="${it.qty}" style="width:60px;">
    </div>`).join('');
  closeModal('ordersModal');
  openModal('returnModal');
}
async function submitReturn() {
  const err = document.getElementById('returnError');
  err.style.display = 'none';
  const items = [];
  RETURN_ORDER.items.forEach((it, i) => {
    if (document.getElementById('rtChk' + i).checked) items.push({ product_name: it.product_name, qty: parseInt(document.getElementById('rtQty' + i).value) || 1 });
  });
  const waTab = preOpenWa();
  const rtReason = document.getElementById('rtReason').value, rtDetails = document.getElementById('rtDetails').value;
  const data = await apiPost('api/store_returns.php', { order_id: RETURN_ORDER.id, reason: rtReason, details: rtDetails, items });
  if (data.success) {
    const waMsg = '*RETURN / REPLACE REQUEST* - ' + SHOP_NAME + '\nOrder #: ' + (RETURN_ORDER.order_no || RETURN_ORDER.id) + '\n' + waCustomerLine() + '\nReason: ' + rtReason + (rtDetails ? '\nDetails: ' + rtDetails : '') + '\n\nItems:\n' + items.map((it, i) => (i + 1) + '. ' + it.product_name + ' x ' + it.qty).join('\n');
    finishWa(waTab, waMsg);
    closeModal('returnModal'); openMyOrders();
    if (LAST_WA_URL && (!waTab || waTab.closed)) { if (confirm('Send this return request on WhatsApp too?')) sendLastWa(); }
  }
  else { cancelWa(waTab); err.textContent = data.error; err.style.display = 'block'; }
}

// ---------- Quick List (apni list type ya tasveer karke bhejna) ----------
function openQuickListModal() {
  if (!CUSTOMER) {
    document.getElementById('authError').style.display = 'none';
    switchAuthTab('login');
    openModal('authModal');
    showToastLike('Please Login/Register first, then you can send your list');
    return;
  }
  document.getElementById('qlText').value = '';
  document.getElementById('qlImage').value = '';
  document.getElementById('quickListError').style.display = 'none';
  openModal('quickListModal');
}

// Chhota helper - is page par koi toast system nahi tha, is liye simple alert jaisa
// error box hi use karte hain (quickListError ke through), ye function abhi khaali
// chhoti si no-op hai taake openQuickListModal ka call error na de.
function showToastLike(msg) { /* kept minimal - login modal khud message de deta hai */ }

document.getElementById('quickListForm').addEventListener('submit', async (e) => {
  e.preventDefault();
  const errBox = document.getElementById('quickListError');
  errBox.style.display = 'none';
  const text = document.getElementById('qlText').value.trim();
  const fileInput = document.getElementById('qlImage');
  const file = fileInput.files[0];

  if (!text && !file) {
    errBox.textContent = 'Write a list or attach a photo';
    errBox.style.display = 'block';
    return;
  }

  const fd = new FormData();
  if (text) fd.append('list_text', text);
  if (file) fd.append('image', file);

  const waTab = preOpenWa();
  const res = await fetch('api/store_quick_lists.php', { method: 'POST', credentials: 'include', body: fd });
  const data = await res.json();

  if (data.success) {
    const waMsg = '*NEW GROCERY LIST* - ' + SHOP_NAME + '\n' + waCustomerLine() + '\n\n' + (text || '(List photo uploaded on website)') + (file ? '\n\n(Photo is uploaded on the website)' : '');
    finishWa(waTab, waMsg);
    closeModal('quickListModal');
    alert('✅ We have received your list and will contact you soon!');
  } else {
    cancelWa(waTab);
    errBox.textContent = data.error || 'Could not send the list, please try again';
    errBox.style.display = 'block';
  }
});

renderCartBadge();
checkSession();
loadStore();

/* ================= URDU MODE (customer EN <-> اردو) ================= */

let FB_ORDER = '';
function openFeedback(orderNo) { FB_ORDER = orderNo || ''; closeModal('ordersModal'); openModal('feedbackModal'); }
function fbGo(num) {
  const t = document.getElementById('fbText').value.trim();
  const msg = 'Assalam-o-Alaikum, ' + SHOP_NAME + '.' + (FB_ORDER ? ' Order # ' + FB_ORDER + '.' : '') + ' Feedback: ' + (t || '');
  window.open('https://wa.me/' + num + '?text=' + encodeURIComponent(msg), '_blank');
  return false;
}
const I18N_UR = {"💬 Feedback": "💬 فیڈ بیک", "Send your opinion, complaint or suggestion directly on WhatsApp — we will reply soon.": "اپنی رائے، شکایت یا مشورہ سیدھا واٹس ایپ پر بھیجیں — ہم جلد جواب دیں گے۔", "ATTR:Write your feedback (optional)...": "اپنا فیڈ بیک لکھیں (اختیاری)...", "💬 WhatsApp: M. Faisal Hayat": "💬 واٹس ایپ: محمد فیصل حیات", "💬 WhatsApp: M. Yasir Hayat": "💬 واٹس ایپ: محمد یاسر حیات", "Online Shopping — Order from home": "آن لائن شاپنگ — گھر بیٹھے آرڈر کریں", "Order Your Daily Grocery Needs From Home": "اپنی روزمرہ کی گروسری گھر بیٹھے منگوائیں", "Browse our products, add them to your cart, and place your order — we'll deliver it right to your doorstep.": "ہماری مصنوعات دیکھیں، کارٹ میں ڈالیں اور آرڈر دیں — ہم آپ کے دروازے تک پہنچائیں گے۔", "📝 Send Your List": "📝 اپنی لسٹ بھیجیں", "🛍️ Cart": "🛍️ کارٹ", "👤 Login / Register": "👤 لاگ ان / رجسٹر", "🔐 Staff Login": "🔐 اسٹاف لاگ ان", "ATTR:🔍 Search products...": "🔍 پروڈکٹ تلاش کریں...", "Loading products...": "پروڈکٹس لوڈ ہو رہی ہیں...", "Loading...": "لوڈ ہو رہا ہے...", "No products found.": "کوئی پروڈکٹ نہیں ملی۔", "No products available yet.": "ابھی کوئی پروڈکٹ دستیاب نہیں۔", "Out of Stock": "اسٹاک ختم", "➕ Add to Cart": "➕ کارٹ میں ڈالیں", "🛍️ Aapki Cart": "🛍️ آپ کی کارٹ", "Cart khaali hai": "کارٹ خالی ہے", "Total": "کل", "Shopping Jari Rakhen": "خریداری جاری رکھیں", "Checkout": "چیک آؤٹ", "📦 Order Confirm Karen": "📦 آرڈر کنفرم کریں", "Delivery Address": "ڈیلیوری کا پتہ", "Note (optional)": "نوٹ (اختیاری)", "Total Payable": "کل قابلِ ادائیگی", "Cancel": "منسوخ", "Order Place Karen": "آرڈر دیں", "ATTR:e.g. deliver in the evening": "مثلاً شام کو ڈیلیور کریں", "Order Mil Gaya!": "آرڈر مل گیا!", "Aapka order number:": "آپ کا آرڈر نمبر:", "Hum jald hi aap se rabta karenge.": "ہم جلد آپ سے رابطہ کریں گے۔", "Mere Orders Dekhen": "میرے آرڈرز دیکھیں", "📜 Mere Orders": "📜 میرے آرڈرز", "Close": "بند کریں", "Login": "لاگ ان", "New Account": "نیا اکاؤنٹ", "Phone Number": "فون نمبر", "Password": "پاس ورڈ", "Aapka Naam": "آپ کا نام", "Address": "پتہ", "Area": "علاقہ", "Account Banayen": "اکاؤنٹ بنائیں", "Write Your List (optional)": "اپنی لسٹ لکھیں (اختیاری)", "Ya List ki Tasveer Lagayen (optional)": "یا لسٹ کی تصویر لگائیں (اختیاری)", "List Bhej Den": "لسٹ بھیج دیں", "No need to select every item — just write your grocery list or attach a photo. We will contact you.": "ہر آئٹم ایک ایک چننے کی ضرورت نہیں — بس اپنی گروسری/راشن کی لسٹ لکھ دیں، یا ایک تصویر لگائیں۔ ہم خود آپ سے رابطہ کر لیں گے۔", "ATTR:Masalan: 5 KG Atta, 1 KG Chini, 2 Cooking Oil...": "مثلاً: 5 کلو آٹا، 1 کلو چینی، 2 کوکنگ آئل...", "↩️ Return Policy": "↩️ ریٹرن پالیسی", "Return Policy": "ریٹرن پالیسی", "↩️ Return Request": "↩️ ریٹرن ریکوئسٹ", "Return Request": "ریٹرن ریکوئسٹ", "Wajah": "وجہ", "Kharab / toota hua": "خراب / ٹوٹا ہوا", "Expiry guzar chuki": "ایکسپائری گزر چکی", "Ghalat item aaya": "غلط آئٹم آیا", "Item kam aaya": "آئٹم کم آیا", "Quality theek nahi": "کوالٹی ٹھیک نہیں", "Aur wajah": "اور وجہ", "Tafseel (optional)": "تفصیل (اختیاری)", "Request Bhejen": "ریکوئسٹ بھیجیں", "Return Policy parhen": "ریٹرن پالیسی پڑھیں", "Policy:": "پالیسی:", "Theek Hai": "ٹھیک ہے", "Return facility within 48 hours of delivery —": "ڈیلیوری کے 48 گھنٹے میں ریٹرن کی سہولت —", "Pending": "زیرِ غور", "Confirmed": "کنفرم", "Dispatched": "روانہ", "Delivered": "پہنچ گیا", "Cancelled": "منسوخ", "Return: Pending": "ریٹرن: زیرِ غور", "Return: Approved": "ریٹرن: منظور", "Return: Rejected": "ریٹرن: مسترد", "Return: Saman utha liya": "ریٹرن: سامان اٹھا لیا گیا", "Return: Refunded": "ریٹرن: رقم واپس ہو گئی", "Return period over": "ریٹرن کی مدت ختم", "No orders yet.": "ابھی تک کوئی آرڈر نہیں ہے۔", "New Ghala Mandi Road, Khanpur": "نیو غلہ منڈی روڈ، خانپور", "📍 New Ghala Mandi Road, Khanpur | ☎": "📍 نیو غلہ منڈی روڈ، خانپور | ☎", "M. Faisal Hayat:": "محمد فیصل حیات:", "M. Yasir Hayat:": "محمد یاسر حیات:"};
const SHOP_NAME = "Mr Cash & Carry", SHOP_WA = "";
let LANG = 'en';
try { LANG = localStorage.getItem('store_lang') === 'ur' ? 'ur' : 'en'; } catch (e) {}
function _norm(t) { return String(t).replace(/\u00a0/g, ' ').replace(/\s+/g, ' ').trim(); }
function applyLang(root) {
  root = root || document.body;
  const ur = LANG === 'ur';
  const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
    acceptNode: n => (n.parentNode && /^(SCRIPT|STYLE|TEXTAREA)$/.test(n.parentNode.nodeName)) ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT });
  const nodes = []; let n; while ((n = walker.nextNode())) nodes.push(n);
  nodes.forEach(node => {
    // node ka text bahar se badal gaya (dynamic re-render) to purana record bhool jao
    if (node.__ur !== undefined && node.nodeValue !== node.__ur) { node.__orig = undefined; node.__ur = undefined; }
    if (node.__orig === undefined) {
      const k = _norm(node.nodeValue);
      if (!I18N_UR[k]) return;
      node.__orig = node.nodeValue; node.__key = k;
    }
    if (ur) { node.nodeValue = I18N_UR[node.__key]; node.__ur = node.nodeValue; }
    else { node.nodeValue = node.__orig; node.__ur = undefined; }
  });
  (root.querySelectorAll ? root.querySelectorAll('[placeholder]') : []).forEach(el => {
    if (el.__ph === undefined) { if (!I18N_UR['ATTR:' + el.getAttribute('placeholder')]) return; el.__ph = el.getAttribute('placeholder'); }
    el.setAttribute('placeholder', ur ? (I18N_UR['ATTR:' + el.__ph] || el.__ph) : el.__ph);
  });
}
function toggleLang() {
  LANG = LANG === 'ur' ? 'en' : 'ur';
  try { localStorage.setItem('store_lang', LANG); } catch (e) {}
  setLangUi();
}
function setLangUi() {
  document.documentElement.classList.toggle('ur-mode', LANG === 'ur');
  document.documentElement.dir = LANG === 'ur' ? 'rtl' : 'ltr';
  const b = document.getElementById('langBtn'); if (b) b.textContent = LANG === 'ur' ? '🌐 English' : '🌐 اردو';
  if (typeof renderProducts === 'function' && PRODUCTS && PRODUCTS.length) renderProducts();
  applyLang();
}
let _langBusy = false;
new MutationObserver(() => { if (LANG !== 'ur' || _langBusy) return; _langBusy = true; setTimeout(() => { applyLang(); _langBusy = false; }, 30); })
  .observe(document.body, { childList: true, subtree: true });
document.addEventListener('DOMContentLoaded', () => { if (LANG === 'ur') setLangUi(); });
</script>
<script src="store-app.js?v=20261104a"></script>
<script>if ("serviceWorker" in navigator) window.addEventListener("load", function () { navigator.serviceWorker.register("sw.js").catch(function () {}); });</script>
</body>
</html>
