<?php
include "auth.php";
include "db.php";

$category = $_GET['category'] ?? '';



$limit = 20;

$page = isset($_GET['page'])
    ? (int)$_GET['page']
    : 1;

if($page < 1){
    $page = 1;
}

$offset = ($page - 1) * $limit;



$countStmt = $conn->prepare("
SELECT COUNT(*) AS total
FROM products
WHERE category = ?
");

$countStmt->bind_param("s", $category);
$countStmt->execute();

$countResult = $countStmt->get_result();
$countRow = $countResult->fetch_assoc();

$totalProducts = $countRow['total'];

$totalPages = ceil($totalProducts / $limit);



$stmt = $conn->prepare("
SELECT *
FROM products
WHERE category = ?
ORDER BY name ASC
LIMIT ? OFFSET ?
");

$stmt->bind_param(
    "sii",
    $category,
    $limit,
    $offset
);

$stmt->execute();

$result = $stmt->get_result();
?>

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description"
content="Maria Curtains offers quality curtains, sheers, curtain rods, mats and home décor in Thika, Kenya. Affordable prices, custom fitting and professional installation.">
  
<title><?= htmlspecialchars($category) ?> Products</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css">
<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=Inter:wght@300;400;500;600&family=Playfair+Display:wght@500;600;700&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&family=Playfair+Display:wght@500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="admin.css">

</head>

<body>

<div class="admin-container">
<button class="menu-toggle" id="menu-toggle">
    <i class="fa-solid fa-bars"></i>
</button>

  <aside class="sidebar" id="sidebar">

    <h2 class="logo">Maria Admin</h2>

   <nav>
      <a href="dashboard.php">Dashboard</a>
      <a href="addproducts.php">Add Product</a>
      <a href="add_offer.php">Add Offer</a>
      <a href="offers.php">Offers</a>
      <a href="products.php">Products</a>
      <a href="categoriesadmin.php" class="active">Categories</a>
      <a href="settings.php">Settings</a>
      <a href="logout.php" class="logout">Logout</a>
    </nav>
  </aside>

  
  <main class="main-content">

    <h1>
      <?= htmlspecialchars($category) ?> Products
    </h1>

    <div class="table-card">

      <table class="admin-table">

        <thead>

          <tr>
            <th>Name</th>
            <th>Price</th>
            <th>Category</th>
            <th>Stock</th>
            <th>Colors</th>
            <th>Image</th>
            <th>Actions</th>
          </tr>

        </thead>

        <tbody>

        <?php while($row = $result->fetch_assoc()): ?>

          <tr>

            <td><?= htmlspecialchars($row['name']) ?></td>

            <td>
              Ksh <?= number_format($row['price']) ?>
            </td>

            <td>
              <?= htmlspecialchars($row['category']) ?>
            </td>

            <td>
              <?= $row['stock'] ?>
            </td>

            
            <td>

              <?php

              $pid = $row['id'];

              $colors = $conn->query("
              SELECT *
              FROM product_colors
              WHERE product_id = $pid
              ");

              while($color = $colors->fetch_assoc()) {

                echo "
                <span class='color-badge'>
                  {$color['color']}
                </span>
                ";
              }

              ?>

            </td>

            
            <td>

              <?php

              $imgResult = $conn->query("
              SELECT *
              FROM product_images
              WHERE product_id = $pid
              LIMIT 1
              ");

              if($img = $imgResult->fetch_assoc()) {

                echo "
                <img
                src='../uploads/".$img['image_path']."'
                class='table-img'>
                ";

              } else {

                echo "No image";

              }

              ?>

            </td>

            
            <td class="actions">

              <a
              href="editproducts.php?id=<?= $row['id'] ?>"
              class="edit">

                Edit

              </a>

              <a
              href="delete-product.php?id=<?= $row['id'] ?>"
              class="delete"
              onclick="return confirm('Delete this product?')">

                Delete

              </a>

            </td>

          </tr>

        <?php endwhile; ?>

        </tbody>

      </table>

    </div>

    

<div class="pagination">

<?php if($page > 1): ?>

<a
href="?category=<?= urlencode($category) ?>&page=<?= $page - 1 ?>"
class="page-btn">

Previous

</a>

<?php endif; ?>


<?php for($i = 1; $i <= $totalPages; $i++): ?>

<a
href="?category=<?= urlencode($category) ?>&page=<?= $i ?>"
class="page-btn <?= ($i == $page) ? 'active-page' : '' ?>">

<?= $i ?>

</a>

<?php endfor; ?>


<?php if($page < $totalPages): ?>

<a
href="?category=<?= urlencode($category) ?>&page=<?= $page + 1 ?>"
class="page-btn">

Next

</a>

<?php endif; ?>

</div>

  </main>

</div>
  <script>
const menuToggle = document.getElementById("menu-toggle");
const sidebar = document.getElementById("sidebar");
const icon = menuToggle.querySelector("i");

menuToggle.addEventListener("click", function(){

    sidebar.classList.toggle("active");

    if(sidebar.classList.contains("active")){

        icon.classList.remove("fa-bars");
        icon.classList.add("fa-xmark");

    }else{

        icon.classList.remove("fa-xmark");
        icon.classList.add("fa-bars");

    }

});

</script>
</body>
</html>