<?php
declare(strict_types=1);
header('Content-Type: application/json');

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

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) {
  echo json_encode([]); exit;
}

$category = trim((string)($_GET['category'] ?? ''));
$hasStatus = false;
try { $hasStatus = (bool)$pdo->query("SHOW COLUMNS FROM products LIKE 'status'")->fetch(); } catch (Throwable $e) {}

$sql = 'SELECT id, product_title, product_size, price, `condition`, category, product_type, brand, image1, image2, image3, image4, image5, created_at FROM products';
$where = [];
$params = [];
if ($category !== '') { $where[] = 'category = :c'; $params[':c'] = $category; }
if ($hasStatus) { $where[] = "status = 'Active'"; }
if ($where) { $sql .= ' WHERE '.implode(' AND ',$where); }
$sql .= ' ORDER BY created_at DESC';
$stmt = $pdo->prepare($sql);
foreach ($params as $k=>$v) { $stmt->bindValue($k, $v); }
$stmt->execute();
$rows = $stmt->fetchAll();
echo json_encode($rows, JSON_UNESCAPED_SLASHES);
