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

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

// Get product ID
$id = intval($_GET['id'] ?? 0);
if (!$id) {
    header("Location: admin-products.php");
    exit();
}

// Fetch existing product
$stmt = $conn->prepare("SELECT * FROM products WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$product = $result->fetch_assoc();
$stmt->close();

if (!$product) {
    header("Location: admin-products.php");
    exit();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_product'])) {
    $name        = trim($_POST['name'] ?? '');
    $slug        = trim($_POST['slug'] ?? '');
    $price       = floatval($_POST['price'] ?? 0);
    $description = trim($_POST['description'] ?? '');
    
    // Measurements
    $measurements = [];
    foreach (['chest','waist','hips','shoulders','bust'] as $field) {
        if (!empty($_POST[$field])) {
            $measurements[$field] = floatval($_POST[$field]);
        }
    }
    $measurements_json = json_encode($measurements);

    // Handle new image upload
    $image_name = $product['image']; // keep old image by default
    if (!empty($_FILES['image']['name'])) {
        $target_dir = "uploads/";
        $image_name = time() . "_" . basename($_FILES["image"]["name"]);
        $target_file = $target_dir . $image_name;
        move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);
    }

    $stmt = $conn->prepare("UPDATE products SET name=?, slug=?, price=?, image=?, description=?, measurements=? WHERE id=?");
    $stmt->bind_param("ssdsssi", $name, $slug, $price, $image_name, $description, $measurements_json, $id);
    $stmt->execute();
    $stmt->close();

    header("Location: admin-products.php");
    exit();
}

// Decode measurements for form fields
$measurements = json_decode($product['measurements'], true) ?? [];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit Product - <?= htmlspecialchars($product['name']) ?></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.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; }
h2 { margin-bottom:20px; }
form.edit-product { background:rgba(20,20,20,0.9); padding:20px; border-radius:10px; margin-bottom:30px; }
form.edit-product input, form.edit-product textarea { width:100%; margin-bottom:10px; padding:8px; border-radius:5px; border:none; }
form.edit-product label { display:block; margin-top:10px; }
form.edit-product button { background:#007bff; color:#fff; padding:10px 15px; border:none; border-radius:6px; cursor:pointer; font-weight:bold; }
form.edit-product button:hover { background:#0069d9; }
.current-image { margin-bottom:15px; }
</style>
</head>
<body>

<?php include "navbar.php"; ?>
<div class="dashboard-wrapper">
  <?php include "admin-sidebar.php"; ?>

  <div class="main-content">
    <h2>Edit Product: <?= htmlspecialchars($product['name']) ?></h2>
    <form method="post" enctype="multipart/form-data" class="edit-product">
      <label>Name</label>
      <input type="text" name="name" value="<?= htmlspecialchars($product['name']) ?>" required>
      <label>Slug</label>
      <input type="text" name="slug" value="<?= htmlspecialchars($product['slug']) ?>" required>
      <label>Price (Ksh)</label>
      <input type="number" step="0.01" name="price" value="<?= htmlspecialchars($product['price']) ?>" required>
      
      <label>Current Image</label>
      <?php if ($product['image']): ?>
        <div class="current-image">
          <img src="uploads/<?= htmlspecialchars($product['image']) ?>" alt="<?= htmlspecialchars($product['name']) ?>" style="width:120px; height:120px; object-fit:cover; border-radius:5px;">
        </div>
      <?php endif; ?>
      
      <label>Replace Image</label>
      <input type="file" name="image" accept="image/*">

      <label>Description</label>
      <textarea name="description" rows="3"><?= htmlspecialchars($product['description']) ?></textarea>

      <h4>Measurements (optional)</h4>
      <label>Chest</label>
      <input type="number" step="0.1" name="chest" value="<?= $measurements['chest'] ?? '' ?>">
      <label>Waist</label>
      <input type="number" step="0.1" name="waist" value="<?= $measurements['waist'] ?? '' ?>">
      <label>Hips</label>
      <input type="number" step="0.1" name="hips" value="<?= $measurements['hips'] ?? '' ?>">
      <label>Shoulders</label>
      <input type="number" step="0.1" name="shoulders" value="<?= $measurements['shoulders'] ?? '' ?>">
      <label>Bust</label>
      <input type="number" step="0.1" name="bust" value="<?= $measurements['bust'] ?? '' ?>">

      <button type="submit" name="edit_product">Update Product</button>
    </form>
  </div>
</div>

<?php include "footer.php"; ?>
</body>
</html>
