<?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'] ?? '');
    $slug = trim($_POST['slug'] ?? '');
    $price = floatval($_POST['price'] ?? 0);
    $description = trim($_POST['description'] ?? '');
    $measurements = $_POST['measurements'] ?? [];
    $stock = intval($_POST['stock'] ?? 10); // default 10 if not provided
    $sold_quantity = 0;
    $remaining_stock = $stock;
    $image_name = '';

    // Handle image upload
    if (!empty($_FILES['image']['name'])) {
        $image_name = time() . "_" . basename($_FILES['image']['name']);
        move_uploaded_file($_FILES['image']['tmp_name'], "uploads/$image_name");
    }

    $stmt = $conn->prepare("INSERT INTO products 
        (name, slug, price, image, description, measurements, stock, remaining_stock, sold_quantity, created_at) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
    $stmt->bind_param("ssdsssiii", $name, $slug, $price, $image_name, $description, json_encode($measurements), $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'] ?? '');
    $slug = trim($_POST['slug'] ?? '');
    $price = floatval($_POST['price'] ?? 0);
    $description = trim($_POST['description'] ?? '');
    $measurements = $_POST['measurements'] ?? [];
    $stock = intval($_POST['stock'] ?? 0);

    // Handle image upload
    if (!empty($_FILES['image']['name'])) {
        // Delete old image
        $stmt = $conn->prepare("SELECT image FROM products WHERE id=?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->bind_result($old_image);
        $stmt->fetch();
        $stmt->close();
        if ($old_image && file_exists("uploads/$old_image")) unlink("uploads/$old_image");

        $image_name = time() . "_" . basename($_FILES['image']['name']);
        move_uploaded_file($_FILES['image']['tmp_name'], "uploads/$image_name");

        $stmt = $conn->prepare("UPDATE products 
            SET name=?, slug=?, price=?, description=?, measurements=?, image=?, stock=?, remaining_stock=? 
            WHERE id=?");
        $stmt->bind_param("ssdsssiii", $name, $slug, $price, $description, json_encode($measurements), $image_name, $stock, $stock, $id);
    } else {
        $stmt = $conn->prepare("UPDATE products 
            SET name=?, slug=?, price=?, description=?, measurements=?, stock=?, remaining_stock=? 
            WHERE id=?");
        $stmt->bind_param("ssdssiii", $name, $slug, $price, $description, json_encode($measurements), $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="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">

<link rel="stylesheet" href="admin-sidebar.css">
<style>
/* Wrapper */
.dashboard-wrapper { display:flex; min-height:100vh; margin-top:60px; }

/* Sidebar + main content */
.main-content { flex:1; padding:20px; background:#111; color:#fff; margin-left:250px; }

/* Forms */
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; }

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

/* Product list items */
.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:8px 12px; border-radius:6px; text-decoration:none; display:inline-block; }
.delete-btn:hover { background:#f33 !important; }

/* Measurements input fields */
.measurements { display:flex; gap:10px; flex-wrap:wrap; justify-content:center; }
.measurements input { width:80px; }
</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="slug" placeholder="Slug" class="short" required>
      <input type="number" name="price" placeholder="Price" class="short" required>
      <input type="number" name="stock" placeholder="Stock Qty" class="short" required>
      <input type="file" name="image">
      <textarea name="description" placeholder="Description"></textarea>

      <div class="measurements">
        <input type="text" name="measurements[]" placeholder="chest">
        <input type="text" name="measurements[]" placeholder="waist">
        <input type="text" name="measurements[]" placeholder="hips">
      </div>

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

    <!-- Existing Products -->
    <?php foreach($products as $prod): ?>
      <div class="product-item">
        <img src="uploads/<?= htmlspecialchars($prod['image']) ?>" alt="<?= htmlspecialchars($prod['name']) ?>">
        <div class="product-details">
          <strong><?= htmlspecialchars($prod['name']) ?></strong><br>
          Price: KES <?= number_format($prod['price']) ?><br>
          Stock: <?= intval($prod['stock']) ?><br>
          Slug: <?= htmlspecialchars($prod['slug']) ?>
        </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 (hidden by default) -->
      <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="slug" value="<?= htmlspecialchars($prod['slug']) ?>" class="short" required>
        <input type="number" name="price" value="<?= htmlspecialchars($prod['price']) ?>" class="short" required>
        <input type="number" name="stock" value="<?= intval($prod['stock']) ?>" class="short" required>
        <input type="file" name="image">
        <textarea name="description"><?= htmlspecialchars($prod['description']) ?></textarea>

        <div class="measurements">
          <?php $m = json_decode($prod['measurements'], true) ?? []; ?>
          <input type="text" name="measurements[]" value="<?= htmlspecialchars($m[0] ?? '') ?>" placeholder="chest">
          <input type="text" name="measurements[]" value="<?= htmlspecialchars($m[1] ?? '') ?>" placeholder="waist">
          <input type="text" name="measurements[]" value="<?= htmlspecialchars($m[2] ?? '') ?>" placeholder="hips">
        </div>

        <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';
}
</script>
<?php include "footer.php"; ?>
</body>
</html>
