<?php
require_once __DIR__ . "/includes/config.php";
require_once __DIR__ . "/includes/functions.php";
require_login();

$slug = $_GET['c'] ?? '';

$stmt = $pdo->prepare("SELECT * FROM categories WHERE slug=? LIMIT 1");
$stmt->execute([$slug]);
$cat = $stmt->fetch();
if (!$cat) die("Category not found.");

$stmt = $pdo->prepare("SELECT * FROM products WHERE category_id=? ORDER BY created_at DESC");
$stmt->execute([(int)$cat['id']]);
$items = $stmt->fetchAll();

include __DIR__ . "/includes/header.php";
?>

<h2 class="mb-3"><?= e($cat['name']) ?></h2>

<div class="row g-3">
  <?php foreach ($items as $p): ?>
    <div class="col-md-4">
      <div class="card product-card h-100 shadow-sm">

        <!-- ✅ IMAGE FIX -->
        <img class="card-img-top"
             src="<?= e(product_image($p['image_url'])) ?>"
             alt="<?= e($p['title']) ?>">

        <div class="card-body">
          <h5 class="card-title"><?= e($p['title']) ?></h5>

          <div class="rating">
            <?= stars_html((float)$p['rating']) ?>
            <span class="small text-muted ms-1"><?= e($p['rating']) ?></span>
          </div>

          <div class="mt-2 d-flex justify-content-between align-items-center">
            <span class="fw-bold">£<?= e($p['price']) ?></span>

            <!-- ✅ DETAILS LINK FIX -->
            <a class="btn btn-sm btn-dark"
               href="/myukstore/product.php?id=<?= (int)$p['id'] ?>">
              Details
            </a>
          </div>
        </div>

      </div>
    </div>
  <?php endforeach; ?>
</div>

<?php include __DIR__ . "/includes/footer.php"; ?>
