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

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

// Load product via lookup table
$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);
        }
    }
}

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

if (!$product) {
    header('HTTP/1.0 404 Not Found');
    $pageTitle = 'Product not found';
    include __DIR__ . '/../includes/header.php';
    echo '<div style="text-align:center;padding:80px 20px">
        <div style="font-size:64px;margin-bottom:16px">😕</div>
        <h1 style="font-size:24px;font-weight:700;color:var(--navy);margin-bottom:8px">Product not found</h1>
        <p style="font-size:14px;color:var(--muted);margin-bottom:20px">This product may no longer be available or the link may be incorrect.</p>
        <a href="/products.php" style="display:inline-flex;padding:11px 22px;background:var(--blue);color:#fff;border-radius:8px;font-size:14px;font-weight:600">Browse all products</a>
    </div>';
    include __DIR__ . '/../includes/footer.php';
    exit;
}

$pageTitle = $product['title'];
$variantsJson = json_encode($product['variants'] ?? []);
$coloursJson  = json_encode($product['colours']  ?? []);
$hasColours   = !empty($product['colours']) && ($product['colours'][0] ?? '') !== 'Standard';
$hasSizes     = !empty($product['sizes'])   && ($product['sizes'][0]   ?? '') !== 'One Size';
$hasLogo      = $product['has_logo'] ?? false;

include __DIR__ . '/../includes/header.php';
?>
<style>
.product-page{max-width:1200px;margin:0 auto;padding:28px 16px}
.product-grid{display:grid;grid-template-columns:1fr;gap:32px}
@media(min-width:768px){.product-grid{grid-template-columns:1fr 1fr;gap:48px}}
.main-image{border-radius:12px;overflow:hidden;background:#f8f9fc;aspect-ratio:1;display:flex;align-items:center;justify-content:center}
.main-image img{max-width:100%;max-height:100%;object-fit:contain;padding:16px}
.thumb-strip{display:flex;gap:8px;margin-top:10px;flex-wrap:wrap}
.thumb{width:64px;height:64px;border-radius:7px;border:2px solid var(--border);overflow:hidden;cursor:pointer;background:#f8f9fc;display:flex;align-items:center;justify-content:center;transition:border-color .2s;flex-shrink:0}
.thumb:hover,.thumb.active{border-color:var(--blue)}
.thumb img{max-width:100%;max-height:100%;object-fit:contain;padding:4px}
.option-label{font-size:12px;font-weight:700;color:var(--navy);text-transform:uppercase;letter-spacing:.5px;margin-bottom:8px}
.colour-buttons{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:18px}
.colour-btn{padding:5px 12px;border-radius:20px;font-size:12px;font-weight:500;border:1.5px solid var(--border);background:#fff;cursor:pointer;transition:all .18s;display:flex;align-items:center;gap:5px}
.colour-btn:hover{border-color:var(--blue)}
.colour-btn.selected{border-color:var(--blue);background:#dbeafe;color:var(--blue);font-weight:700}
.colour-dot-sm{width:12px;height:12px;border-radius:50%;border:1px solid rgba(0,0,0,.15);flex-shrink:0}
.size-buttons{display:flex;flex-wrap:wrap;gap:7px;margin-bottom:18px}
.size-btn{min-width:44px;padding:7px 10px;border-radius:7px;font-size:13px;font-weight:500;border:1.5px solid var(--border);background:#fff;cursor:pointer;transition:all .18s;text-align:center}
.size-btn:hover{border-color:var(--blue)}
.size-btn.selected{border-color:var(--blue);background:var(--blue);color:#fff;font-weight:700}
.size-btn.unavailable{opacity:.35;cursor:not-allowed}
.live-price{font-size:32px;font-weight:700;color:var(--navy)}
.price-from{font-size:13px;color:var(--muted);font-weight:400}
.qty-row{display:flex;align-items:center;gap:10px;margin-bottom:16px}
.qty-btn{width:36px;height:36px;border:1px solid var(--border);border-radius:7px;background:#fff;font-size:18px;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all .2s}
.qty-btn:hover{border-color:var(--blue);color:var(--blue)}
.qty-input{width:60px;text-align:center;padding:7px;border:1px solid var(--border);border-radius:7px;font-size:15px;font-weight:600;outline:none}
.add-to-cart{width:100%;padding:14px;background:var(--blue);color:#fff;border:none;border-radius:9px;font-size:15px;font-weight:700;cursor:pointer;transition:all .2s;margin-bottom:10px;display:flex;align-items:center;justify-content:center;gap:8px}
.add-to-cart:hover{background:var(--navy);transform:translateY(-1px)}
.add-to-cart:disabled{background:#9ca3af;cursor:not-allowed;transform:none}
.logo-section{background:#fffbeb;border:1px solid #fde68a;border-radius:10px;padding:16px;margin-bottom:16px}
.logo-toggle{display:flex;align-items:center;gap:8px;font-size:14px;font-weight:600;color:var(--navy);cursor:pointer}
.logo-options{display:none;margin-top:14px}
.logo-options.open{display:block}
.logo-field{display:flex;flex-direction:column;gap:4px}
.logo-field label{font-size:11px;font-weight:500;color:var(--text)}
.logo-field input,.logo-field select,.logo-field textarea{padding:8px 10px;border:1px solid var(--border);border-radius:6px;font-size:13px;outline:none;font-family:inherit}
.logo-field input:focus,.logo-field select:focus,.logo-field textarea:focus{border-color:var(--blue)}
.trust-badges{display:flex;flex-wrap:wrap;gap:8px;margin:14px 0}
.trust-badge{display:flex;align-items:center;gap:5px;font-size:11.5px;color:var(--text);background:var(--light);padding:5px 10px;border-radius:6px}
.cart-success{background:#dcfce7;border:1px solid #86efac;color:#166534;padding:12px 16px;border-radius:8px;font-size:13px;font-weight:600;margin-bottom:12px;display:none}
.product-desc{font-size:13.5px;line-height:1.8;color:#374151}
</style>

<div class="product-page">
  <div class="breadcrumb" style="margin-bottom:20px">
    <a href="/">Home</a><span>›</span>
    <a href="/products.php">Products</a><span>›</span>
    <?php if ($product['cat']): ?>
    <a href="/products.php?cat=<?php echo clean($product['cat']); ?>"><?php echo clean($product['type']); ?></a><span>›</span>
    <?php endif; ?>
    <span><?php echo clean($product['title']); ?></span>
  </div>

  <div class="product-grid">
    <!-- IMAGES -->
    <div>
      <div class="main-image" id="mainImg">
        <?php if (!empty($product['imgs'])): ?>
        <img src="<?php echo htmlspecialchars($product['imgs'][0]); ?>" alt="<?php echo clean($product['title']); ?>"
             id="mainImgEl" onerror="this.parentElement.innerHTML='<span style=\'font-size:80px\'>👕</span>'">
        <?php else: ?><span style="font-size:80px">👕</span><?php endif; ?>
      </div>
      <?php if (count($product['imgs'] ?? []) > 1): ?>
      <div class="thumb-strip">
        <?php foreach ($product['imgs'] as $i => $imgUrl): ?>
        <div class="thumb <?php echo $i===0?'active':''; ?>" onclick="switchImg('<?php echo htmlspecialchars($imgUrl); ?>', this)">
          <img src="<?php echo htmlspecialchars($imgUrl); ?>" alt="View <?php echo $i+1; ?>" onerror="this.parentElement.style.display='none'">
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>
    </div>

    <!-- PRODUCT INFO -->
    <div>
      <div style="font-size:12px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px"><?php echo clean($product['vendor']); ?></div>
      <h1 style="font-size:clamp(18px,3vw,26px);font-weight:700;color:var(--navy);line-height:1.3;margin-bottom:12px"><?php echo clean($product['title']); ?></h1>

      <div style="margin-bottom:18px">
        <div class="live-price" id="livePrice">
          £<?php echo number_format((float)$product['price'], 2); ?>
          <span class="price-from" id="priceFromLabel"> (from)</span>
        </div>
        <div style="font-size:12px;color:var(--muted);margin-top:2px" id="priceNote">ex. VAT · Select options below</div>
        <div style="font-size:11px;color:var(--muted);margin-top:3px" id="skuDisplay"></div>
      </div>

      <!-- COLOUR SELECTOR -->
      <?php if ($hasColours): ?>
      <div style="margin-bottom:16px">
        <div class="option-label">Colour: <span id="selectedColourLabel" style="color:var(--blue);text-transform:none;font-weight:600"></span></div>
        <div class="colour-buttons" id="colourButtons">
          <?php foreach ($product['colours'] as $col):
            $colClean = trim($col, '*Ü ');
            $colLower = strtolower($colClean);
            $colMap = ['black'=>'#111','white'=>'#f8f8f8','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','raspberry'=>'#e30b5d','graphite'=>'#4b5563','cardinal'=>'#c41e3a','heather'=>'#8b7d7b'];
            $hex = '#ddd';
            foreach ($colMap as $k=>$v) { if (strpos($colLower,$k)!==false){$hex=$v;break;} }
          ?>
          <button class="colour-btn" data-colour="<?php echo htmlspecialchars($col); ?>" onclick="selectColour(this)">
            <div class="colour-dot-sm" style="background:<?php echo $hex;?>;<?php echo $colLower==='white'?'border:1px solid #ddd;':''; ?>"></div>
            <?php echo clean($colClean); ?>
          </button>
          <?php endforeach; ?>
        </div>
      </div>
      <?php endif; ?>

      <!-- SIZE SELECTOR -->
      <?php if (!empty($product['sizes'])): ?>
      <div style="margin-bottom:16px">
        <div class="option-label">Size: <span id="selectedSizeLabel" style="color:var(--blue);text-transform:none;font-weight:600"></span></div>
        <div class="size-buttons" id="sizeButtons">
          <?php foreach ($product['sizes'] as $sz): ?>
          <button class="size-btn" data-size="<?php echo htmlspecialchars($sz); ?>" onclick="selectSize(this)">
            <?php echo clean($sz); ?>
          </button>
          <?php endforeach; ?>
        </div>
      </div>
      <?php endif; ?>

      <!-- QTY -->
      <div class="qty-row">
        <span style="font-size:13px;font-weight:600;color:var(--navy)">Qty:</span>
        <button class="qty-btn" onclick="changeQty(-1)">−</button>
        <input type="number" class="qty-input" id="qtyInput" value="1" min="1" max="999">
        <button class="qty-btn" onclick="changeQty(1)">+</button>
        <span style="font-size:11px;color:var(--muted)">No minimum</span>
      </div>

      <div class="cart-success" id="cartSuccess"></div>

      <button class="add-to-cart" id="addToCartBtn" onclick="addToCartFull()">🛒 Add to basket</button>

      <button style="width:100%;padding:11px;border:1.5px solid var(--border);border-radius:9px;font-size:14px;font-weight:600;background:#fff;cursor:pointer;margin-bottom:14px;transition:border-color .2s" onmouseover="this.style.borderColor='var(--blue)'" onmouseout="this.style.borderColor='var(--border)'" onclick="addToWishlist()">♡ Save to wishlist</button>

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

      <?php if ($hasLogo): ?>
      <div class="logo-section">
        <div class="logo-toggle" onclick="toggleLogo()">
          <span>🎨</span><span>Add logo embroidery or printing</span>
          <span id="logoArrow" style="margin-left:auto;font-size:12px;transition:transform .2s">▾</span>
        </div>
        <div class="logo-options" id="logoOptions">
          <div style="font-size:12px;color:#92400e;margin-bottom:12px;line-height:1.6;margin-top:10px">
            <strong>Artwork digitisation: £10 per logo</strong> (one-off setup fee, saved for repeat orders).
            Customised orders ship in <strong>7–10 working days</strong> after artwork approval.
            Our team will confirm stitch count and final cost before production begins.
          </div>
          <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:10px">
            <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 style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:10px">
            <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>Approximate 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 logo"></textarea></div>
        </div>
      </div>
      <?php endif; ?>

      <div style="font-size:12px;color:var(--muted);margin-top:8px">
        <strong>Category:</strong> <?php echo clean($product['type']); ?> &nbsp;·&nbsp;
        <strong>Brand:</strong> <a href="/products.php?brand=<?php echo urlencode($product['vendor']); ?>" style="color:var(--blue)"><?php echo clean($product['vendor']); ?></a>
      </div>
    </div>
  </div>

  <!-- DESCRIPTION -->
  <?php if (!empty($product['desc'])): ?>
  <div style="margin-top:40px;background:#fff;border:1px solid var(--border);border-radius:12px;padding:24px">
    <h2 style="font-size:16px;font-weight:700;color:var(--navy);margin-bottom:14px">Product description</h2>
    <div class="product-desc" id="descText"><?php echo clean(substr($product['desc'], 0, 500)); ?><?php echo strlen($product['desc'])>500?'...':''; ?></div>
    <?php if (strlen($product['desc']) > 500): ?>
    <button style="font-size:12px;color:var(--blue);cursor:pointer;background:none;border:none;padding:0;margin-top:8px" id="descToggle" onclick="toggleDesc()">Show full description ▾</button>
    <?php endif; ?>
  </div>
  <?php endif; ?>

  <div style="margin-top:40px">
    <h2 style="font-size:18px;font-weight:700;color:var(--navy);margin-bottom:16px">More from <?php echo clean($product['vendor']); ?></h2>
    <a href="/products.php?brand=<?php echo urlencode($product['vendor']); ?>" class="btn-primary" style="padding:10px 20px;font-size:13px;display:inline-flex">View all <?php echo clean($product['vendor']); ?> products →</a>
  </div>
</div>

<script>
var variants   = <?php echo $variantsJson; ?>;
var colours    = <?php echo $coloursJson; ?>;
var hasColours = <?php echo $hasColours ? 'true' : 'false'; ?>;
var selectedColour = hasColours ? (colours[0] || null) : 'Standard';
var selectedSize   = null;

function selectColour(btn) {
  document.querySelectorAll('.colour-btn').forEach(b => b.classList.remove('selected'));
  btn.classList.add('selected');
  selectedColour = btn.dataset.colour;
  document.getElementById('selectedColourLabel').textContent = selectedColour.replace(/[*Ü]/g,'');
  selectedSize = null;
  document.querySelectorAll('.size-btn').forEach(b => b.classList.remove('selected'));
  updateSizes(); updatePrice();
}
function selectSize(btn) {
  if (btn.classList.contains('unavailable')) return;
  document.querySelectorAll('.size-btn').forEach(b => b.classList.remove('selected'));
  btn.classList.add('selected');
  selectedSize = btn.dataset.size;
  document.getElementById('selectedSizeLabel').textContent = selectedSize;
  updatePrice();
}
function updateSizes() {
  if (!selectedColour) return;
  var colVariants = variants[selectedColour] || {};
  document.querySelectorAll('.size-btn').forEach(function(btn) {
    btn.classList.toggle('unavailable', !colVariants[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');
  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;
      document.getElementById('addToCartBtn').disabled = false;
      return;
    }
  } else if (selectedColour) {
    var prices = Object.values(variants[selectedColour]||{}).map(v=>v.price).filter(p=>p>0);
    if (prices.length) {
      var mn = Math.min(...prices), mx = Math.max(...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';
    }
  }
  document.getElementById('addToCartBtn').disabled = true;
}
function changeQty(d) {
  var inp = document.getElementById('qtyInput');
  inp.value = Math.max(1, Math.min(999, parseInt(inp.value)+d));
}
function addToCartFull() {
  var sizeBtns = document.querySelectorAll('.size-btn');
  if (sizeBtns.length > 0 && !selectedSize) { showToast('⚠️ Please select a size'); return; }
  var qty   = parseInt(document.getElementById('qtyInput').value)||1;
  var sz    = selectedSize || 'One Size';
  var v     = (variants[selectedColour]||{})[sz] || {};
  var price = v.price || <?php echo (float)$product['price']; ?>;
  var logoType = document.getElementById('logoType');
  var logoData = (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;
  var item = {
    handle: '<?php echo addslashes($product['handle']); ?>',
    title:  '<?php echo addslashes($product['title']); ?>',
    vendor: '<?php echo addslashes($product['vendor']); ?>',
    colour: selectedColour || '',
    size:   sz,
    price:  price,
    sku:    v.sku || '',
    qty:    qty,
    img:    '<?php echo addslashes($product['img'] ?? ''); ?>',
    logo:   logoData
  };
  var cart = JSON.parse(localStorage.getItem('gc_cart_items')||'[]');
  var idx  = cart.findIndex(c => c.handle===item.handle && c.colour===item.colour && c.size===item.size);
  if (idx >= 0) cart[idx].qty += qty; else cart.push(item);
  localStorage.setItem('gc_cart_items', JSON.stringify(cart));
  var total = cart.reduce((s,c)=>s+c.qty,0);
  localStorage.setItem('gc_cart', total);
  document.querySelectorAll('.cart-count').forEach(el=>el.textContent=total);
  var s = document.getElementById('cartSuccess');
  s.style.display='block';
  s.textContent='✅ '+qty+'× '+item.title+' ('+item.colour+' / '+item.size+') added!';
  setTimeout(()=>s.style.display='none', 3500);
  showToast('🛒 Added to basket!');
}
function addToWishlist() {
  var wish = JSON.parse(localStorage.getItem('gc_wishlist')||'[]');
  var h = '<?php echo addslashes($product['handle']); ?>';
  if (!wish.includes(h)) { wish.push(h); localStorage.setItem('gc_wishlist',JSON.stringify(wish)); }
  showToast('❤️ Added to wishlist!');
}
var fullDesc = <?php echo json_encode($product['desc'] ?? ''); ?>;
var descExpanded = false;
function toggleDesc() {
  descExpanded = !descExpanded;
  document.getElementById('descText').textContent = descExpanded ? fullDesc : fullDesc.substring(0,500)+'...';
  document.getElementById('descToggle').textContent = descExpanded ? 'Show less ▲' : 'Show full description ▾';
}
function toggleLogo() {
  var o = document.getElementById('logoOptions'), a = document.getElementById('logoArrow');
  o.classList.toggle('open');
  a.style.transform = o.classList.contains('open') ? 'rotate(180deg)' : '';
}
function switchImg(url, thumb) {
  document.getElementById('mainImgEl').src = url;
  document.querySelectorAll('.thumb').forEach(t=>t.classList.remove('active'));
  thumb.classList.add('active');
}
document.addEventListener('DOMContentLoaded', function() {
  if (hasColours) {
    var first = document.querySelector('.colour-btn');
    if (first) selectColour(first);
  } else {
    updateSizes();
    var sb = document.querySelectorAll('.size-btn');
    if (sb.length===1) selectSize(sb[0]);
    else if (sb.length > 0) document.getElementById('addToCartBtn').disabled = true;
    else document.getElementById('addToCartBtn').disabled = false;
  }
  var items = JSON.parse(localStorage.getItem('gc_cart_items')||'[]');
  var total = items.reduce((s,c)=>s+c.qty,0);
  document.querySelectorAll('.cart-count').forEach(el=>el.textContent=total);
});
</script>

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