<?php
require_once __DIR__ . '/../config/db.php';
include __DIR__ . '/../includes/header.php';

$brand = isset($_GET['brand']) ? $_GET['brand'] : null;
$category = isset($_GET['category']) ? $_GET['category'] : null;
$new_arrival = isset($_GET['new_arrival']) ? (bool)$_GET['new_arrival'] : false;

$sql = "
  SELECT p.*, b.name AS brand_name, c.name AS cat_name
  FROM products p
  LEFT JOIN brands b ON p.brand_id = b.id
  LEFT JOIN categories c ON p.category_id = c.id
  WHERE 1=1
";
if ($brand) {
  if (is_numeric($brand)) {
    // Handle brand ID (for backward compatibility)
    $sql .= " AND p.brand_id = " . (int)$brand;
  } else {
    // Handle brand name
    $sql .= " AND b.name = '" . db()->real_escape_string($brand) . "'";
  }
}
if ($category && in_array($category, ['Men','Women'])) {
  $sql .= " AND c.name = '" . db()->real_escape_string($category) . "'";
}
if ($new_arrival) {
  $sql .= " AND p.is_new_arrival = 1";
}
$sql .= " ORDER BY p.created_at DESC";
$res = db()->query($sql);
?>
<div class="container glass-card" style="padding: 16px;">
  <div class="section-title">
    <h2>Shop</h2>
    <p>Browse premium watches<?php
      if ($brand) {
        if (is_numeric($brand)) {
          // Handle brand ID
          $b = db()->query("SELECT name FROM brands WHERE id=" . (int)$brand)->fetch_assoc();
          echo ' — Brand: ' . htmlspecialchars($b['name']);
        } else {
          // Handle brand name
          echo ' — Brand: ' . htmlspecialchars($brand);
        }
      }
      if ($category) echo ' — Category: ' . htmlspecialchars($category);
    ?></p>
  </div>
  <div class="card-grid">
    <?php while ($p = $res->fetch_assoc()): ?>
      <div class="product-card glass-card">
        <img src="<?php echo htmlspecialchars($p['image_main'] ?: '/WATCHING/assets/images/placeholder.jpg'); ?>" alt="">
        <div class="meta">
          <div class="title"><?php echo htmlspecialchars($p['title']); ?></div>
          <div class="brand"><?php echo htmlspecialchars($p['brand_name']); ?> — <?php echo htmlspecialchars($p['cat_name']); ?></div>
          <div class="price">BDT <?php echo number_format($p['price'], 2); ?></div>
          <div class="actions">
            <a class="btn" href="/WATCHING/pages/product.php?id=<?php echo $p['id']; ?>">View</a>
            <?php if ((int)$p['stock'] > 0): ?>
              <a class="btn" href="/WATCHING/actions/add_to_cart.php?id=<?php echo $p['id']; ?>">Add to Cart</a>
            <?php else: ?>
              <a class="btn" href="/WATCHING/actions/add_to_wishlist.php?id=<?php echo $p['id']; ?>">Add to Wishlist</a>
            <?php endif; ?>
          </div>
        </div>
      </div>
    <?php endwhile; ?>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>