<?php
declare(strict_types=1);

$dbHost = getenv('DB_HOST') ?: 'localhost';
$dbUser = getenv('DB_USER') ?: 'root';
$dbPass = getenv('DB_PASSWORD') ?: '';
$dbName = 'listbnb';

$categoryParam = trim((string)($_GET['category'] ?? ''));
$allowed = [
  'Summer Clothing','Winter Clothing','Party & Formal Wear','Active Wear / Gym Wear',
  'Nightwear / Sleepwear','Modest Wear','Casual Wear',
  'Spring Clothing','Autumn / Fall Clothing','Bridal','Fancy (wedding wear)'
];
if ($categoryParam === '' || !in_array($categoryParam, $allowed, true)) {
    http_response_code(404);
    echo "<!doctype html><html><head><meta charset='utf-8'><title>Category Not Found</title>
    <link rel='stylesheet' href='assets/css/bootstrap.css'>
    <link rel='stylesheet' href='assets/css/main.css'>
    </head><body class='black-bg'>
    <div class='container pt-120 pb-120'><div class='row justify-content-center'><div class='col-xl-6 col-lg-7 col-md-8'>
    <div class='tp-login-wrapper text-center p-40' style='border:1px solid #1b1b1b;border-radius:16px;background:#0f0f10;'>
    <h3 class='tp-form-title mb-10'>Category not found</h3>
    <p class='mb-20'>The requested category is invalid.</p>
    <a class='tp-btn-theme' href='index-2.html'><span>Back to Home</span></a>
    </div></div></div></div></body></html>";
    exit;
}

try {
    $pdo = new PDO("mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4", $dbUser, $dbPass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Database connection failed.');window.location.href='index-2.html';</script></body></html>";
    exit;
}

// Ensure table exists and status column available
try {
    $pdo->exec('CREATE TABLE IF NOT EXISTS products (
        id INT AUTO_INCREMENT PRIMARY KEY,
        product_title VARCHAR(255) NOT NULL,
        product_size ENUM("XS","Small","Medium","Large","XL") NOT NULL,
        price DECIMAL(10,2) NOT NULL,
        `condition` ENUM("New","Used") NOT NULL,
        category VARCHAR(50) NOT NULL,
        product_type VARCHAR(100) NOT NULL,
        brand VARCHAR(100),
        description TEXT NOT NULL,
        image1 VARCHAR(255),
        image2 VARCHAR(255),
        image3 VARCHAR(255),
        image4 VARCHAR(255),
        image5 VARCHAR(255),
        status ENUM("Pending","Active","Inactive") NOT NULL DEFAULT "Pending",
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
} catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN status ENUM("Pending","Active","Inactive") NOT NULL DEFAULT "Pending"'); } catch (Throwable $e) {}

$hasStatus = false;
try { $hasStatus = (bool)$pdo->query("SHOW COLUMNS FROM products LIKE 'status'")->fetch(); } catch (Throwable $e) { $hasStatus = false; }

$stmt = $hasStatus
  ? $pdo->prepare('SELECT * FROM products WHERE category = :c AND status = "Active" ORDER BY created_at DESC')
  : $pdo->prepare('SELECT * FROM products WHERE category = :c ORDER BY created_at DESC');
$stmt->execute([':c' => $categoryParam]);
$products = $stmt->fetchAll();

?>
<!doctype html>
<html class="no-js" lang="zxx">
<head>
   <meta charset="utf-8">
   <meta http-equiv="x-ua-compatible" content="ie=edge">
   <title><?php echo htmlspecialchars($categoryParam, ENT_QUOTES); ?> - ListBnb</title>
   <meta name="viewport" content="width=device-width, initial-scale=1">

   <link rel="shortcut icon" type="image/x-icon" href="assets/img/logo/favicon.png">
   <link rel="stylesheet" href="assets/css/bootstrap.css">
   <link rel="stylesheet" href="assets/css/animate.css">
   <link rel="stylesheet" href="assets/css/swiper-bundle.css">
   <link rel="stylesheet" href="assets/css/slick.css">
   <link rel="stylesheet" href="assets/css/magnific-popup.css">
   <link rel="stylesheet" href="assets/css/font-awesome-pro.css">
   <link rel="stylesheet" href="assets/css/spacing.css">
   <link rel="stylesheet" href="assets/css/custom-animation.css">
   <link rel="stylesheet" href="assets/css/main.css">
   <style>
     :root {
       --primary: #4f46e5;
       --primary-light: #eef2ff;
       --primary-dark: #4338ca;
       --success: #10b981;
       --danger: #ef4444;
       --warning: #f59e0b;
       --dark: #1f2937;
       --light: #f9fafb;
       --border: #e5e7eb;
       --text: #374151;
       --text-light: #6b7280;
       --radius: 12px;
       --shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
       --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
     }

     /* Category Hero Section */
    .cat-hero {
      padding: 80px 0 60px;
      background: linear-gradient(135deg, #f3f4f6 0%, #ffe6ef 100%);
      position: relative;
      overflow: hidden;
    }

     .cat-hero::before {
       content: '';
       position: absolute;
       top: 0;
       left: 0;
       right: 0;
       bottom: 0;
       background: url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M54.627 0l.83.828-1.415 1.415L51.8 0h2.827zM5.373 0l-2.242 2.243L1.716.828 2.544 0h2.829zM48.97 0l-8.486 8.485-1.414-1.414L46.142 0h2.828zM.515 0L0 .515v2.544l2.121-2.121.394-1.418L.515 0zm6.272 0l2.242 2.243 1.415-1.415L8.2 0H6.787zm39.9 0l-8.485 8.485-1.415-1.414L44.313 0h2.374zM9.02 0L.535 8.485l1.414 1.414L10.434 0H9.02zM4.929 4.929L0 0v60l60-60H5.172l-.243.243L4.93 4.93zM60 0L0 60h60V0zM0 60L60 0v60H0z' fill='rgba(255,255,255,0.1)' fill-rule='evenodd'/%3E%3C/svg%3E");
       opacity: 0.1;
     }

    .cat-title {
      color: #1f2937;
      font-weight: 800;
      font-size: 2.5rem;
      margin: 0 0 0.5rem;
      position: relative;
      text-shadow: none;
    }
    .cat-title span{color:#ff3b8f}

    .result-count {
      color: #6b7280;
      font-size: 1.1rem;
      margin: 0;
      position: relative;
    }

     /* Product Grid */
     .product-card {
       background: #fff;
       border: 1px solid var(--border);
       border-radius: var(--radius);
       overflow: hidden;
       transition: var(--transition);
       height: 100%;
       display: flex;
       flex-direction: column;
       box-shadow: var(--shadow);
     }

     .product-card:hover {
       transform: translateY(-5px);
       box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
       border-color: var(--primary-light);
     }

    .product-thumb-container {
      position: relative;
      height: 280px;
      overflow: hidden;
      background: #fff;
      border-bottom: 1px solid var(--border);
    }

    .product-thumb {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: contain;
      transition: transform 0.5s ease;
      background: #fff;
    }

     .product-card:hover .product-thumb {
       transform: scale(1.05);
     }

     .product-badge {
       position: absolute;
       top: 12px;
       right: 12px;
       background: var(--primary);
       color: white;
       padding: 4px 10px;
       border-radius: 12px;
       font-size: 0.75rem;
       font-weight: 600;
       z-index: 1;
     }

     .product-body {
       padding: 1.25rem;
       flex: 1;
       display: flex;
       flex-direction: column;
     }

     .product-title {
       color: var(--dark);
       font-size: 1.1rem;
       font-weight: 600;
       margin: 0 0 0.75rem;
       line-height: 1.4;
       display: -webkit-box;
       -webkit-line-clamp: 2;
       -webkit-box-orient: vertical;
       overflow: hidden;
       min-height: 3em;
     }

     .product-price {
       color: var(--primary);
       font-weight: 700;
       font-size: 1.25rem;
       margin-top: auto;
       padding-top: 0.5rem;
     }

     .product-meta {
       display: flex;
       flex-wrap: wrap;
       gap: 8px;
       margin: 0.5rem 0;
       font-size: 0.85rem;
     }

    .badge-soft {
      display: inline-flex;
      align-items: center;
      gap: 8px;
      background: linear-gradient(180deg, #ffffff 0%, #f8fafc 100%);
      color: #374151;
      border: 1px solid #e5e7eb;
      border-radius: 999px;
      padding: 6px 12px;
      font-size: 0.78rem;
      font-weight: 600;
      box-shadow: 0 6px 16px rgba(0,0,0,.06);
      transition: var(--transition);
    }

     .badge-soft i {
       font-size: 0.7em;
     }

    .product-card:hover .badge-soft {
      background: #eef2ff;
      color: #4f46e5;
      border-color: #dbeafe;
    }

     /* Empty State */
     .empty-box {
       background: #fff;
       border: 2px dashed var(--border);
       border-radius: var(--radius);
       padding: 3rem 2rem;
       text-align: center;
       max-width: 600px;
       margin: 0 auto;
       box-shadow: var(--shadow);
     }

     .empty-box i {
       font-size: 3rem;
       color: var(--primary-light);
       margin-bottom: 1rem;
       display: inline-block;
     }

     .empty-box h3 {
       color: var(--dark);
       margin: 0 0 1rem;
       font-weight: 600;
     }

     .empty-box p {
       color: var(--text-light);
       margin-bottom: 1.5rem;
     }

     /* Responsive Adjustments */
     @media (max-width: 991px) {
       .cat-hero {
         padding: 60px 0 40px;
       }
       
       .cat-title {
         font-size: 2rem;
       }
     }

     @media (max-width: 767px) {
       .cat-title {
         font-size: 1.75rem;
       }
       
       .product-card {
         max-width: 330px;
         margin: 0 auto;
       }
     }
   </style>
</head>
<body>
   <header class="tp-header-height">
      <div id="header-sticky" class="tp-header-area tp-header-inner-style">
         <div class="container">
            <div class="row align-items-center">
               <div class="col-xl-3 col-lg-6 col-md-6 col-6">
                  <div class="tp-header-logo">
                     <a href="index-2.php" class="brand-text">ReWear</a>
                  </div>
               </div>
               <div class="col-xl-6 col-lg-4 d-none d-xl-block">
                  <div class="tp-header-menu">
                     <nav class="tp-main-menu-content">
                        <ul>
                           <li><a href="index-2.php">Home</a></li>
                           <li><a href="listing-ads.php">Post Your Ad</a></li>
                           <li><a href="about-us.html">About Us</a></li>
                           <li><a href="contact.html">Contact</a></li>
                        </ul>
                     </nav>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </header>

   <main>
      <section class="cat-hero">
        <div class="container">
          <div class="row">
            <div class="col-12">
              <nav aria-label="breadcrumb">
                <ol class="breadcrumb" style="background: transparent; padding: 0; margin-bottom: 1rem;">
                  <li class="breadcrumb-item"><a href="index-2.php" style="color:#6b7280; text-decoration: none;">Home</a></li>
                  <li class="breadcrumb-item active" aria-current="page" style="color:#1f2937;"><?php echo htmlspecialchars($categoryParam, ENT_QUOTES); ?></li>
                </ol>
              </nav>
              <?php $parts = preg_split('/\s+/', $categoryParam, 2); ?>
              <h1 class="cat-title"><?php echo htmlspecialchars($parts[0] ?? $categoryParam, ENT_QUOTES); ?><?php if (!empty($parts[1])): ?> <span><?php echo htmlspecialchars($parts[1], ENT_QUOTES); ?></span><?php endif; ?></h1>
              <p class="result-count">
                <i class="fa-regular fa-grid-2 me-2"></i>Showing <?php echo (int)count($products); ?> item<?php echo count($products) !== 1 ? 's' : ''; ?> in this category
              </p>
            </div>
          </div>
        </div>
      </section>

      <section class="pb-120 pt-80">
        <div class="container">
          <?php if (!$products): ?>
            <div class="row justify-content-center">
              <div class="col-xl-8 col-lg-9">
                <div class="empty-box">
                  <i class="fa-regular fa-box-open"></i>
                  <h3>No Products Found</h3>
                  <p>There are currently no products listed in this category. Check back later or browse other categories.</p>
                  <a class="btn btn-primary px-4 py-2 rounded-pill" href="index-2.php">
                    <i class="fa-light fa-arrow-left me-2"></i> Back to Home
                  </a>
                </div>
              </div>
            </div>
          <?php else: ?>
          <div class="row row-cols-xl-4 row-cols-lg-3 row-cols-md-2 row-cols-1 g-4">
            <?php foreach ($products as $p): ?>
              <?php 
                $img = $p['image1'] ?: ($p['image2'] ?: ($p['image3'] ?: 'assets/img/listing/listing-1-1.png'));
                $conditionClass = strtolower($p['condition']) === 'new' ? 'bg-success' : 'bg-warning';
                $conditionText = $p['condition'] === 'New' ? 'New' : 'Used';
              ?>
              <div class="col">
                <a class="product-card d-block h-100" href="product.php?id=<?php echo (int)$p['id']; ?>" style="text-decoration: none;">
                  <div class="product-thumb-container">
                    <img class="product-thumb" src="<?php echo htmlspecialchars($img, ENT_QUOTES); ?>" alt="<?php echo htmlspecialchars($p['product_title'], ENT_QUOTES); ?>">
                    <span class="product-badge <?php echo $conditionClass; ?>"><?php echo $conditionText; ?></span>
                  </div>
                  <div class="product-body">
                    <h3 class="product-title"><?php echo htmlspecialchars($p['product_title'], ENT_QUOTES); ?></h3>
                    <div class="product-meta">
                      <span class="badge-soft" title="Size"><i class="fa-light fa-shirt"></i> <?php echo htmlspecialchars($p['product_size'], ENT_QUOTES); ?></span>
                      <span class="badge-soft" title="Type"><i class="fa-light fa-swatchbook"></i> <?php echo htmlspecialchars($p['product_type'], ENT_QUOTES); ?></span>
                      <?php if (!empty($p['brand'])): ?>
                        <span class="badge-soft" title="Brand"><i class="fa-light fa-copyright"></i> <?php echo htmlspecialchars($p['brand'], ENT_QUOTES); ?></span>
                      <?php endif; ?>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mt-auto pt-2">
                      <span class="badge-soft bg-primary-light text-primary" title="Category">
                        <i class="fa-light fa-tag"></i> <?php echo htmlspecialchars($p['category'], ENT_QUOTES); ?>
                      </span>
                      <span class="product-price">$<?php echo number_format((float)$p['price'], 2); ?></span>
                    </div>
                  </div>
                </a>
              </div>
            <?php endforeach; ?>
          </div>
          <?php endif; ?>
        </div>
      </section>
   </main>

   <footer>
      <div class="tp-copyright-area black-bg">
         <div class="container">
            <div class="tp-copyright-ptb">
               <div class="row align-items-center">
                  <div class="col-xl-7 col-lg-6 col-md-6 col-sm-7">
                     <div class="tp-copyright-left d-flex align-items-center justify-content-center justify-content-md-start">
                        <div class="tp-copyright-text text-center text-md-start">
                           <p>Listbnb</p>
                        </div>
                     </div>
                  </div>
                  <div class="col-xl-5 col-lg-6 col-md-6 col-sm-5">
                     <div class="tp-copyright-right justify-content-center d-flex justify-content-sm-end align-items-center">
                        <div class="tp-copyright-social">
                           <a href="#"><i class="fa-brands fa-facebook-f"></i></a>
                           <a href="#"><i class="fa-brands fa-twitter"></i></a>
                           <a href="#"><i class="fa-brands fa-youtube"></i></a>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </footer>

   <script src="assets/js/vendor/jquery.js"></script>
   <script src="assets/js/bootstrap-bundle.js"></script>
   <script src="assets/js/swiper-bundle.js"></script>
   <script src="assets/js/slick.js"></script>
   <script src="assets/js/magnific-popup.js"></script>
   <script src="assets/js/nice-select.js"></script>
   <script src="assets/js/purecounter.js"></script>
   <script src="assets/js/countdown.js"></script>
   <script src="assets/js/wow.js"></script>
   <script src="assets/js/isotope-pkgd.js"></script>
   <script src="assets/js/imagesloaded-pkgd.js"></script>
   <script src="assets/js/ajax-form.js"></script>
   <script src="assets/js/main.js"></script>
</body>
</html>
