<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/functions.php';
startSecureSession();
requireCustomer();
$pageTitle = 'My Saved Products';
$customer = getCurrentCustomer();
$custId = $customer['id'];

// Handle remove
if (isset($_GET['remove']) && is_numeric($_GET['remove'])) {
  Database::execute("DELETE FROM wishlist WHERE customer_id=? AND product_id=?", [$custId, (int)$_GET['remove']]);
  header('Location: /customer/wishlist.php?removed=1'); exit;
}
// Handle add all to RFQ cart (redirect to quote cart with IDs)
if (isset($_GET['add_all'])) {
  $wItems = Database::fetchAll("SELECT product_id FROM wishlist WHERE customer_id=?", [$custId]);
  foreach ($wItems as $wi) {
    // Add to session cart
    if (!isset($_SESSION['quote_cart'])) $_SESSION['quote_cart'] = [];
    $_SESSION['quote_cart'][$wi['product_id']] = ($_SESSION['quote_cart'][$wi['product_id']] ?? 0) + 1;
  }
  header('Location: /quote-cart.php?from=wishlist'); exit;
}

$items = Database::fetchAll("
  SELECT w.*, p.name, p.slug, p.sku, p.short_description, p.image, p.standards, p.brand, p.is_active, c.name as cat_name
  FROM wishlist w
  JOIN products p ON p.id = w.product_id
  LEFT JOIN categories c ON c.id = p.category_id
  WHERE w.customer_id=?
  ORDER BY w.created_at DESC
", [$custId]);

include dirname(__DIR__) . '/includes/header.php';
?>

<div class="max-w-5xl mx-auto px-4 py-10">
  <div class="flex items-center justify-between mb-8">
    <div>
      <h1 class="text-2xl font-bold">Saved Products</h1>
      <p class="text-gray-400 text-sm mt-0.5"><?= count($items) ?> saved item<?= count($items) !== 1 ? 's' : '' ?></p>
    </div>
    <div class="flex gap-3">
      <?php if ($items): ?>
      <a href="?add_all=1" class="btn-primary text-sm px-4 py-2">📋 Add All to RFQ</a>
      <?php endif; ?>
      <a href="/customer/dashboard.php" class="btn-outline text-sm px-4 py-2">← Dashboard</a>
    </div>
  </div>

  <?php if (isset($_GET['removed'])): ?>
  <div class="bg-green-600/10 border border-green-600/30 text-green-400 text-sm px-4 py-3 rounded-lg mb-6">Product removed from saved list.</div>
  <?php endif; ?>

  <?php if ($items): ?>
  <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
    <?php foreach ($items as $item): ?>
    <div class="card-dark overflow-hidden hover:border-orange-600/40 transition-colors <?= !$item['is_active'] ? 'opacity-60' : '' ?>">
      <div class="flex gap-4 p-4">
        <!-- Image -->
        <div class="w-20 h-20 rounded-lg overflow-hidden bg-navy-700 flex-shrink-0">
          <?php if ($item['image']): ?>
          <img src="/uploads/<?= e($item['image']) ?>" alt="<?= e($item['name']) ?>" class="w-full h-full object-contain p-1"
            onerror="this.onerror=null;this.style.display='none';this.nextElementSibling.style.display='flex'">
          <div class="hidden w-full h-full items-center justify-center text-2xl text-gray-600">⚙️</div>
          <?php else: ?>
          <div class="w-full h-full flex items-center justify-center text-2xl text-gray-600">⚙️</div>
          <?php endif; ?>
        </div>
        <!-- Info -->
        <div class="flex-1 min-w-0">
          <div class="text-xs text-orange-400 mb-0.5"><?= e($item['cat_name']) ?></div>
          <h3 class="font-semibold text-white text-sm leading-snug mb-1"><?= e($item['name']) ?></h3>
          <div class="text-xs text-gray-500 mb-1">SKU: <?= e($item['sku']) ?></div>
          <?php if ($item['standards']): ?>
          <div class="text-xs text-gray-400 mb-2"><?= e($item['standards']) ?></div>
          <?php endif; ?>
          <?php if (!$item['is_active']): ?>
          <span class="text-xs bg-red-600/10 text-red-400 px-2 py-0.5 rounded-full">No longer available</span>
          <?php endif; ?>
        </div>
      </div>
      <!-- Actions -->
      <div class="border-t border-navy-500 flex">
        <?php if ($item['is_active']): ?>
        <button onclick="addToQuote(<?= $item['product_id'] ?>, this)"
          class="flex-1 py-2.5 text-xs font-medium text-orange-500 hover:bg-orange-600 hover:text-white transition-colors flex items-center justify-center gap-1">
          📋 Add to RFQ
        </button>
        <?php endif; ?>
        <a href="/product-detail.php?slug=<?= e($item['slug']) ?>" class="flex-1 py-2.5 text-xs font-medium text-gray-400 hover:bg-navy-700 transition-colors flex items-center justify-center gap-1">
          🔍 View Details
        </a>
        <a href="?remove=<?= $item['product_id'] ?>" class="px-4 py-2.5 text-xs font-medium text-gray-500 hover:text-red-400 hover:bg-navy-700 transition-colors flex items-center justify-center">
          🗑
        </a>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <?php else: ?>
  <div class="card-dark p-12 text-center">
    <div class="text-5xl mb-4">❤️</div>
    <h3 class="text-xl font-bold mb-3">No Saved Products</h3>
    <p class="text-gray-400 mb-6">Browse our product catalogue and save items you're interested in for quick RFQ submission later.</p>
    <a href="/shop.php" class="btn-primary px-8 py-3">Browse Products</a>
  </div>
  <?php endif; ?>
</div>

<script>
function addToQuote(id, btn) {
  btn.disabled = true; btn.innerHTML = '✓ Added';
  btn.classList.add('opacity-70');
  fetch('/api/cart.php', {
    method:'POST', headers:{'Content-Type':'application/json'},
    body: JSON.stringify({action:'add', product_id:id, qty:1})
  }).then(r=>r.json()).then(d=>{
    if (d.success) { document.querySelectorAll('.quote-count').forEach(el=>el.textContent=d.count); }
  }).catch(()=>{});
}
</script>

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