<?php
$pageTitle   = 'Accessories';
$currentPage = 'accessories';
require_once __DIR__ . '/backend/includes/head.php';
require_once __DIR__ . '/backend/includes/navbar.php';

require_once __DIR__ . '/backend/config/database.php';

// Check for success state
$success = isset($_GET['success']) && $_GET['success'] === '1';

$db   = getDB();
$stmt = $db->prepare("SELECT id,name,price,description,image_url,stock FROM products WHERE category='accessory' AND is_active=1 ORDER BY created_at DESC");
$stmt->execute();
$accessories  = $stmt->fetchAll(PDO::FETCH_ASSOC);
$totalCount   = count($accessories);
$inStockCount = count(array_filter($accessories, fn($a) => (int)($a['stock'] ?? 0) > 0));
?>

<style>
@keyframes fadeInUp {
  from { opacity:0; transform:translateY(22px); }
  to   { opacity:1; transform:translateY(0);    }
}
@keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
@keyframes spin   { to   { transform:rotate(360deg); } }

.fade-in-up { animation: fadeInUp .55s ease both; }
.fade-in    { animation: fadeIn   .4s  ease both; }

.acc-card {
  transition: transform .22s ease, box-shadow .22s ease;
  animation: fadeInUp .5s ease both;
}
.acc-card:hover {
  transform: translateY(-6px);
  box-shadow: 0 16px 40px rgba(0,0,0,.12) !important;
}

.btn-add {
  display:inline-flex; align-items:center; justify-content:center; gap:.45rem;
  background:linear-gradient(135deg,#f97316,#fb923c);
  color:#fff; border:none; border-radius:12px;
  padding:.6rem 1rem; font-weight:800; font-size:.85rem;
  cursor:pointer; width:100%; transition:all .2s;
  box-shadow:0 4px 14px rgba(249,115,22,.3);
}
.btn-add:hover:not(:disabled) {
  transform:translateY(-1px);
  box-shadow:0 6px 20px rgba(249,115,22,.45);
}
.btn-add:disabled {
  background:linear-gradient(135deg,#cbd5e1,#94a3b8);
  box-shadow:none; cursor:not-allowed; opacity:.75;
}

.stock-badge {
  display:inline-flex; align-items:center; gap:.3rem;
  font-size:.68rem; font-weight:700;
  padding:.22rem .6rem; border-radius:20px;
  position:absolute; top:.7rem; right:.7rem;
}
.stock-in  { background:#f0fdf4; border:1px solid #bbf7d0; color:#15803d; }
.stock-out { background:#fef2f2; border:1px solid #fecaca; color:#dc2626; }

.sort-btn { transition:all .2s; }
.active-sort-btn {
  background:linear-gradient(135deg,#0f172a,#1e293b) !important;
  color:#fff !important;
}

.search-wrap { position:relative; flex:1 1 240px; max-width:360px; }
.search-wrap svg { position:absolute; left:.9rem; top:50%; transform:translateY(-50%); pointer-events:none; }
.search-wrap input { padding-left:2.6rem !important; }

.cart-item-row { animation: fadeInUp .3s ease both; }
</style>

<!-- ═══ HERO ═══ -->
<section class="fade-in" style="background:linear-gradient(145deg,#0f172a 0%,#1e293b 60%,#0f172a 100%);padding:5rem 0 4rem;position:relative;overflow:hidden">
  <div style="position:absolute;inset:0;background-image:radial-gradient(circle,rgba(255,255,255,.025) 1px,transparent 1px);background-size:28px 28px;pointer-events:none"></div>
  <div style="position:absolute;top:-80px;right:-80px;width:380px;height:380px;background:radial-gradient(circle,rgba(249,115,22,.13) 0%,transparent 70%);pointer-events:none"></div>
  <div style="position:absolute;bottom:-60px;left:-60px;width:280px;height:280px;background:radial-gradient(circle,rgba(251,191,36,.07) 0%,transparent 70%);pointer-events:none"></div>

  <div style="max-width:860px;margin:0 auto;padding:0 1.5rem;text-align:center;position:relative">
    <div style="display:inline-flex;align-items:center;gap:.5rem;background:rgba(249,115,22,.15);border:1px solid rgba(249,115,22,.3);border-radius:50px;padding:.4rem 1.1rem;margin-bottom:1.75rem">
      <svg width="13" height="13" fill="none" stroke="#f97316" stroke-width="2.2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"/></svg>
      <span style="color:#f97316;font-size:.78rem;font-weight:700;letter-spacing:.09em">LPG ACCESSORIES</span>
    </div>

    <h1 style="color:#fff;font-weight:900;font-size:clamp(2rem,5vw,3rem);line-height:1.1;margin-bottom:1.25rem">
      Quality <span style="background:linear-gradient(90deg,#f97316,#fbbf24);-webkit-background-clip:text;-webkit-text-fill-color:transparent">Gas Accessories</span>
    </h1>
    <p style="color:#94a3b8;font-size:1.05rem;line-height:1.7;max-width:560px;margin:0 auto 2rem">
      Browse our certified regulators, hoses, stoves and fittings. Add to cart — pay cash on delivery.
    </p>

    <div style="display:inline-flex;gap:2rem;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.08);border-radius:16px;padding:.85rem 2rem">
      <div style="text-align:center">
        <div style="color:#f97316;font-weight:900;font-size:1.4rem"><?= $totalCount ?></div>
        <div style="color:#64748b;font-size:.72rem;font-weight:600;letter-spacing:.05em">PRODUCTS</div>
      </div>
      <div style="width:1px;background:rgba(255,255,255,.08)"></div>
      <div style="text-align:center">
        <div style="color:#22c55e;font-weight:900;font-size:1.4rem"><?= $inStockCount ?></div>
        <div style="color:#64748b;font-size:.72rem;font-weight:600;letter-spacing:.05em">IN STOCK</div>
      </div>
      <div style="width:1px;background:rgba(255,255,255,.08)"></div>
      <div style="text-align:center">
        <div style="color:#38bdf8;font-weight:900;font-size:1.4rem">COD</div>
        <div style="color:#64748b;font-size:.72rem;font-weight:600;letter-spacing:.05em">PAYMENT</div>
      </div>
    </div>
  </div>
</section>

<?php if($success): ?>
<!-- ═══ SUCCESS STATE ═══ -->
<section style="max-width:1100px;margin:0 auto;padding:4rem 1.5rem;position:relative;z-index:1">
  <div style="display:flex;align-items:center;justify-content:center;min-height:50vh">
    <div style="background:#fff;border-radius:24px;padding:3.5rem 2.5rem;max-width:480px;width:100%;text-align:center;box-shadow:0 8px 40px rgba(0,0,0,.1)">
      <div style="width:80px;height:80px;border-radius:50%;background:linear-gradient(135deg,#22c55e,#16a34a);display:flex;align-items:center;justify-content:center;margin:0 auto 1.5rem;box-shadow:0 8px 24px rgba(34,197,94,.35)">
        <svg width="40" height="40" fill="none" stroke="#fff" stroke-width="2.5" viewBox="0 0 24 24"><polyline stroke-linecap="round" stroke-linejoin="round" points="20 6 9 17 4 12"/></svg>
      </div>
      <h2 style="color:#0f172a;font-weight:900;font-size:1.6rem;margin:0 0 .75rem">Order Placed!</h2>
      <p style="color:#64748b;line-height:1.7;margin:0 0 2rem">Your accessories order has been received. We'll contact you to confirm delivery details.</p>
      <a href="/stile-lpg/accessories.php" class="btn-primary" style="display:inline-flex;align-items:center;justify-content:center;gap:.5rem;background:linear-gradient(135deg,#f97316,#fb923c);color:#fff;border:none;border-radius:12px;padding:.75rem 1.75rem;font-weight:800;font-size:.9rem;text-decoration:none;cursor:pointer;transition:all .2s;box-shadow:0 4px 14px rgba(249,115,22,.3)">
        <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"/></svg>
        Continue Shopping
      </a>
    </div>
  </div>
</section>
<?php else: ?>

<!-- ═══ TOOLBAR ═══ -->
<section style="max-width:1100px;margin:2rem auto 0;padding:0 1.5rem">
  <div style="display:flex;align-items:center;justify-content:space-between;gap:1rem;flex-wrap:wrap">
    <div class="search-wrap">
      <svg width="16" height="16" fill="none" stroke="#94a3b8" stroke-width="2" viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><path stroke-linecap="round" d="m21 21-4.35-4.35"/></svg>
      <input type="text" id="search_input" placeholder="Search accessories…" class="input-field" style="border:2px solid #e2e8f0;border-radius:50px" oninput="filterProducts()">
    </div>
    <div style="display:flex;gap:.5rem;flex-wrap:wrap">
      <button onclick="setSortBtn(this,'default')" class="sort-btn active-sort-btn" style="background:linear-gradient(135deg,#0f172a,#1e293b);color:#fff;border:none;padding:.5rem 1.1rem;border-radius:50px;font-weight:700;font-size:.82rem;cursor:pointer;display:inline-flex;align-items:center;gap:.4rem">
        <svg width="13" height="13" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 12h16M4 18h16"/></svg>Default
      </button>
      <button onclick="setSortBtn(this,'asc')" class="sort-btn" style="background:#f1f5f9;color:#475569;border:none;padding:.5rem 1.1rem;border-radius:50px;font-weight:700;font-size:.82rem;cursor:pointer;display:inline-flex;align-items:center;gap:.4rem">
        <svg width="13" height="13" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 4h13M3 8h9m-9 4h6m4 0l4-4m0 0l4 4m-4-4v12"/></svg>Price Low
      </button>
      <button onclick="setSortBtn(this,'desc')" class="sort-btn" style="background:#f1f5f9;color:#475569;border:none;padding:.5rem 1.1rem;border-radius:50px;font-weight:700;font-size:.82rem;cursor:pointer;display:inline-flex;align-items:center;gap:.4rem">
        <svg width="13" height="13" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 4h13M3 8h9m-9 4h9m5-4v12m0 0l-4-4m4 4l4-4"/></svg>Price High
      </button>
    </div>
  </div>
</section>

<!-- ═══ PRODUCT GRID ═══ -->
<section style="max-width:1100px;margin:2rem auto 5rem;padding:0 1.5rem">
  <div id="product_grid" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:1.5rem">

    <?php foreach($accessories as $i => $acc):
      $stock   = (int)($acc['stock'] ?? 0);
      $inStock = $stock > 0;
      $delay   = ($i % 4) * 0.08;
    ?>
    <div class="acc-card anim-fade-up"
         data-name="<?= htmlspecialchars(strtolower($acc['name'])) ?>"
         data-price="<?= $acc['price'] ?>"
         data-stock="<?= $stock ?>"
         style="background:#fff;border-radius:20px;overflow:hidden;border:1px solid #e2e8f0;box-shadow:0 2px 12px rgba(0,0,0,.06);animation-delay:<?= $delay ?>s">

      <!-- Image -->
      <div style="height:190px;background:linear-gradient(135deg,#f8fafc,#e2e8f0);position:relative;overflow:hidden">
        <?php if($acc['image_url']): ?>
        <img src="<?= htmlspecialchars($acc['image_url']) ?>" alt="<?= htmlspecialchars($acc['name']) ?>"
             style="width:100%;height:100%;object-fit:cover;transition:transform .4s ease"
             onmouseover="this.style.transform='scale(1.05)'" onmouseout="this.style.transform='scale(1)'">
        <?php else: ?>
        <div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center">
          <svg width="56" height="56" fill="none" stroke="#cbd5e1" stroke-width="1.2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M20 7H4a2 2 0 00-2 2v6a2 2 0 002 2h16a2 2 0 002-2V9a2 2 0 00-2-2zM16 21V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v16"/></svg>
        </div>
        <?php endif; ?>

        <!-- Stock badge -->
        <span class="stock-badge <?= $inStock ? 'stock-in' : 'stock-out' ?>">
          <?php if($inStock): ?>
          <svg width="8" height="8" viewBox="0 0 8 8"><circle cx="4" cy="4" r="4" fill="#16a34a"/></svg>In Stock
          <?php else: ?>
          <svg width="8" height="8" viewBox="0 0 8 8"><circle cx="4" cy="4" r="4" fill="#dc2626"/></svg>Out of Stock
          <?php endif; ?>
        </span>
      </div>

      <!-- Info -->
      <div style="padding:1.2rem">
        <div style="display:inline-flex;align-items:center;gap:.35rem;font-size:.68rem;font-weight:700;color:#f97316;letter-spacing:.07em;text-transform:uppercase;margin-bottom:.4rem">
          <svg width="10" height="10" fill="none" stroke="#f97316" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
          LPG Accessory
        </div>
        <h3 style="color:#0f172a;font-weight:800;font-size:.97rem;margin:0 0 .35rem;line-height:1.35"><?= htmlspecialchars($acc['name']) ?></h3>
        <?php if(!empty($acc['description'])): ?>
        <p style="color:#64748b;font-size:.8rem;margin:0 0 .9rem;line-height:1.55;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden"><?= htmlspecialchars($acc['description']) ?></p>
        <?php endif; ?>

        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:.9rem">
          <span style="color:#f97316;font-weight:900;font-size:1.2rem">₦<?= number_format($acc['price']) ?></span>
          <?php if($inStock): ?>
          <span style="color:#64748b;font-size:.75rem;font-weight:600"><?= $stock ?> left</span>
          <?php endif; ?>
        </div>

        <?php if($inStock): ?>
        <button onclick="addToCart('<?= $acc['id'] ?>','<?= htmlspecialchars(addslashes($acc['name'])) ?>',<?= $acc['price'] ?>,<?= $stock ?>)"
                class="btn-add">
          <svg width="15" height="15" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"/></svg>
          Add to Cart
        </button>
        <?php else: ?>
        <button class="btn-add" disabled>
          <svg width="15" height="15" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"/></svg>
          Out of Stock
        </button>
        <?php endif; ?>
      </div>
    </div>
    <?php endforeach; ?>

    <?php if(empty($accessories)): ?>
    <div style="grid-column:1/-1;text-align:center;padding:5rem 1rem" class="fade-in">
      <svg width="64" height="64" fill="none" stroke="#cbd5e1" stroke-width="1.2" viewBox="0 0 24 24" style="margin:0 auto 1rem;display:block"><path stroke-linecap="round" stroke-linejoin="round" d="M20 7H4a2 2 0 00-2 2v6a2 2 0 002 2h16a2 2 0 002-2V9a2 2 0 00-2-2zM16 21V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v16"/></svg>
      <p style="color:#94a3b8;font-size:1rem">No accessories available right now.</p>
    </div>
    <?php endif; ?>

  </div>
</section>

<?php endif; ?>

<!-- ═══ CART OVERLAY ═══ -->
<div id="cart_overlay" onclick="closeCart()" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.55);z-index:100;backdrop-filter:blur(4px);animation:fadeIn .25s ease"></div>

<!-- ═══ CART DRAWER ═══ -->
<aside id="cart_drawer" style="position:fixed;top:0;right:-460px;width:440px;max-width:100vw;height:100vh;background:#fff;z-index:101;box-shadow:-8px 0 48px rgba(0,0,0,.18);transition:right .35s cubic-bezier(.4,0,.2,1);display:flex;flex-direction:column;overflow:hidden">

  <!-- Drawer Header -->
  <div style="background:linear-gradient(135deg,#0f172a,#1e293b);padding:1.4rem 1.5rem;display:flex;align-items:center;justify-content:space-between;flex-shrink:0">
    <div style="display:flex;align-items:center;gap:.75rem">
      <div style="width:42px;height:42px;border-radius:12px;background:linear-gradient(135deg,#f97316,#fb923c);display:flex;align-items:center;justify-content:center">
        <svg width="20" height="20" fill="none" stroke="#fff" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"/></svg>
      </div>
      <div>
        <div style="color:#fff;font-weight:800;font-size:1rem">Your Cart</div>
        <div style="color:#64748b;font-size:.75rem"><span id="cart_items_count">0</span> items</div>
      </div>
    </div>
    <button onclick="closeCart()" style="background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.1);color:#94a3b8;width:36px;height:36px;border-radius:10px;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all .2s" onmouseover="this.style.background='rgba(255,255,255,.15)'" onmouseout="this.style.background='rgba(255,255,255,.08)'">
      <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
    </button>
  </div>

  <!-- Cart Items -->
  <div id="cart_items_list" style="flex:1;overflow-y:auto;padding:1.25rem"></div>

  <!-- Checkout Footer -->
  <div style="padding:1.25rem;border-top:2px solid #f1f5f9;background:#fafafa;flex-shrink:0">
    <div style="margin-bottom:1rem">
      <label style="color:#475569;font-weight:700;font-size:.72rem;letter-spacing:.07em;text-transform:uppercase;display:block;margin-bottom:.5rem">Fulfillment</label>
      <select id="cart_fulfillment" class="input-field" style="border:2px solid #e2e8f0;border-radius:12px" onchange="toggleCartAddress()">
        <option value="delivery">Delivery</option>
        <option value="pickup">Pickup</option>
      </select>
    </div>
    <div id="cart_address_row" style="margin-bottom:1rem">
      <label style="color:#475569;font-weight:700;font-size:.72rem;letter-spacing:.07em;text-transform:uppercase;display:block;margin-bottom:.5rem">Delivery Address</label>
      <input type="text" id="cart_address" placeholder="Your full delivery address" class="input-field" style="border:2px solid #e2e8f0;border-radius:12px">
    </div>
    <div style="margin-bottom:1rem">
      <label style="color:#475569;font-weight:700;font-size:.72rem;letter-spacing:.07em;text-transform:uppercase;display:block;margin-bottom:.5rem">Phone Number <span style="color:#dc2626">*</span></label>
      <input type="tel" id="cart_phone" placeholder="e.g. +234 800 000 0000" class="input-field" style="border:2px solid #e2e8f0;border-radius:12px" oninput="this.value=this.value.replace(/[^0-9+\s\-()]/g,'')">
    </div>
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:1rem">
      <div>
        <div style="color:#94a3b8;font-size:.7rem;font-weight:700;letter-spacing:.06em">ORDER TOTAL</div>
        <div id="cart_total_display" style="color:#f97316;font-weight:900;font-size:1.6rem;line-height:1.1">₦0</div>
      </div>
      <div style="display:flex;align-items:center;gap:.4rem;background:#f0fdf4;border:1px solid #bbf7d0;border-radius:20px;padding:.4rem .9rem">
        <svg width="15" height="15" fill="none" stroke="#15803d" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z"/></svg>
        <span style="color:#15803d;font-weight:700;font-size:.75rem">Cash on Delivery</span>
      </div>
    </div>
    <button onclick="placeCartOrder()" id="cart_place_btn" class="btn-primary" style="width:100%;justify-content:center;font-size:.92rem;padding:.85rem 1rem;border-radius:14px;display:flex;align-items:center;gap:.5rem">
      <svg width="17" height="17" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
      Place Order
    </button>
    <div id="cart_error"   style="color:#dc2626;font-size:.8rem;margin-top:.6rem;text-align:center;display:none"></div>
    <div id="cart_success" style="color:#16a34a;font-size:.85rem;margin-top:.6rem;text-align:center;font-weight:700;display:none"></div>
  </div>
</aside>

<!-- ═══ FLOATING CART FAB ═══ -->
<button id="open_cart_fab" onclick="openCart()" style="display:none;position:fixed;bottom:2rem;right:2rem;background:linear-gradient(135deg,#f97316,#fb923c);color:#fff;border:none;width:58px;height:58px;border-radius:50%;cursor:pointer;box-shadow:0 8px 28px rgba(249,115,22,.5);z-index:50;align-items:center;justify-content:center;transition:transform .2s,box-shadow .2s" onmouseover="this.style.transform='scale(1.1)';this.style.boxShadow='0 12px 36px rgba(249,115,22,.6)'" onmouseout="this.style.transform='scale(1)';this.style.boxShadow='0 8px 28px rgba(249,115,22,.5)'">
  <svg width="24" height="24" fill="none" stroke="#fff" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"/></svg>
  <span id="fab_badge" style="position:absolute;top:-4px;right:-4px;background:#dc2626;color:#fff;font-size:.62rem;font-weight:800;width:20px;height:20px;border-radius:50%;display:flex;align-items:center;justify-content:center;border:2px solid #fff">0</span>
</button>

<script>
<?php
$sessionToken = $_SESSION['jwt_token'] ?? '';
$isLoggedIn   = !empty($_SESSION['user_id']);
?>
const SESSION_TOKEN = <?= json_encode($sessionToken) ?>;
const IS_LOGGED_IN  = <?= $isLoggedIn ? 'true' : 'false' ?>;

let cart = {};

// Load cart from localStorage on page load
function loadCartFromStorage() {
  try {
    const savedCart = localStorage.getItem('stilesLPG_cart');
    if (savedCart) {
      cart = JSON.parse(savedCart);
      updateCartUI();
    }
  } catch(e) {
    console.error('Error loading cart:', e);
  }
}

// Save cart to localStorage whenever it changes
function saveCartToStorage() {
  try {
    localStorage.setItem('stilesLPG_cart', JSON.stringify(cart));
  } catch(e) {
    console.error('Error saving cart:', e);
  }
}

// Clear cart from localStorage
function clearCartStorage() {
  try {
    localStorage.removeItem('stilesLPG_cart');
  } catch(e) {
    console.error('Error clearing cart:', e);
  }
}

// Load cart when page loads
window.addEventListener('DOMContentLoaded', function() {
  loadCartFromStorage();
});

function addToCart(id, name, price, stock){
  const maxStock = parseInt(stock) || 0;
  if(maxStock === 0) return;
  if(cart[id]){
    if(cart[id].qty >= maxStock){
      showCartError('Only ' + maxStock + ' unit(s) available for "' + name + '".');
      return;
    }
    cart[id].qty++;
  } else {
    cart[id] = { id, name, price, stock: maxStock, qty: 1 };
  }
  saveCartToStorage();
  updateCartUI();
}

function removeFromCart(id){
  delete cart[id];
  saveCartToStorage();
  updateCartUI();
}

function changeQty(id, delta){
  if(!cart[id]) return;
  const newQty = cart[id].qty + delta;
  if(newQty <= 0){ removeFromCart(id); return; }
  if(newQty > cart[id].stock){
    showCartError('Only ' + cart[id].stock + ' unit(s) in stock.');
    return;
  }
  cart[id].qty = newQty;
  saveCartToStorage();
  updateCartUI();
}

function showCartError(msg){
  const el = document.getElementById('cart_error');
  el.textContent = msg; el.style.display = 'block';
  setTimeout(() => { el.style.display = 'none'; }, 3500);
}

function updateCartUI(){
  const items = Object.values(cart);
  const total = items.reduce((s,i) => s + i.price * i.qty, 0);
  const count = items.reduce((s,i) => s + i.qty, 0);

  document.getElementById('cart_items_count').textContent   = count;
  document.getElementById('cart_total_display').textContent = '₦' + total.toLocaleString();
  document.getElementById('fab_badge').textContent          = count;

  const fab = document.getElementById('open_cart_fab');
  fab.style.display = count > 0 ? 'flex' : 'none';

  const list = document.getElementById('cart_items_list');
  if(items.length === 0){
    list.innerHTML = `
      <div style="text-align:center;padding:3.5rem 1rem;color:#94a3b8">
        <svg width="56" height="56" fill="none" stroke="#e2e8f0" stroke-width="1.5" viewBox="0 0 24 24" style="margin:0 auto 1rem;display:block"><path stroke-linecap="round" stroke-linejoin="round" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"/></svg>
        <p style="font-weight:600;font-size:.95rem">Your cart is empty</p>
        <p style="font-size:.8rem;margin-top:.4rem">Tap "Add to Cart" on any in-stock product</p>
      </div>`;
    return;
  }

  list.innerHTML = items.map(item => `
    <div class="cart-item-row" style="display:flex;align-items:center;gap:.85rem;padding:.9rem 0;border-bottom:1px solid #f1f5f9">
      <div style="width:44px;height:44px;border-radius:12px;background:linear-gradient(135deg,#fff7ed,#ffedd5);display:flex;align-items:center;justify-content:center;flex-shrink:0">
        <svg width="20" height="20" fill="none" stroke="#f97316" stroke-width="1.8" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M20 7H4a2 2 0 00-2 2v6a2 2 0 002 2h16a2 2 0 002-2V9a2 2 0 00-2-2zM16 21V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v16"/></svg>
      </div>
      <div style="flex:1;min-width:0">
        <div style="font-weight:700;font-size:.875rem;color:#0f172a;overflow:hidden;white-space:nowrap;text-overflow:ellipsis">${item.name}</div>
        <div style="color:#f97316;font-weight:700;font-size:.8rem;margin-top:.15rem">₦${item.price.toLocaleString()} each</div>
      </div>
      <div style="display:flex;align-items:center;gap:.4rem">
        <button onclick="changeQty('${item.id}',-1)" style="width:28px;height:28px;border-radius:8px;background:#f1f5f9;border:1px solid #e2e8f0;cursor:pointer;display:flex;align-items:center;justify-content:center">
          <svg width="12" height="12" fill="none" stroke="#475569" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" d="M5 12h14"/></svg>
        </button>
        <span style="font-weight:800;font-size:.9rem;min-width:20px;text-align:center">${item.qty}</span>
        <button onclick="changeQty('${item.id}',1)" style="width:28px;height:28px;border-radius:8px;background:linear-gradient(135deg,#f97316,#fb923c);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center">
          <svg width="12" height="12" fill="none" stroke="#fff" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" d="M12 5v14M5 12h14"/></svg>
        </button>
        <button onclick="removeFromCart('${item.id}')" style="width:28px;height:28px;border-radius:8px;background:#fef2f2;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;margin-left:.15rem">
          <svg width="13" height="13" fill="none" stroke="#dc2626" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
        </button>
      </div>
    </div>`).join('');
}

function openCart(){
  document.getElementById('cart_drawer').style.right  = '0';
  document.getElementById('cart_overlay').style.display = 'block';
}
function closeCart(){
  document.getElementById('cart_drawer').style.right  = '-460px';
  document.getElementById('cart_overlay').style.display = 'none';
}
function toggleCartAddress(){
  document.getElementById('cart_address_row').style.display =
    document.getElementById('cart_fulfillment').value === 'delivery' ? 'block' : 'none';
}

function setSortBtn(el, mode){
  document.querySelectorAll('.sort-btn').forEach(b => {
    b.classList.remove('active-sort-btn');
    b.style.background = '#f1f5f9'; b.style.color = '#475569';
  });
  el.classList.add('active-sort-btn');
  el.style.background = 'linear-gradient(135deg,#0f172a,#1e293b)';
  el.style.color = '#fff';
  sortProducts(mode);
}

function sortProducts(mode){
  const grid  = document.getElementById('product_grid');
  const cards = Array.from(document.querySelectorAll('.acc-card'));
  if(mode === 'asc')  cards.sort((a,b) => parseFloat(a.dataset.price) - parseFloat(b.dataset.price));
  if(mode === 'desc') cards.sort((a,b) => parseFloat(b.dataset.price) - parseFloat(a.dataset.price));
  cards.forEach(c => grid.appendChild(c));
}

function filterProducts(){
  const q = document.getElementById('search_input').value.toLowerCase();
  document.querySelectorAll('.acc-card').forEach(c => {
    c.style.display = c.dataset.name.includes(q) ? '' : 'none';
  });
}

function placeCartOrder(){
  const items = Object.values(cart);
  if(items.length === 0) return;

  if(!IS_LOGGED_IN || !SESSION_TOKEN){
    window.location.href = '/stile-lpg/login.php?redirect=accessories';
    return;
  }

  const fulfillment = document.getElementById('cart_fulfillment').value;
  const address     = document.getElementById('cart_address').value.trim();
  const phone       = document.getElementById('cart_phone').value.trim();
  const errEl       = document.getElementById('cart_error');
  const successEl   = document.getElementById('cart_success');
  errEl.style.display = 'none'; successEl.style.display = 'none';

  if(fulfillment === 'delivery' && !address){
    errEl.textContent = 'Please enter your delivery address.';
    errEl.style.display = 'block'; return;
  }
  if(!phone){
    errEl.textContent = 'Phone number is required.';
    errEl.style.display = 'block'; return;
  }

  const btn = document.getElementById('cart_place_btn');
  btn.disabled = true;
  btn.innerHTML = `<svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24" style="animation:spin 1s linear infinite"><path stroke-linecap="round" d="M12 2a10 10 0 0110 10"/></svg>&nbsp;Placing order…`;

  const total      = items.reduce((s,i) => s + i.price * i.qty, 0);
  const orderItems = items.map(i => ({ productId:i.id, productName:i.name, quantity:i.qty, price:i.price }));

  fetch('/stile-lpg/backend/api/customer/orders/place-order', {
    method:'POST',
    headers:{ 'Content-Type':'application/json', 'Authorization':'Bearer ' + SESSION_TOKEN },
    body: JSON.stringify({ items:orderItems, total, fulfillment, address, phone, notes:'', paymentMethod:'cod' })
  })
  .then(r => r.json().then(data => ({ ok:r.ok, status:r.status, data })))
  .then(({ ok, data, status }) => {
    if(ok || data.message || data.order_id || data.id){
      clearCartStorage();
      cart = {};
      // Redirect to success page
      window.location.href = '/stile-lpg/accessories.php?success=1';
    } else {
      errEl.textContent = data.error || ('Server error ' + status);
      errEl.style.display = 'block';
      btn.disabled = false;
      btn.innerHTML = `<svg width="17" height="17" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>&nbsp;Place Order`;
    }
  })
  .catch(err => {
    console.error('Order error:', err);
    errEl.textContent = 'Request failed: ' + err.message;
    errEl.style.display = 'block';
    btn.disabled = false;
    btn.innerHTML = `<svg width="17" height="17" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>&nbsp;Place Order`;
  });
}

updateCartUI();
</script>

<?php require_once __DIR__ . '/backend/includes/footer.php'; ?>
