<?php
include '_head.php';

/* =====================================================
   حذف جميع المنتجات
   ===================================================== */
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_all_products'])) {

  $confirm_text = isset($_POST['confirm_delete_all']) ? trim($_POST['confirm_delete_all']) : '';

  if ($confirm_text === 'DELETE') {

    /*
      نحذف صور المنتجات من قاعدة البيانات أولاً
      ثم نحذف المنتجات
      ملاحظة: لا نحذف ملفات الصور من السيرفر هنا حتى لا نحذف صور قد تحتاجها لاحقاً.
    */

    mysqli_query($conn, "DELETE FROM product_images");
    mysqli_query($conn, "DELETE FROM products");

    // تصفير عداد ID إذا تحب يبدأ من 1 مرة ثانية
    mysqli_query($conn, "ALTER TABLE product_images AUTO_INCREMENT = 1");
    mysqli_query($conn, "ALTER TABLE products AUTO_INCREMENT = 1");

    echo '<div class="admin-card" style="background:#e8fff1;border:1px solid #9be7b4;color:#0f7a35;font-weight:bold;margin-bottom:15px;">
            ✅ تم حذف جميع المنتجات بنجاح
          </div>';

  } else {
    echo '<div class="admin-card" style="background:#fff3f3;border:1px solid #ffb3b3;color:#b30000;font-weight:bold;margin-bottom:15px;">
            ❌ لم يتم الحذف. يجب كتابة DELETE بالضبط للتأكيد.
          </div>';
  }
}

/* =====================================================
   إضافة منتج
   ===================================================== */
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !isset($_POST['delete_all_products'])) {

  $cat   = (int)$_POST['category_id'];
  $brand = (int)$_POST['brand_id'];

  $name_en = mysqli_real_escape_string($conn, $_POST['name_en']);
  $name_ar = mysqli_real_escape_string($conn, $_POST['name_ar']);
  $name_ku = mysqli_real_escape_string($conn, $_POST['name_ku']);

  $desc_en = mysqli_real_escape_string($conn, $_POST['description_en']);
  $desc_ar = mysqli_real_escape_string($conn, $_POST['description_ar']);
  $desc_ku = mysqli_real_escape_string($conn, $_POST['description_ku']);

  $features = mysqli_real_escape_string($conn, $_POST['features']);
  $sku      = mysqli_real_escape_string($conn, $_POST['sku']);

  $price = (float)$_POST['price'];
  $old   = (float)$_POST['old_price'];
  $disc  = (float)$_POST['discount_percent'];
  $stock = (int)$_POST['stock'];

  $is_new  = isset($_POST['is_new']) ? 1 : 0;
  $is_hot  = isset($_POST['is_hot']) ? 1 : 0;
  $is_best = isset($_POST['is_best']) ? 1 : 0;

  mysqli_query($conn, "
    INSERT INTO products
    (
      category_id,
      brand_id,
      name_en,
      name_ar,
      name_ku,
      sku,
      description_en,
      description_ar,
      description_ku,
      features,
      price,
      old_price,
      discount_percent,
      stock,
      is_new,
      is_hot,
      is_best,
      status
    )
    VALUES
    (
      $cat,
      $brand,
      '$name_en',
      '$name_ar',
      '$name_ku',
      '$sku',
      '$desc_en',
      '$desc_ar',
      '$desc_ku',
      '$features',
      $price,
      $old,
      $disc,
      $stock,
      $is_new,
      $is_hot,
      $is_best,
      1
    )
  ");

  $pid = mysqli_insert_id($conn);
  $sort = 1;

  foreach (upload_multi('images', 'uploads/products') as $img) {
    $im = mysqli_real_escape_string($conn, $img);
    mysqli_query($conn, "
      INSERT INTO product_images(product_id, image_path, sort_order)
      VALUES($pid, '$im', $sort)
    ");
    $sort++;
  }

  echo '<div class="admin-card" style="background:#e8fff1;border:1px solid #9be7b4;color:#0f7a35;font-weight:bold;margin-bottom:15px;">
          ✅ تم إضافة المنتج بنجاح
        </div>';
}

/* =====================================================
   حذف منتج واحد
   ===================================================== */
if (isset($_GET['delete'])) {
  $id = (int)$_GET['delete'];

  mysqli_query($conn, "DELETE FROM product_images WHERE product_id = $id");
  mysqli_query($conn, "DELETE FROM products WHERE id = $id");

  echo '<div class="admin-card" style="background:#fff8e6;border:1px solid #ffd36b;color:#9b6500;font-weight:bold;margin-bottom:15px;">
          ✅ تم حذف المنتج
        </div>';
}

/* =====================================================
   جلب البيانات
   ===================================================== */
$cats = mysqli_query($conn, "
  SELECT c.*, p.name_en parent_name
  FROM categories c
  LEFT JOIN categories p ON c.parent_id = p.id
  WHERE c.status = 1
  ORDER BY COALESCE(c.parent_id,0), c.sort_order, c.id
");

$brands = mysqli_query($conn, "
  SELECT *
  FROM brands
  ORDER BY sort_order, id
");

$rs = mysqli_query($conn, "
  SELECT p.*, c.name_en cat, b.name brand
  FROM products p
  LEFT JOIN categories c ON p.category_id = c.id
  LEFT JOIN brands b ON p.brand_id = b.id
  ORDER BY p.id DESC
");

$product_count_q = mysqli_query($conn, "SELECT COUNT(*) total FROM products");
$product_count_r = mysqli_fetch_assoc($product_count_q);
$product_count = isset($product_count_r['total']) ? (int)$product_count_r['total'] : 0;
?>

<h1>Products / المنتجات</h1>

<!-- زر حذف جميع المنتجات -->
<div class="admin-card" style="border:1px solid #ffb3b3;background:#fff5f5;margin-bottom:18px;">
  <h3 style="margin-top:0;color:#b30000;">⚠️ حذف جميع المنتجات</h3>
  <p style="margin-bottom:10px;">
    عدد المنتجات الحالي:
    <strong><?php echo $product_count; ?></strong>
  </p>

  <form method="post" onsubmit="return confirm('تحذير: سيتم حذف جميع المنتجات نهائياً. هل أنت متأكد؟');">
    <input type="hidden" name="delete_all_products" value="1">

    <label style="display:block;margin-bottom:8px;font-weight:bold;">
      للتأكيد اكتب:
      <span style="color:#b30000;">DELETE</span>
    </label>

    <input
      type="text"
      name="confirm_delete_all"
      placeholder="اكتب DELETE هنا"
      style="max-width:260px;border:1px solid #ff9b9b;"
    >

    <button
      class="primary-btn"
      style="background:#d60000;margin-top:10px;"
      type="submit"
    >
      حذف جميع المنتجات
    </button>
  </form>
</div>

<!-- إضافة منتج -->
<form class="admin-card admin-form" method="post" enctype="multipart/form-data">

  <select name="category_id" required>
    <?php
    while ($c = mysqli_fetch_assoc($cats)) {
      $label = ($c['parent_name'] ? $c['parent_name'] . ' › ' : '') . $c['name_en'];
      echo '<option value="' . (int)$c['id'] . '">' . e($label) . '</option>';
    }
    ?>
  </select>

  <select name="brand_id" required>
    <?php
    while ($b = mysqli_fetch_assoc($brands)) {
      echo '<option value="' . (int)$b['id'] . '">' . e($b['name']) . '</option>';
    }
    ?>
  </select>

  <input name="name_en" placeholder="English product name" required>
  <input name="name_ar" placeholder="Arabic name">
  <input name="name_ku" placeholder="Kurdish name">

  <input name="sku" placeholder="SKU / Product code">

  <textarea name="description_en" placeholder="English description"></textarea>
  <textarea name="description_ar" placeholder="Arabic description"></textarea>
  <textarea name="description_ku" placeholder="Kurdish description"></textarea>

  <textarea name="features" placeholder="Features"></textarea>

  <input name="price" placeholder="Price">
  <input name="old_price" placeholder="Old price">
  <input name="discount_percent" placeholder="Discount percent">
  <input name="stock" placeholder="Stock">

  <label>
    <input type="checkbox" name="is_new" checked>
    New / الجديد وصل
  </label>

  <label>
    <input type="checkbox" name="is_hot">
    Hot Deal
  </label>

  <label>
    <input type="checkbox" name="is_best">
    Best Seller
  </label>

  <label>Product images</label>
  <input type="file" name="images[]" multiple accept="image/*">

  <button class="primary-btn">Add Product</button>
</form>

<table class="table">
  <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Category</th>
    <th>Brand</th>
    <th>Price</th>
    <th></th>
  </tr>

  <?php while ($r = mysqli_fetch_assoc($rs)): ?>
    <tr>
      <td><?php echo (int)$r['id']; ?></td>

      <td>
        <?php echo e($r['name_en']); ?>
        <br>
        <small><?php echo e($r['name_ar']); ?></small>
      </td>

      <td><?php echo e($r['cat']); ?></td>
      <td><?php echo e($r['brand']); ?></td>
      <td><?php echo money_iqd($r['price']); ?></td>

      <td>
        <a
          onclick="return confirm('Delete this product?')"
          href="?delete=<?php echo (int)$r['id']; ?>"
          style="color:#d60000;font-weight:bold;"
        >
          Delete
        </a>
      </td>
    </tr>
  <?php endwhile; ?>
</table>

<?php include '_foot.php'; ?>