<?php
session_start();
// Include the database connection from the admin panel
require_once __DIR__ . '/admin-panal/includes/db.php';

$query = $_GET['q'] ?? '';

// Base query
$sql = '
    SELECT p.*, c.name AS category_name, c.slug AS category_slug 
    FROM products p 
    LEFT JOIN categories c ON c.id = p.category_id 
    WHERE p.is_active = 1
';
$params = [];

if (!empty($query)) {
    $searchTerm = "%$query%";
    $sql .= ' AND (p.name LIKE ? OR p.sku LIKE ? OR c.name LIKE ?)';
    $params = [$searchTerm, $searchTerm, $searchTerm];
}

$sql .= ' ORDER BY p.created_at DESC';

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Search Results for "' . htmlspecialchars($query) . '"';

// Helper: get first swatch image from product
if (!function_exists('getProductImage')) {
    function getProductImage($product, $index = 0) {
        $swatches = json_decode($product['design_swatches'] ?? '[]', true);
        if (empty($swatches)) return 'assets/placeholder-product.jpg';
        
        // Support refined structure: thumb or gallery
        $sw = $swatches[0]; // Primary swatch
        if ($index > 0) {
            if (!empty($sw['gallery']) && isset($sw['gallery'][$index-1])) return $sw['gallery'][$index-1];
            if (!empty($swatches[1])) {
                $sw2 = $swatches[1];
                if (!empty($sw2['thumb'])) return $sw2['thumb'];
                if (!empty($sw2['src'])) return $sw2['src'];
                if (!empty($sw2['gallery'][0])) return $sw2['gallery'][0];
            }
        }
        
        if (!empty($sw['thumb'])) return $sw['thumb'];
        if (!empty($sw['src'])) return $sw['src']; // Old format fallback
        if (!empty($sw['gallery'])) return $sw['gallery'][0];
        
        return 'assets/placeholder-product.jpg';
    }
}

if (!function_exists('getProductVideo')) {
    function getProductVideo($product) {
        $swatches = json_decode($product['design_swatches'] ?? '[]', true);
        if (empty($swatches)) return '';
        $sw = $swatches[0];
        if (!empty($sw['videos'][0])) return $sw['videos'][0];
        return '';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
       <!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-Z2X2T395KZ"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-Z2X2T395KZ');
</script>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title><?= htmlspecialchars($pageTitle) ?> — Elegance of India</title>
  <link rel="preconnect" href="https://fonts.googleapis.com" />
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
  <link href="https://fonts.googleapis.com/css2?family=Raleway:ital,wght@0,300;0,400;0,500;0,600;0,700;1,400&display=swap" rel="stylesheet" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" />
  <link rel="stylesheet" href="style.css" />
  <style>
    /* ── PAGE LAYOUT ── */
    .plp-wrapper {
      max-width: 1440px;
      margin: 0 auto;
      padding: 0 24px 80px;
    }
    .plp-main { min-width: 0; }

    /* Breadcrumb */
    .breadcrumb {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 10.5px;
      letter-spacing: 0.06em;
      color: #aaa;
      padding: 24px 0 18px;
    }
    .breadcrumb a { color: #aaa; text-decoration: none; }
    .breadcrumb a:hover { color: var(--gold); }
    .breadcrumb .sep { font-size: 9px; }
    .breadcrumb .current { color: var(--gold); font-style: italic; }

    /* Product grid */
    .plp-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 20px 12px;
    }
    .plp-card {
      display: block;
      text-decoration: none;
      color: inherit;
      cursor: pointer;
    }
    .plp-card__img-wrap {
      position: relative;
      overflow: hidden;
      aspect-ratio: 2/3;
      background: var(--warm-gray);
    }
    .plp-card__img-wrap img, .plp-card__img-wrap video {
      width: 100%;
      height: 100%;
      object-fit: cover;
      display: block;
      transition: transform 0.85s ease;
    }
    .plp-card:hover .plp-card__img-wrap img:first-child,
    .plp-card:hover .plp-card__img-wrap video { transform: scale(1.04); }
    .plp-card__img-wrap .plp-hover-img {
      position: absolute;
      inset: 0;
      width: 100%;
      height: 100%;
      object-fit: cover;
      opacity: 0;
      transition: opacity 0.55s ease;
    }
    .plp-card:hover .plp-hover-img { opacity: 1; }
    
    .plp-card__badge {
      position: absolute;
      top: 10px;
      left: 10px;
      background: var(--black);
      color: var(--white);
      font-size: 8px;
      font-weight: 700;
      letter-spacing: 0.14em;
      text-transform: uppercase;
      padding: 3px 8px;
      z-index: 1;
    }
    .plp-card__wishlist {
      position: absolute;
      top: 10px;
      right: 10px;
      width: 28px;
      height: 28px;
      background: var(--white);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 11px;
      color: var(--charcoal);
      opacity: 0;
      transform: translateY(-6px);
      transition: opacity 0.3s ease, transform 0.3s ease, color 0.2s;
      border: none;
      cursor: pointer;
      box-shadow: 0 2px 6px rgba(0,0,0,0.10);
      z-index: 1;
    }
    .plp-card:hover .plp-card__wishlist { opacity: 1; transform: translateY(0); }
    .plp-card__wishlist:hover { color: #c03a2bff; }
    
    .plp-card__info { padding: 10px 0 0; }
    .plp-card__designer {
      font-size: 9px;
      font-weight: 700;
      letter-spacing: 0.2em;
      text-transform: uppercase;
      color: var(--gold);
      margin-bottom: 3px;
    }
    .plp-card__name {
      font-size: 0.84rem;
      font-weight: 400;
      color: var(--black);
      margin-bottom: 5px;
      line-height: 1.3;
      transition: color 0.25s;
    }
    .plp-card:hover .plp-card__name { color: var(--gold-dk); }
    .plp-card__price {
      font-size: 10px;
      font-weight: 500;
      color: var(--charcoal);
      letter-spacing: 0.04em;
    }

    .empty-state {
      grid-column: 1 / -1;
      text-align: center;
      padding: 80px 20px;
      color: var(--charcoal);
      background: #fafafa;
      border-radius: 8px;
      border: 1px dashed #ddd;
    }
    .empty-state i { font-size: 40px; color: #ccc; margin-bottom: 20px; display: block; }
    .empty-state h3 { font-size: 20px; font-weight: normal; margin-bottom: 8px; }
    
    @media (max-width: 1024px) {
      .plp-grid { grid-template-columns: repeat(3, 1fr); gap: 18px 10px; }
    }
    @media (max-width: 768px) {
      .plp-grid { grid-template-columns: repeat(2, 1fr); gap: 14px 8px; }
    }
    @media (max-width: 480px) {
      .plp-grid { grid-template-columns: repeat(2, 1fr); gap: 12px 6px; }
    }
  </style>
</head>
<body>

  <!-- Include Header -->
  <?php include 'inc/header.php'; ?>

  <!-- SEARCH RESULTS WRAPPER -->
  <div class="plp-wrapper">
    <main class="plp-main">

      <!-- Breadcrumb -->
      <nav class="breadcrumb" aria-label="Breadcrumb">
        <a href="index.php">Home</a>
        <span class="sep"><i class="fas fa-chevron-right"></i></span>
        <span class="current">Search Results</span>
      </nav>

      <!-- Title -->
      <h1 style="font-size: 2.2rem; font-weight: normal; margin-bottom: 8px;">
        Search Results
      </h1>
      <p style="color: #666; font-size: 14px; margin-bottom: 40px;">
        We found <?= count($products) ?> items for "<strong><?= htmlspecialchars($query) ?></strong>"
      </p>

      <!-- Product Grid -->
      <div class="plp-grid">
        
        <?php if (empty($products)): ?>
          <div class="empty-state">
            <i class="fas fa-search"></i>
            <h3>No results found</h3>
            <p style="margin-top: 8px; font-size: 14px; color: #888;">We couldn't find anything matching your search. Please try different keywords.</p>
            <a href="shop.php" class="btn btn-gold" style="display:inline-block; margin-top: 24px; padding: 12px 30px; text-decoration:none;">Explore All Products</a>
          </div>
        <?php else: ?>
          
          <?php foreach ($products as $prod): 
            $img1 = getProductImage($prod, 0);
            $vid1 = ($img1 === 'assets/placeholder-product.jpg') ? getProductVideo($prod) : '';
            $img2 = getProductImage($prod, 1);
            $link = "product.php?id=" . $prod['id'];
          ?>
          <a href="<?= htmlspecialchars($link) ?>" class="plp-card">
            <div class="plp-card__img-wrap">
              <?php if ($vid1): ?>
                <video src="<?= htmlspecialchars($vid1) ?>" autoplay muted loop playsinline></video>
              <?php else: ?>
                <img src="<?= htmlspecialchars($img1) ?>" alt="<?= htmlspecialchars($prod['name']) ?>" loading="lazy" />
                <?php if ($img2): ?>
                  <img class="plp-hover-img" src="<?= htmlspecialchars($img2) ?>" alt="hover" loading="lazy" />
                <?php endif; ?>
              <?php endif; ?>
              
              <?php if (!empty($prod['badge_text'])): ?>
                <span class="plp-card__badge" style="background: <?= htmlspecialchars($prod['badge_color'] ?? '#000') ?>;">
                  <?= htmlspecialchars($prod['badge_text']) ?>
                </span>
              <?php endif; ?>
              
              <button class="plp-card__wishlist" aria-label="Wishlist" onclick="event.preventDefault();"><i class="far fa-heart"></i></button>
            </div>
            
            <div class="plp-card__info">
              <p class="plp-card__designer"><?= htmlspecialchars($prod['sku']) ?></p>
              <p class="plp-card__name"><?= htmlspecialchars($prod['name']) ?></p>
              <p class="plp-card__price">USD <?= number_format($prod['price_usd'], 2) ?></p>
            </div>
          </a>
          <?php endforeach; ?>
          
        <?php endif; ?>

      </div>
      <!-- End Grid -->

    </main>
  </div>
  <!-- End Search Wrapper -->

  <?php include 'inc/footer.php'; ?>
</body>
</html>
