<?php
require_once 'config/config.php';
require_once 'includes/functions.php';
startSecureSession();
$pageTitle = 'Products Catalog';
$metaDesc = 'Browse our complete range of API standard industrial equipment, flanges, pipes, valves and machinery spare parts.';

// Filters
$search   = trim($_GET['q'] ?? '');
$catSlug  = trim($_GET['category'] ?? '');
$stock    = trim($_GET['stock'] ?? '');
$sortBy   = trim($_GET['sort'] ?? 'featured');
$viewMode = trim($_GET['view'] ?? 'grid');
$page     = max(1, (int)($_GET['page'] ?? 1));

// Build query
$where = ['p.is_active = 1'];
$params = [];

if ($search !== '') {
    $where[] = '(p.name LIKE ? OR p.sku LIKE ? OR p.short_description LIKE ? OR p.brand LIKE ?)';
    $params = array_merge($params, ["%$search%", "%$search%", "%$search%", "%$search%"]);
}
if ($catSlug !== '') {
    $where[] = 'c.slug = ?';
    $params[] = $catSlug;
}
if ($stock !== '') {
    $where[] = 'p.stock_status = ?';
    $params[] = $stock;
}

$whereStr = implode(' AND ', $where);
$orderMap = [
    'featured' => 'p.is_featured DESC, p.views DESC',
    'newest'   => 'p.created_at DESC',
    'az'       => 'p.name ASC',
    'za'       => 'p.name DESC',
];
$order = $orderMap[$sortBy] ?? $orderMap['featured'];

// Count
$total = (int)(Database::fetchOne("SELECT COUNT(*) as c FROM products p LEFT JOIN categories c ON p.category_id=c.id WHERE $whereStr", $params)['c'] ?? 0);
$pag = paginate($total, PRODUCTS_PER_PAGE, $page, '/shop.php?' . http_build_query(array_filter(['q'=>$search,'category'=>$catSlug,'stock'=>$stock,'sort'=>$sortBy,'view'=>$viewMode])));

$products = Database::fetchAll(
    "SELECT p.*, c.name as category_name, c.slug as cat_slug
     FROM products p LEFT JOIN categories c ON p.category_id=c.id
     WHERE $whereStr ORDER BY $order LIMIT ? OFFSET ?",
    array_merge($params, [$pag['per_page'], $pag['offset']])
);

$categories = Database::fetchAll("SELECT * FROM categories WHERE is_active=1 ORDER BY sort_order");
include 'includes/header.php';
?>

<div class="max-w-7xl mx-auto px-4 py-10">
  <!-- Breadcrumb -->
  <nav class="text-xs text-gray-400 mb-6">
    <a href="/" class="hover:text-orange-500">Home</a> / <span class="text-gray-200">Products</span>
    <?php if ($catSlug): foreach($categories as $cat): if($cat['slug']===$catSlug): ?>
    / <span class="text-orange-500"><?= e($cat['name']) ?></span>
    <?php break; endif; endforeach; endif; ?>
  </nav>

  <div class="flex gap-8">
    <!-- Sidebar Filters -->
    <aside class="w-64 flex-shrink-0 hidden lg:block">
      <form method="GET" id="filter-form">
        <input type="hidden" name="view" value="<?= e($viewMode) ?>">
        <div class="filter-panel mb-4">
          <h3 class="font-semibold text-sm mb-3">Search Products</h3>
          <div class="relative">
            <input type="text" name="q" value="<?= e($search) ?>" placeholder="Product name, SKU..." class="pr-8">
            <button type="submit" class="absolute right-2 top-2.5 text-gray-400 hover:text-orange-500">🔍</button>
          </div>
        </div>
        <div class="filter-panel mb-4">
          <h3 class="font-semibold text-sm mb-3">Categories</h3>
          <div class="space-y-1.5">
            <a href="/shop.php" class="block text-sm py-1 <?= !$catSlug ? 'text-orange-500' : 'text-gray-300 hover:text-white' ?>">All Products</a>
            <?php foreach ($categories as $cat): ?>
            <a href="/shop.php?category=<?= e($cat['slug']) ?><?= $search ? '&q=' . urlencode($search) : '' ?>"
               class="block text-sm py-1 <?= $catSlug===$cat['slug'] ? 'text-orange-500 font-semibold' : 'text-gray-300 hover:text-white' ?>">
              <?= $cat['icon'] ?: '' ?> <?= e($cat['name']) ?>
            </a>
            <?php endforeach; ?>
          </div>
        </div>
        <div class="filter-panel mb-4">
          <h3 class="font-semibold text-sm mb-3">Stock Status</h3>
          <?php foreach ([''=>'All', 'in_stock'=>'In Stock', 'out_of_stock'=>'Out of Stock', 'on_order'=>'On Order'] as $v=>$l): ?>
          <label class="flex items-center gap-2 text-sm py-1 cursor-pointer">
            <input type="radio" name="stock" value="<?= $v ?>" class="auto-submit" <?= $stock===$v ? 'checked' : '' ?> style="width:auto">
            <?= $l ?>
          </label>
          <?php endforeach; ?>
        </div>
      </form>
    </aside>

    <!-- Main Content -->
    <div class="flex-1 min-w-0">
      <!-- Toolbar -->
      <div class="flex flex-wrap items-center justify-between gap-3 mb-6">
        <div class="text-sm text-gray-400">
          <?= $total ?> products found
          <?php if ($search): ?> for "<strong class="text-white"><?= e($search) ?></strong>"<?php endif; ?>
        </div>
        <div class="flex items-center gap-3">
          <select name="sort" form="filter-form" onchange="document.getElementById('filter-form').submit()" class="text-sm py-1.5 pr-8" style="width:auto">
            <option value="featured" <?= $sortBy==='featured'?'selected':'' ?>>Featured</option>
            <option value="newest" <?= $sortBy==='newest'?'selected':'' ?>>Newest</option>
            <option value="az" <?= $sortBy==='az'?'selected':'' ?>>A–Z</option>
            <option value="za" <?= $sortBy==='za'?'selected':'' ?>>Z–A</option>
          </select>
          <div class="flex gap-1">
            <a href="?<?= http_build_query(array_merge($_GET, ['view'=>'grid'])) ?>" class="p-2 rounded <?= $viewMode!=='list'?'bg-orange-600 text-white':'bg-navy-700 text-gray-400 hover:text-white' ?>">⊞</a>
            <a href="?<?= http_build_query(array_merge($_GET, ['view'=>'list'])) ?>" class="p-2 rounded <?= $viewMode==='list'?'bg-orange-600 text-white':'bg-navy-700 text-gray-400 hover:text-white' ?>">☰</a>
          </div>
        </div>
      </div>

      <?php if (empty($products)): ?>
      <div class="text-center py-20 text-gray-400">
        <div class="text-5xl mb-4">🔍</div>
        <p class="text-lg">No products found</p>
        <a href="/shop.php" class="btn-outline mt-4 inline-block">Clear Filters</a>
      </div>
      <?php elseif ($viewMode === 'list'): ?>
      <!-- List View -->
      <div class="space-y-3">
        <?php foreach ($products as $p): ?>
        <div class="product-card flex-row p-4 flex gap-4 items-center">
          <?php if ($p['image']): ?>
          <img src="/uploads/<?= e($p['image']) ?>" class="w-20 h-20 object-cover rounded-lg flex-shrink-0" alt="<?= e($p['name']) ?>"
               onerror="this.onerror=null;this.style.display='none';this.nextElementSibling.style.display='flex'">
          <div class="w-20 h-20 rounded-lg bg-navy-600 items-center justify-center text-2xl flex-shrink-0" style="display:none">⚙️</div>
          <?php else: ?>
          <div class="w-20 h-20 rounded-lg bg-navy-600 flex items-center justify-center text-2xl flex-shrink-0">⚙️</div>
          <?php endif; ?>
          <div class="flex-1 min-w-0">
            <div class="text-xs text-orange-500 mb-0.5"><?= e($p['category_name'] ?? '') ?></div>
            <a href="/product-detail.php?slug=<?= e($p['slug']) ?>" class="font-semibold hover:text-orange-400 line-clamp-1"><?= e($p['name']) ?></a>
            <p class="text-xs text-gray-400 mt-0.5 line-clamp-1"><?= e($p['short_description'] ?? '') ?></p>
          </div>
          <div class="flex flex-col items-end gap-2">
            <?= statusBadge($p['stock_status']) ?>
            <button onclick="addToQuote(<?= $p['id'] ?>, this)" class="btn-primary text-xs py-1.5 px-3">Get Quote</button>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
      <?php else: ?>
      <!-- Grid View -->
      <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-5">
        <?php foreach ($products as $p): ?>
        <div class="product-card">
          <a href="/product-detail.php?slug=<?= e($p['slug']) ?>">
            <?php if ($p['image']): ?>
            <img src="/uploads/<?= e($p['image']) ?>" class="product-img" alt="<?= e($p['name']) ?>"
                 onerror="this.onerror=null;this.style.display='none';this.nextElementSibling.style.display='flex'">
            <div class="product-img-placeholder" style="display:none">⚙️</div>
            <?php else: ?>
            <div class="product-img-placeholder">⚙️</div>
            <?php endif; ?>
          </a>
          <div class="p-4 flex flex-col flex-1">
            <div class="text-xs text-orange-500 mb-0.5"><?= e($p['category_name'] ?? '') ?></div>
            <a href="/product-detail.php?slug=<?= e($p['slug']) ?>" class="font-semibold text-sm mb-1 hover:text-orange-400 line-clamp-2 flex-1"><?= e($p['name']) ?></a>
            <?php if ($p['sku']): ?><div class="text-xs text-gray-500 mb-2">SKU: <?= e($p['sku']) ?></div><?php endif; ?>
            <?php if ($p['standards']): ?><div class="badge badge-orange mb-2">📋 <?= e($p['standards']) ?></div><?php endif; ?>
            <div class="flex items-center justify-between mt-auto pt-2">
              <label class="flex items-center gap-1.5 text-xs text-gray-400 cursor-pointer" title="Add to Compare">
                <input type="checkbox" class="compare-check w-3.5 h-3.5 accent-blue-500" value="<?= $p['id'] ?>" data-name="<?= e($p['name']) ?>" onchange="handleCompareCheck(this)">
                <span>Compare</span>
              </label>
              <div class="flex gap-1">
                <button onclick="addToQuote(<?= $p['id'] ?>, this)" class="btn-primary text-xs py-1.5 px-3">Get Quote</button>
                <button onclick="openQuickView(<?= $p['id'] ?>)" class="btn-outline text-xs py-1.5 px-2" title="Quick View">👁</button>
              </div>
            </div>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>

      <?= paginationHtml($pag) ?>
    </div>
  </div>
</div>

<!-- Quick View Modal -->
<div id="quick-view-overlay" class="modal-overlay hidden" onclick="if(event.target===this)closeQuickView()">
  <div class="modal-box relative"><div id="quick-view-content"></div></div>
</div>

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