<?php
session_start();
$conn = new mysqli("localhost", "kkfxoaad", "Bitok@2025", "kkfxoaad_bella");

// Only allow admins
if (!isset($_SESSION['user_id']) || ($_SESSION['is_admin'] ?? 0) != 1) {
    header("Location: login.php");
    exit();
}

// -------------------------
// Handle Add Product
// -------------------------
if (isset($_POST['add_product'])) {
    $name = trim($_POST['name'] ?? '');
    $sku = trim($_POST['sku'] ?? '');
    $category = $_POST['category'] ?? '';
    $gender = $_POST['gender'] ?? 'Unisex';
    $brand = trim($_POST['brand'] ?? '');
    $price = floatval($_POST['price'] ?? 0);
    $discount_price = !empty($_POST['discount_price']) ? floatval($_POST['discount_price']) : 0.00;
    $description = trim($_POST['description'] ?? '');
    $sizes = array_filter(array_map('trim', explode(',', $_POST['sizes'] ?? '')));
    $colors = array_filter(array_map('trim', explode(',', $_POST['colors'] ?? '')));
    $material = trim($_POST['material'] ?? '');
    $stock = intval($_POST['stock'] ?? 10);
    $sold_quantity = 0;
    $remaining_stock = $stock;

    // Custom attributes
    $attributes = [];
    if (!empty($_POST['attr_name'])) {
        foreach ($_POST['attr_name'] as $i => $attrName) {
            $val = $_POST['attr_value'][$i] ?? '';
            if ($attrName && $val) {
                $attributes[$attrName] = $val;
            }
        }
    }

    // Multiple image upload
    $uploaded_images = [];
    $main_image = null;
    if (!empty($_FILES['images']['name'][0])) {
        foreach ($_FILES['images']['name'] as $key => $val) {
            if (!empty($val)) {
                $image_name = time() . "_" . basename($val);
                move_uploaded_file($_FILES['images']['tmp_name'][$key], "uploads/$image_name");
                $uploaded_images[] = $image_name;
                if ($main_image === null) {
                    $main_image = $image_name; // first image = main thumbnail
                }
            }
        }
    }

    // Convert JSON values
    $sizes_json = json_encode($sizes);
    $colors_json = json_encode($colors);
    $attr_json = json_encode($attributes);
    $images_json = json_encode($uploaded_images);

    $stmt = $conn->prepare("INSERT INTO products 
        (name, sku, category, gender, brand, price, discount_price, description, material, sizes, colors, attributes, image, images, stock, remaining_stock, sold_quantity, created_at) 
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW())");

    $stmt->bind_param(
        "sssssdsssssssssiii",
        $name, $sku, $category, $gender, $brand,
        $price, $discount_price, $description, $material,
        $sizes_json, $colors_json,
        $attr_json, $main_image, $images_json,
        $stock, $remaining_stock, $sold_quantity
    );

    $stmt->execute();
    $stmt->close();
    header("Location: admin-products.php");
    exit();
}

// -------------------------
// Handle Edit Product
// -------------------------
if (isset($_POST['edit_product'])) {
    $id = intval($_POST['id']);
    $name = trim($_POST['name'] ?? '');
    $sku = trim($_POST['sku'] ?? '');
    $category = $_POST['category'] ?? '';
    $gender = $_POST['gender'] ?? 'Unisex';
    $brand = trim($_POST['brand'] ?? '');
    $price = floatval($_POST['price'] ?? 0);
    $discount_price = !empty($_POST['discount_price']) ? floatval($_POST['discount_price']) : 0.00;
    $description = trim($_POST['description'] ?? '');
    $sizes = array_filter(array_map('trim', explode(',', $_POST['sizes'] ?? '')));
    $colors = array_filter(array_map('trim', explode(',', $_POST['colors'] ?? '')));
    $material = trim($_POST['material'] ?? '');
    $stock = intval($_POST['stock'] ?? 0);

    // Attributes
    $attributes = [];
    if (!empty($_POST['attr_name'])) {
        foreach ($_POST['attr_name'] as $i => $attrName) {
            $val = $_POST['attr_value'][$i] ?? '';
            if ($attrName && $val) {
                $attributes[$attrName] = $val;
            }
        }
    }

    // Fetch existing images + main image
    $result = $conn->query("SELECT image, images FROM products WHERE id=$id");
    $row = $result->fetch_assoc();
    $existing_images = json_decode($row['images'], true) ?? [];
    $main_image = $row['image'];

    // Upload new images (append to existing)
    if (!empty($_FILES['images']['name'][0])) {
        foreach ($_FILES['images']['name'] as $key => $val) {
            if (!empty($val)) {
                $image_name = time() . "_" . basename($val);
                move_uploaded_file($_FILES['images']['tmp_name'][$key], "uploads/$image_name");
                $existing_images[] = $image_name;
                if ($main_image === null) {
                    $main_image = $image_name; // set if no main image yet
                }
            }
        }
    }

    // Convert JSON values
    $sizes_json = json_encode($sizes);
    $colors_json = json_encode($colors);
    $attr_json = json_encode($attributes);
    $images_json = json_encode($existing_images);

    $stmt = $conn->prepare("UPDATE products 
        SET name=?, sku=?, category=?, gender=?, brand=?, price=?, discount_price=?, description=?, material=?, sizes=?, colors=?, attributes=?, image=?, images=?, stock=?, remaining_stock=? 
        WHERE id=?");

    $stmt->bind_param(
        "sssssdssssssssiii",
        $name, $sku, $category, $gender, $brand,
        $price, $discount_price, $description, $material,
        $sizes_json, $colors_json,
        $attr_json, $main_image, $images_json,
        $stock, $stock, $id
    );

    $stmt->execute();
    $stmt->close();
    header("Location: admin-products.php");
    exit();
}

// -------------------------
// Fetch products
// -------------------------
$result = $conn->query("SELECT * FROM products ORDER BY created_at DESC");
$products = [];
while ($row = $result->fetch_assoc()) $products[] = $row;
$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Admin Products - Taji Yetu</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="admin-sidebar.css">
<style>
.dashboard-wrapper { display:flex; min-height:100vh; margin-top:60px; }
.main-content { flex:1; padding:20px; background:#111; color:#fff; margin-left:250px; }

form { background:rgba(25,25,25,0.95); padding:15px; margin-bottom:20px; border-radius:10px; display:flex; flex-wrap:wrap; gap:10px; align-items:flex-end; justify-content:center; }
form input, form select, form textarea { padding:8px; border-radius:6px; border:none; background:#222; color:#fff; }
form input.short, form select.short { width:150px; }
form input.medium { width:200px; }
form textarea { width:100%; resize:vertical; height:60px; }

button { background:#28a745; color:#fff; border:none; padding:8px 14px; border-radius:6px; cursor:pointer; font-weight:bold; }
button:hover { background:#218838; }

.product-item { display:flex; align-items:center; justify-content:space-between; padding:10px; background:#1a1a1a; margin-bottom:10px; border-radius:8px; text-align:center; }
.product-item img { width:80px; height:80px; object-fit:cover; border-radius:6px; margin-right:10px; }
.product-details { flex:1; text-align:center; }
.product-actions { text-align:center; }
.product-actions button { margin-left:5px; background:#555; }
.product-actions button:hover { background:#777; }
.delete-btn { background:#c00 !important; color:#fff !important; padding:6px 10px; border-radius:6px; text-decoration:none; display:inline-block; }
.delete-btn:hover { background:#f33 !important; }

.gallery { display:flex; gap:8px; flex-wrap:wrap; }
.gallery img { width:60px; height:60px; object-fit:cover; border-radius:6px; }
</style>
</head>
<body>

<?php include "navbar.php"; ?>
<div class="dashboard-wrapper">
  <?php include "admin-sidebar.php"; ?>
  <div class="main-content">
    <h2>Manage Products</h2>

    <!-- Add Product Form -->
    <form method="post" enctype="multipart/form-data">
      <input type="text" name="name" placeholder="Product Name" class="medium" required>
      <input type="text" name="sku" placeholder="SKU / Product Code" class="short" required>
      <select name="category" class="short">
        <option>Men</option>
        <option>Women</option>
        <option>Kids</option>
        <option>Accessories</option>
      </select>
      <select name="gender" class="short">
        <option>Unisex</option>
        <option>Men</option>
        <option>Women</option>
        <option>Kids</option>
      </select>
      <input type="text" name="brand" placeholder="Brand" class="short">
      <input type="number" name="price" placeholder="Price" class="short" required>
      <input type="number" name="discount_price" placeholder="Discount Price" class="short">
      <input type="number" name="stock" placeholder="Stock Qty" class="short" required>
      <input type="text" name="sizes" placeholder="Sizes (comma separated)" class="medium">
      <input type="text" name="colors" placeholder="Colors (comma separated)" class="medium">
      <input type="text" name="material" placeholder="Material / Fabric" class="medium">
      <textarea name="description" placeholder="Description"></textarea>
      <label>Images:</label>
      <input type="file" name="images[]" multiple>

      <div id="attr-box"></div>
      <button type="button" onclick="addAttr()">+ Add Attribute</button>

      <button type="submit" name="add_product"><i class="fas fa-plus"></i> Add Product</button>
    </form>

    <!-- Product List -->
    <?php foreach($products as $prod): ?>
      <div class="product-item">
        <?php if (!empty($prod['image'])): ?>
          <img src="uploads/<?= htmlspecialchars($prod['image']) ?>" alt="">
        <?php endif; ?>
        <div class="product-details">
          <strong><?= htmlspecialchars($prod['name']) ?></strong><br>
          SKU: <?= htmlspecialchars($prod['sku']) ?><br>
          Price: KES <?= number_format($prod['price']) ?>  
          <?php if($prod['discount_price']): ?>  
            <span style="color:#f66;">(Sale: <?= number_format($prod['discount_price']) ?>)</span>
          <?php endif; ?><br>
          Stock: <?= intval($prod['stock']) ?><br>
          Category: <?= htmlspecialchars($prod['category']) ?> | Brand: <?= htmlspecialchars($prod['brand']) ?>
        </div>
        <div class="product-actions">
          <button onclick="openEdit(<?= $prod['id'] ?>)">Edit</button>
          <a href="delete-product.php?id=<?= $prod['id'] ?>" onclick="return confirm('Delete this product?');" class="delete-btn">Delete</a>
        </div>
      </div>

      <!-- Edit Form -->
      <form method="post" enctype="multipart/form-data" id="edit-<?= $prod['id'] ?>" style="display:none; flex-wrap:wrap; gap:10px; justify-content:center;">
        <input type="hidden" name="id" value="<?= $prod['id'] ?>">
        <input type="text" name="name" value="<?= htmlspecialchars($prod['name']) ?>" class="medium" required>
        <input type="text" name="sku" value="<?= htmlspecialchars($prod['sku']) ?>" class="short" required>
        <select name="category" class="short">
          <option <?= $prod['category']=='Men'?'selected':'' ?>>Men</option>
          <option <?= $prod['category']=='Women'?'selected':'' ?>>Women</option>
          <option <?= $prod['category']=='Kids'?'selected':'' ?>>Kids</option>
          <option <?= $prod['category']=='Accessories'?'selected':'' ?>>Accessories</option>
        </select>
        <select name="gender" class="short">
          <option <?= $prod['gender']=='Unisex'?'selected':'' ?>>Unisex</option>
          <option <?= $prod['gender']=='Men'?'selected':'' ?>>Men</option>
          <option <?= $prod['gender']=='Women'?'selected':'' ?>>Women</option>
          <option <?= $prod['gender']=='Kids'?'selected':'' ?>>Kids</option>
        </select>
        <input type="text" name="brand" value="<?= htmlspecialchars($prod['brand']) ?>" class="short">
        <input type="number" name="price" value="<?= htmlspecialchars($prod['price']) ?>" class="short" required>
        <input type="number" name="discount_price" value="<?= htmlspecialchars($prod['discount_price']) ?>" class="short">
        <input type="number" name="stock" value="<?= intval($prod['stock']) ?>" class="short" required>
        <input type="text" name="sizes" value="<?= htmlspecialchars(implode(',', json_decode($prod['sizes'],true)??[])) ?>" class="medium">
        <input type="text" name="colors" value="<?= htmlspecialchars(implode(',', json_decode($prod['colors'],true)??[])) ?>" class="medium">
        <input type="text" name="material" value="<?= htmlspecialchars($prod['material']) ?>" class="medium">
        <textarea name="description"><?= htmlspecialchars($prod['description']) ?></textarea>

        <!-- Existing images -->
        <div class="gallery">
          <?php $imgs = json_decode($prod['images'], true) ?? []; ?>
          <?php foreach($imgs as $img): ?>
            <div>
              <img src="uploads/<?= htmlspecialchars($img) ?>">
              <a href="delete-product-image.php?pid=<?= $prod['id'] ?>&img=<?= urlencode($img) ?>" class="delete-btn">X</a>
            </div>
          <?php endforeach; ?>
        </div>
        <label>Add Photos:</label>
        <input type="file" name="images[]" multiple>

        <!-- Attributes -->
        <?php $attr = json_decode($prod['attributes'], true) ?? []; ?>
        <div id="attr-box-<?= $prod['id'] ?>">
          <?php foreach($attr as $k=>$v): ?>
            <div>
              <input type="text" name="attr_name[]" value="<?= htmlspecialchars($k) ?>">
              <input type="text" name="attr_value[]" value="<?= htmlspecialchars($v) ?>">
            </div>
          <?php endforeach; ?>
        </div>
        <button type="button" onclick="addAttr(<?= $prod['id'] ?>)">+ Add Attribute</button>

        <button type="submit" name="edit_product">Save Changes</button>
      </form>
    <?php endforeach; ?>
  </div>
</div>

<script>
function openEdit(id){
  const form = document.getElementById('edit-' + id);
  form.style.display = form.style.display === 'none' ? 'flex' : 'none';
}
function addAttr(id=null){
  const box = id ? document.getElementById('attr-box-'+id) : document.getElementById('attr-box');
  const div = document.createElement('div');
  div.innerHTML = '<input type="text" name="attr_name[]" placeholder="Name"> <input type="text" name="attr_value[]" placeholder="Value">';
  box.appendChild(div);
}
</script>
<?php include "footer.php"; ?>
</body>
</html>
