<?php
require_once __DIR__ . '/../includes/config.php';

$handle = clean($_GET['h'] ?? '');
if (!$handle) { header('Location: /catalogue.php'); exit; }

/* ---- load product (lookup table, then direct filename fallback) ---- */
$product    = null;
$lookupPath = '/var/www/gctrade68/product_files/lookup.json';
$filesDir   = '/var/www/gctrade68/product_files/';

if (file_exists($lookupPath)) {
    $lookup = json_decode(file_get_contents($lookupPath), true) ?: [];
    if (isset($lookup[$handle])) {
        $file = $filesDir . $lookup[$handle];
        if (file_exists($file)) $product = json_decode(file_get_contents($file), true);
    }
}
if (!$product) {
    $safe   = preg_replace('/-+/', '-', preg_replace('/[^\w\-]/', '-', $handle));
    $direct = $filesDir . $safe . '.json';
    if (file_exists($direct)) $product = json_decode(file_get_contents($direct), true);
}

if (!$product) {
    http_response_code(404);
    $page_title = 'Product not found — GC Trade 68';
    include __DIR__ . '/../includes/header.php';
    echo '<section class="wrap" style="text-align:center;padding:90px 20px">
            <h1 class="display" style="font-size:2.2rem">Product not found</h1>
            <p style="color:var(--ink-soft);margin:12px 0 22px">This item may no longer be available, or the link is incorrect.</p>
            <a class="btn btn--dark" href="/catalogue.php">Browse the catalogue</a>
          </section>';
    include __DIR__ . '/../includes/footer.php';
    exit;
}

$variantsJson = json_encode($product['variants'] ?? []);
$coloursJson  = json_encode($product['colours']  ?? []);
$hasColours   = !empty($product['colours']) && ($product['colours'][0] ?? '') !== 'Standard';
$hasSizes     = !empty($product['sizes']);
$hasLogo      = $product['has_logo'] ?? false;
$imgs         = $product['imgs'] ?? ($product['img'] ? [$product['img']] : []);

$gcU    = currentUser();
$isBiz  = $gcU && isBusinessAccount($gcU);
$addFn  = $isBiz ? 'addToQuoteFull' : 'addToCartFull';
$addTxt = $isBiz ? 'Add to quote'   : 'Add to basket';
$addCls = $isBiz ? 'btn--mint'      : 'btn--dark';

$colMap = ['black'=>'#141414','white'=>'#f4f2ec','navy'=>'#0a1628','red'=>'#dc2626','blue'=>'#1d4ed8','green'=>'#15803d','grey'=>'#6b7280','gray'=>'#6b7280','yellow'=>'#eab308','orange'=>'#f97316','purple'=>'#7c3aed','pink'=>'#ec4899','brown'=>'#78350f','khaki'=>'#a3824a','bottle'=>'#014421','royal'=>'#2563eb','burgundy'=>'#7f1d1d','charcoal'=>'#374151','teal'=>'#0f766e','lime'=>'#65a30d','turquoise'=>'#0e7490','gold'=>'#d97706','silver'=>'#9ca3af','cream'=>'#fef3c7','beige'=>'#d9c9a3','forest'=>'#166534','maroon'=>'#7f1d1d','magenta'=>'#c026d3','coral'=>'#f97316','kelly'=>'#4d9e4d','jade'=>'#00a86b','graphite'=>'#4b5563','cardinal'=>'#c41e3a','heather'=>'#8b7d7b'];

$page_title = $product['title'] . ' — GC Trade 68';
$active_nav = 'catalogue';
include __DIR__ . '/../includes/header.php';
?>
<style>
.pdp { padding: clamp(20px,3vw,36px) 0 var(--section-y); }
.pdp-crumb { font-size: .78rem; color: var(--ink-soft); margin-bottom: 20px; display: flex; gap: 8px; flex-wrap: wrap; }
.pdp-crumb a { font-weight: 600; }
.pdp-grid { display: grid; grid-template-columns: 1fr 1fr; gap: clamp(24px,3vw,48px); align-items: start; }
.pdp-main-img { position: relative; overflow: hidden; aspect-ratio: 1; display: grid; place-items: center; background: linear-gradient(160deg,#F6E7D4,#F3D9BE); }
.pdp-main-img img { width: 82%; height: 82%; object-fit: contain; mix-blend-mode: multiply; }
.pdp-main-img .ph { font-size: 90px; }
.pdp-thumbs { display: flex; gap: 10px; margin-top: 12px; flex-wrap: wrap; }
.pdp-thumb { width: 68px; height: 68px; border: var(--bw) solid var(--line); border-radius: var(--r-sm); overflow: hidden; background: var(--paper); display: grid; place-items: center; cursor: pointer; }
.pdp-thumb.active { outline: 3px solid var(--orange); outline-offset: 1px; }
.pdp-thumb img { width: 100%; height: 100%; object-fit: contain; padding: 4px; }
.pdp-vendor { font-weight: 700; font-size: .68rem; letter-spacing: .16em; text-transform: uppercase; color: var(--ink-soft); }
.pdp-title { font-family: var(--font-display); font-weight: 900; text-transform: uppercase; letter-spacing: -.01em; line-height: 1; font-size: clamp(1.7rem,3.2vw,2.6rem); margin: 8px 0 16px; }
.pdp-price { font-family: var(--font-display); font-weight: 900; color: var(--orange); font-size: 2.1rem; line-height: 1; }
.pdp-price small { font-family: var(--font-body); font-weight: 600; font-size: .8rem; color: var(--ink-soft); }
.pdp-note { font-size: .78rem; color: var(--ink-soft); margin-top: 4px; }
.opt-label { font-weight: 800; font-size: .72rem; letter-spacing: .1em; text-transform: uppercase; margin: 22px 0 10px; }
.opt-label span { color: var(--orange); text-transform: none; letter-spacing: 0; }
.swatches { display: flex; flex-wrap: wrap; gap: 8px; }
.swatch { display: inline-flex; align-items: center; gap: 7px; padding: 8px 14px; border: var(--bw) solid var(--line); border-radius: var(--pill); background: var(--paper); font-weight: 600; font-size: .82rem; cursor: pointer; transition: transform .1s ease; }
.swatch:hover { transform: translateY(-1px); }
.swatch.selected { background: var(--ink); color: #fff; }
.swatch .sd { width: 13px; height: 13px; border-radius: 50%; border: 1px solid rgba(0,0,0,.2); flex: none; }
.sizes { display: flex; flex-wrap: wrap; gap: 8px; }
.size-btn { min-width: 46px; padding: 9px 12px; border: var(--bw) solid var(--line); border-radius: var(--r-sm); background: var(--paper); font-weight: 700; font-size: .85rem; cursor: pointer; text-align: center; }
.size-btn.selected { background: var(--orange); color: var(--ink); }
.size-btn.unavailable { opacity: .3; cursor: not-allowed; }
.qty-row { display: flex; align-items: center; gap: 10px; margin: 22px 0 16px; }
.qty-row .lbl { font-weight: 700; font-size: .8rem; }
.qbtn { width: 40px; height: 40px; border: var(--bw) solid var(--line); border-radius: var(--r-sm); background: var(--paper); font-size: 18px; font-weight: 800; cursor: pointer; }
.qin { width: 64px; text-align: center; padding: 9px; border: var(--bw) solid var(--line); border-radius: var(--r-sm); font-weight: 700; font-size: 1rem; outline: none; }
.big-add { width: 100%; justify-content: center; font-size: 1rem; padding: 16px; }
.big-add:disabled { opacity: .45; cursor: not-allowed; }
.wish-btn { width: 100%; justify-content: center; margin-top: 10px; background: var(--paper); }
.pdp-success { display: none; background: var(--mint); border: var(--bw) solid var(--line); border-radius: var(--r-md); padding: 12px 16px; font-weight: 700; font-size: .85rem; margin-bottom: 12px; }
.badges { display: flex; flex-wrap: wrap; gap: 8px; margin: 16px 0; }
.badge { font-size: .72rem; font-weight: 600; background: var(--cream-2); border: var(--bw) solid var(--line); padding: 7px 12px; border-radius: var(--pill); }
.logo-card { border: var(--bw) solid var(--line); border-radius: var(--r-md); background: #FFFBEB; padding: 16px; margin-top: 8px; }
.logo-head { display: flex; align-items: center; gap: 10px; font-weight: 800; font-size: .85rem; cursor: pointer; }
.logo-head .arw { margin-left: auto; transition: transform .2s; }
.logo-body { display: none; margin-top: 14px; }
.logo-body.open { display: block; }
.logo-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 10px; }
.logo-field { display: flex; flex-direction: column; gap: 4px; }
.logo-field label { font-size: .68rem; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; color: var(--ink-soft); }
.logo-field select, .logo-field textarea, .logo-field input { border: var(--bw) solid var(--line); border-radius: var(--r-sm); padding: 9px 11px; font: inherit; background: var(--paper); outline: none; }
.pdp-meta { font-size: .8rem; color: var(--ink-soft); margin-top: 14px; }
.pdp-meta a { color: var(--orange); font-weight: 600; }
.desc-card { margin-top: 40px; padding: 26px; }
.desc-card h2 { font-family: var(--font-display); font-weight: 900; text-transform: uppercase; font-size: 1.3rem; margin: 0 0 14px; }
.desc-card .body { color: var(--ink-soft); line-height: 1.8; font-size: .95rem; }
.more-brand { margin-top: 34px; }
@media (max-width: 820px){ .pdp-grid{ grid-template-columns: 1fr; } .logo-grid{ grid-template-columns: 1fr; } }
</style>

<section class="pdp">
  <div class="wrap">
    <div class="pdp-crumb">
      <a href="/">Home</a>›<a href="/catalogue.php">Catalogue</a>›
      <?php if (!empty($product['cat'])): ?><a href="/catalogue.php?cat=<?= urlencode($product['cat']) ?>"><?= gc_e($product['type'] ?? 'Products') ?></a>›<?php endif; ?>
      <span><?= gc_e($product['title']) ?></span>
    </div>

    <div class="pdp-grid">
      <div>
        <div class="pdp-main-img card" id="mainImg">
          <?php if ($imgs): ?>
            <img id="mainImgEl" src="<?= gc_e($imgs[0]) ?>" alt="<?= gc_e($product['title']) ?>" onerror="this.parentElement.innerHTML='<span class=\'ph\'>\ud83d\udc55</span>'">
          <?php else: ?><span class="ph">👕</span><?php endif; ?>
        </div>
        <?php if (count($imgs) > 1): ?>
        <div class="pdp-thumbs">
          <?php foreach ($imgs as $i => $u): ?>
            <div class="pdp-thumb <?= $i===0?'active':'' ?>" onclick="switchImg('<?= gc_e($u) ?>', this)">
              <img src="<?= gc_e($u) ?>" alt="View <?= $i+1 ?>" onerror="this.parentElement.style.display='none'">
            </div>
          <?php endforeach; ?>
        </div>
        <?php endif; ?>
      </div>

      <div>
        <div class="pdp-vendor"><?= gc_e($product['vendor']) ?></div>
        <h1 class="pdp-title"><?= gc_e($product['title']) ?></h1>

        <div class="pdp-price" id="livePrice">£<?= number_format((float)$product['price'], 2) ?> <small id="priceFromLabel">(from)</small></div>
        <div class="pdp-note" id="priceNote">ex. VAT · select options below</div>
        <div class="pdp-note" id="skuDisplay"></div>

        <?php if ($hasColours): ?>
        <div class="opt-label">Colour: <span id="selColour"></span></div>
        <div class="swatches" id="colourButtons">
          <?php foreach ($product['colours'] as $col):
            $cc = trim($col, '*Ü '); $cl = strtolower($cc); $hex = '#ddd';
            foreach ($colMap as $k=>$v) { if (strpos($cl,$k)!==false){ $hex=$v; break; } } ?>
            <button class="swatch" data-colour="<?= gc_e($col) ?>" onclick="selectColour(this)">
              <span class="sd" style="background:<?= $hex ?>"></span><?= gc_e($cc) ?>
            </button>
          <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <?php if ($hasSizes): ?>
        <div class="opt-label">Size: <span id="selSize"></span></div>
        <div class="sizes" id="sizeButtons">
          <?php foreach ($product['sizes'] as $sz): ?>
            <button class="size-btn" data-size="<?= gc_e($sz) ?>" onclick="selectSize(this)"><?= gc_e($sz) ?></button>
          <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <div class="qty-row">
          <span class="lbl">Qty</span>
          <button class="qbtn" onclick="changeQty(-1)" type="button">−</button>
          <input class="qin" id="qtyInput" type="number" value="1" min="1" max="999">
          <button class="qbtn" onclick="changeQty(1)" type="button">+</button>
          <span class="pdp-note" style="margin:0">No minimum</span>
        </div>

        <div class="pdp-success" id="pdpSuccess"></div>
        <button class="btn <?= $addCls ?> big-add" id="addBtn" onclick="<?= $addFn ?>()"><?= $addTxt ?></button>
        <button class="btn wish-btn" onclick="addToWishlist()" type="button">♡ Save to wishlist</button>

        <div class="badges">
          <span class="badge">🚚 Free delivery over £75</span>
          <span class="badge">↩ 28-day returns</span>
          <span class="badge">📦 24hr dispatch</span>
          <?php if ($hasLogo): ?><span class="badge">🎨 Logo available</span><?php endif; ?>
        </div>

        <?php if ($hasLogo): ?>
        <div class="logo-card">
          <div class="logo-head" onclick="toggleLogo()"><span>🎨 Add logo embroidery or printing</span><span class="arw" id="logoArw">▾</span></div>
          <div class="logo-body" id="logoBody">
            <p style="font-size:.8rem;color:#92400e;line-height:1.6;margin:0 0 12px">
              <strong>Artwork digitisation: £10 per logo</strong> (one-off, saved for repeat orders). Customised orders ship in 7–10 working days after artwork approval. We'll confirm stitch count and final cost before production.</p>
            <div class="logo-grid">
              <div class="logo-field"><label>Decoration type</label>
                <select id="logoType"><option value="">Select…</option><option>Embroidery</option><option>Screen printing</option><option>Heat transfer / vinyl</option><option>Direct to garment (DTG)</option></select></div>
              <div class="logo-field"><label>Positions</label>
                <select id="logoPositions"><option value="1">1 position</option><option value="2">2 positions</option><option value="3">3 positions</option><option value="4">4+ positions</option></select></div>
            </div>
            <div class="logo-grid">
              <div class="logo-field"><label>Placement</label>
                <select id="logoPlacement"><option>Left chest</option><option>Right chest</option><option>Centre chest</option><option>Back</option><option>Left sleeve</option><option>Right sleeve</option><option>Cap front</option></select></div>
              <div class="logo-field"><label>Approx. size</label>
                <select id="logoSize"><option>Small (up to 5cm)</option><option>Medium (5–10cm)</option><option>Large (10–20cm)</option><option>Full back (20cm+)</option></select></div>
            </div>
            <div class="logo-field"><label>Artwork notes</label>
              <textarea id="logoNotes" rows="2" placeholder="e.g. 3-colour logo, white text, company name below"></textarea></div>
          </div>
        </div>
        <?php endif; ?>

        <div class="pdp-meta">
          <strong>Category:</strong> <?= gc_e($product['type'] ?? '—') ?> &nbsp;·&nbsp;
          <strong>Brand:</strong> <a href="/catalogue.php?brand=<?= urlencode($product['vendor']) ?>"><?= gc_e($product['vendor']) ?></a>
        </div>
      </div>
    </div>

    <?php if (!empty($product['desc'])): ?>
    <div class="desc-card card">
      <h2>Product description</h2>
      <div class="body" id="descText"><?= gc_e(substr($product['desc'],0,500)) ?><?= strlen($product['desc'])>500?'…':'' ?></div>
      <?php if (strlen($product['desc'])>500): ?>
        <button class="btn" style="margin-top:14px" id="descToggle" onclick="toggleDesc()">Show full description ▾</button>
      <?php endif; ?>
    </div>
    <?php endif; ?>

    <div class="more-brand">
      <a class="btn btn--dark" href="/catalogue.php?brand=<?= urlencode($product['vendor']) ?>">View all <?= gc_e($product['vendor']) ?> →</a>
    </div>
  </div>
</section>

<script>
var variants   = <?= $variantsJson ?>;
var colours    = <?= $coloursJson ?>;
var hasColours = <?= $hasColours ? 'true' : 'false' ?>;
var basePrice  = <?= (float)$product['price'] ?>;
var P = {
  handle: <?= json_encode($product['handle']) ?>,
  title:  <?= json_encode($product['title']) ?>,
  vendor: <?= json_encode($product['vendor']) ?>,
  img:    <?= json_encode($product['img'] ?? ($imgs[0] ?? '')) ?>
};
var selectedColour = hasColours ? (colours[0] || null) : 'Standard';
var selectedSize   = null;

function toast(m){ if (window.gcToast) gcToast(m); else alert(m); }

function selectColour(btn){
  document.querySelectorAll('.swatch').forEach(function(b){ b.classList.remove('selected'); });
  btn.classList.add('selected');
  selectedColour = btn.dataset.colour;
  var lbl = document.getElementById('selColour'); if (lbl) lbl.textContent = selectedColour.replace(/[*Ü]/g,'');
  selectedSize = null;
  document.querySelectorAll('.size-btn').forEach(function(b){ b.classList.remove('selected'); });
  updateSizes(); updatePrice();
}
function selectSize(btn){
  if (btn.classList.contains('unavailable')) return;
  document.querySelectorAll('.size-btn').forEach(function(b){ b.classList.remove('selected'); });
  btn.classList.add('selected');
  selectedSize = btn.dataset.size;
  var lbl = document.getElementById('selSize'); if (lbl) lbl.textContent = selectedSize;
  updatePrice();
}
function updateSizes(){
  if (!selectedColour) return;
  var cv = variants[selectedColour] || {};
  document.querySelectorAll('.size-btn').forEach(function(btn){
    btn.classList.toggle('unavailable', Object.keys(cv).length > 0 && !cv[btn.dataset.size]);
  });
}
function updatePrice(){
  var priceEl = document.getElementById('livePrice');
  var noteEl  = document.getElementById('priceNote');
  var fromLbl = document.getElementById('priceFromLabel');
  var skuEl   = document.getElementById('skuDisplay');
  var addBtn  = document.getElementById('addBtn');
  if (selectedColour && selectedSize){
    var v = (variants[selectedColour]||{})[selectedSize];
    if (v && v.price > 0){
      priceEl.innerHTML = '£' + parseFloat(v.price).toFixed(2);
      if (fromLbl) fromLbl.style.display = 'none';
      noteEl.textContent = 'ex. VAT per item';
      if (skuEl && v.sku) skuEl.textContent = 'SKU: ' + v.sku;
      addBtn.disabled = false; return;
    }
  } else if (selectedColour){
    var prices = Object.values(variants[selectedColour]||{}).map(function(v){return v.price;}).filter(function(p){return p>0;});
    if (prices.length){
      var mn = Math.min.apply(null,prices), mx = Math.max.apply(null,prices);
      priceEl.innerHTML = (mn===mx ? '£'+mn.toFixed(2) : '£'+mn.toFixed(2)+' – £'+mx.toFixed(2));
      if (fromLbl) fromLbl.style.display = 'none';
      noteEl.textContent = 'ex. VAT · select a size';
    }
  }
  addBtn.disabled = true;
}
function changeQty(d){
  var i = document.getElementById('qtyInput');
  i.value = Math.max(1, Math.min(999, (parseInt(i.value)||1) + d));
}
function buildItem(){
  var qty = parseInt(document.getElementById('qtyInput').value) || 1;
  var sz  = selectedSize || 'One Size';
  var v   = (variants[selectedColour]||{})[sz] || {};
  var logoType = document.getElementById('logoType');
  var logo = (logoType && logoType.value) ? {
    type: logoType.value,
    positions: document.getElementById('logoPositions').value,
    placement: document.getElementById('logoPlacement').value,
    size: document.getElementById('logoSize').value,
    notes: document.getElementById('logoNotes').value
  } : null;
  return { handle:P.handle, title:P.title, vendor:P.vendor, colour:selectedColour||'', size:sz,
           price: v.price || basePrice, sku: v.sku || '', qty:qty, img:P.img, logo:logo };
}
function needsSize(){ return document.querySelectorAll('.size-btn').length > 0 && !selectedSize; }

function addToCartFull(){
  if (needsSize()){ toast('Please select a size'); return; }
  var item = buildItem();
  var cart = JSON.parse(localStorage.getItem('gc_cart_items')||'[]');
  var idx = cart.findIndex(function(c){ return c.handle===item.handle && c.colour===item.colour && c.size===item.size; });
  if (idx>=0) cart[idx].qty += item.qty; else cart.push(item);
  localStorage.setItem('gc_cart_items', JSON.stringify(cart));
  localStorage.setItem('gc_cart', cart.reduce(function(s,c){return s+c.qty;},0));
  if (window.gcSyncCounts) gcSyncCounts();
  var s = document.getElementById('pdpSuccess');
  s.style.display='block'; s.textContent='✅ '+item.qty+'× '+item.title+' ('+item.colour+' / '+item.size+') added to basket';
  setTimeout(function(){ s.style.display='none'; }, 3500);
  toast('Added to basket');
}
function addToQuoteFull(){
  if (needsSize()){ toast('Please select a size'); return; }
  var item = buildItem();
  var q = JSON.parse(localStorage.getItem('gc_quote_items')||'[]');
  var idx = q.findIndex(function(c){ return c.handle===item.handle && c.colour===item.colour && c.size===item.size; });
  if (idx>=0) q[idx].qty += item.qty; else q.push(item);
  localStorage.setItem('gc_quote_items', JSON.stringify(q));
  if (window.gcSyncCounts) gcSyncCounts();
  var s = document.getElementById('pdpSuccess');
  s.style.display='block'; s.textContent='✅ '+item.qty+'× '+item.title+' added to your quote';
  setTimeout(function(){ s.style.display='none'; }, 3500);
  toast('Added to your quote');
}
function addToWishlist(){
  var w = JSON.parse(localStorage.getItem('gc_wishlist')||'[]');
  if (!w.includes(P.handle)){ w.push(P.handle); localStorage.setItem('gc_wishlist', JSON.stringify(w)); }
  toast('Saved to wishlist');
}
var fullDesc = <?= json_encode($product['desc'] ?? '') ?>;
var descOpen = false;
function toggleDesc(){
  descOpen = !descOpen;
  document.getElementById('descText').textContent = descOpen ? fullDesc : fullDesc.substring(0,500)+'…';
  document.getElementById('descToggle').textContent = descOpen ? 'Show less ▲' : 'Show full description ▾';
}
function toggleLogo(){
  var b = document.getElementById('logoBody'), a = document.getElementById('logoArw');
  b.classList.toggle('open');
  a.style.transform = b.classList.contains('open') ? 'rotate(180deg)' : '';
}
function switchImg(url, thumb){
  document.getElementById('mainImgEl').src = url;
  document.querySelectorAll('.pdp-thumb').forEach(function(t){ t.classList.remove('active'); });
  thumb.classList.add('active');
}
document.addEventListener('DOMContentLoaded', function(){
  if (hasColours){ var f = document.querySelector('.swatch'); if (f) selectColour(f); }
  else {
    updateSizes();
    var sb = document.querySelectorAll('.size-btn');
    if (sb.length === 1) selectSize(sb[0]);
    else if (sb.length > 0) document.getElementById('addBtn').disabled = true;
    else document.getElementById('addBtn').disabled = false;
  }
});
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
