<?php
require_once __DIR__ . "/../config/db.php";
require_once __DIR__ . "/../config/price.php";
include __DIR__ . "/partials/header.php";

$products = db()->query("SELECT * FROM products ORDER BY id DESC")->fetchAll();
$prices = getPrices();
?>

<div class="container">
  <h2 class="admin-title">إدارة المنتجات</h2>
  <a href="product_add.php" class="btn btn-primary" style="margin-bottom:20px;">➕ إضافة منتج</a>

  <table class="table">
    <thead>
      <tr>
        <th>م</th>
        <th>الصورة</th>
        <th>الاسم</th>
        <th>الوصف</th>
        <th>الوزن (جم)</th>
        <th>العيار / المعدن</th>
        <th>السعر (ر.س)</th>
        <th>إجراءات</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($products as $i => $p): ?>
        <?php
          // تحديد نوع المعدن
          if (isset($p['karat']) && in_array($p['karat'], [24, 21, 18])) {
              $key = "gold_" . $p['karat'];
              $metal = "ذهب عيار " . $p['karat'];
          } else {
              $key = "silver";
              $metal = "فضة";
          }

          // حساب السعر
          $price = isset($prices[$key]) ? $prices[$key] * $p['weight'] : 0;

          // الوصف
          $desc = isset($p['description']) && $p['description'] ? mb_strimwidth($p['description'], 0, 50, "...") : "لا يوجد وصف";
        ?>
        <tr>
          <td><?= $i + 1 ?></td>
          <td><img src="../uploads/<?= htmlspecialchars($p['image']) ?>" alt="" style="max-height:50px;"></td>
          <td><?= htmlspecialchars($p['name']) ?></td>
          <td><?= htmlspecialchars($desc) ?></td>
          <td><?= $p['weight'] ?></td>
          <td><?= $metal ?></td>
          <td><?= number_format($price, 2) ?></td>
          <td>
            <a href="product_edit.php?id=<?= $p['id'] ?>" class="btn btn-sm btn-warning">تعديل</a>
            <a href="product_delete.php?id=<?= $p['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('هل أنت متأكد من الحذف؟')">حذف</a>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

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