<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/functions.php';
$pageTitle = 'Compare Products';
$currentPage = 'compare';

// Get product IDs from query string (?ids=1,2,3)
$ids = array_filter(array_map('intval', explode(',', $_GET['ids'] ?? '')));
$ids = array_slice(array_unique($ids), 0, 4); // max 4
$products = [];
if ($ids) {
  $placeholders = implode(',', array_fill(0, count($ids), '?'));
  $products = Database::fetchAll("SELECT p.*, c.name as cat_name FROM products p LEFT JOIN categories c ON c.id=p.category_id WHERE p.id IN ($placeholders) AND p.is_active=1", $ids);
}
include __DIR__ . '/includes/header.php';
?>

<section class="pt-28 pb-16 bg-navy-900">
  <div class="max-w-7xl mx-auto px-4">
    <div class="flex items-center gap-4 mb-8">
      <a href="/shop.php" class="text-gray-400 hover:text-white text-sm">← Back to Products</a>
      <div class="h-px flex-1 bg-navy-500"></div>
      <h1 class="text-2xl font-bold">Compare Products</h1>
    </div>

    <?php if (count($products) >= 2): ?>
    <!-- Comparison table -->
    <div class="overflow-x-auto">
      <table class="w-full border-collapse">
        <!-- Product headers -->
        <thead>
          <tr>
            <th class="w-40 bg-navy-800 border border-navy-500 p-4 text-left text-xs text-gray-400 uppercase">Specification</th>
            <?php foreach ($products as $p): ?>
            <th class="bg-navy-700 border border-navy-500 p-4 min-w-[200px]">
              <?php if ($p['image']): ?>
              <div class="h-32 mb-3 overflow-hidden rounded-lg bg-navy-600">
                <img src="/uploads/<?= e($p['image']) ?>" alt="<?= e($p['name']) ?>" class="w-full h-full object-contain p-2"
                  onerror="this.onerror=null;this.style.display='none'">
              </div>
              <?php else: ?>
              <div class="h-32 mb-3 bg-navy-600 rounded-lg flex items-center justify-center text-4xl">⚙️</div>
              <?php endif; ?>
              <div class="text-sm font-bold text-white text-left leading-snug mb-1"><?= e($p['name']) ?></div>
              <div class="text-xs text-gray-400 text-left mb-2"><?= e($p['sku']) ?></div>
              <a href="/product-detail.php?slug=<?= e($p['slug']) ?>" class="text-xs text-orange-500 hover:underline text-left block">View Details →</a>
              <button onclick="removeFromCompare(<?= $p['id'] ?>)" class="mt-2 text-xs text-gray-500 hover:text-red-400">Remove</button>
            </th>
            <?php endforeach; ?>
          </tr>
        </thead>
        <tbody>
          <?php
          $rows = [
            ['Category', 'cat_name'],
            ['Brand', 'brand'],
            ['Origin', 'origin'],
            ['Standards', 'standards'],
            ['Short Description', 'short_description'],
          ];
          foreach ($rows as [$label, $field]):
          ?>
          <tr class="hover:bg-navy-800/50">
            <td class="bg-navy-800 border border-navy-500 p-3 text-xs font-semibold text-orange-400 uppercase tracking-wider"><?= $label ?></td>
            <?php foreach ($products as $p): ?>
            <td class="border border-navy-500 p-3 text-sm text-gray-300"><?= e($p[$field] ?? '—') ?: '—' ?></td>
            <?php endforeach; ?>
          </tr>
          <?php endforeach; ?>

          <!-- Specifications row (parsed from JSON) -->
          <?php
          $allSpecKeys = [];
          $parsedSpecs = [];
          foreach ($products as $p) {
            $specs = json_decode($p['specifications'] ?? '{}', true) ?: [];
            $parsedSpecs[$p['id']] = $specs;
            $allSpecKeys = array_unique(array_merge($allSpecKeys, array_keys($specs)));
          }
          foreach ($allSpecKeys as $specKey):
          ?>
          <tr class="hover:bg-navy-800/50">
            <td class="bg-navy-800 border border-navy-500 p-3 text-xs font-semibold text-gray-400"><?= e($specKey) ?></td>
            <?php foreach ($products as $p): ?>
            <td class="border border-navy-500 p-3 text-sm text-gray-300"><?= e($parsedSpecs[$p['id']][$specKey] ?? '—') ?></td>
            <?php endforeach; ?>
          </tr>
          <?php endforeach; ?>

          <!-- RFQ row -->
          <tr>
            <td class="bg-navy-800 border border-navy-500 p-3 text-xs font-semibold text-orange-400 uppercase">Get Quote</td>
            <?php foreach ($products as $p): ?>
            <td class="border border-navy-500 p-4">
              <button onclick="addToQuote(<?= $p['id'] ?>, this)" class="btn-primary text-xs w-full py-2">+ Add to RFQ</button>
            </td>
            <?php endforeach; ?>
          </tr>
        </tbody>
      </table>
    </div>
    <?php else: ?>
    <div class="card-dark p-12 text-center">
      <div class="text-5xl mb-4">⚖️</div>
      <h2 class="text-xl font-bold mb-3">No Products to Compare</h2>
      <p class="text-gray-400 mb-6">Browse our product catalogue and use the compare button to add up to 4 products for side-by-side comparison.</p>
      <a href="/shop.php" class="btn-primary px-8 py-3">Browse Products</a>
    </div>
    <?php endif; ?>
  </div>
</section>

<script>
function removeFromCompare(id) {
  let ids = new URLSearchParams(location.search).get('ids') || '';
  let arr = ids.split(',').filter(i => i && parseInt(i) !== id);
  if (arr.length >= 2) {
    location.href = '/compare.php?ids=' + arr.join(',');
  } else if (arr.length === 1) {
    location.href = '/product-detail.php?id=' + arr[0];
  } else {
    location.href = '/shop.php';
  }
}
function addToQuote(id, btn) {
  const originalHtml = btn.innerHTML;
  btn.disabled = true; 
  btn.textContent = '⏳ ...';
  
  const apiUrl = (window.SITE_URL || '') + '/api/cart.php';
  
  fetch(apiUrl, {
    method: 'POST', 
    headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': window.CSRF_TOKEN || ''
    },
    body: JSON.stringify({action: 'add', product_id: id, quantity: 1})
  })
  .then(async r => {
    const isJson = r.headers.get('content-type')?.includes('application/json');
    const data = isJson ? await r.json() : null;
    if (!r.ok || !data) throw new Error('Network error');
    return data;
  })
  .then(d => {
    if (d.success) { 
        btn.textContent = '✓ Added';
        btn.classList.add('bg-green-600', 'border-green-600');
        document.querySelectorAll('.cart-badge').forEach(el => {
            el.textContent = d.count;
            el.style.display = 'flex';
        });
    } else {
        btn.disabled = false;
        btn.innerHTML = originalHtml;
        alert(d.error || 'Error adding to quote');
    }
  })
  .catch(err => {
    btn.disabled = false;
    btn.innerHTML = originalHtml;
    alert('Connection error: ' + (err.message || 'Check connection'));
  });
}
</script>

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