<?php
$conn = new mysqli("localhost", "root", "", "bella");

function slugify($text) {
  $text = strtolower(trim($text));
  $text = preg_replace('/[^a-z0-9]+/', '-', $text);
  return trim($text, '-');
}

$name = $_POST['name'];
$price = $_POST['price'];
$info = $_POST['info'];
$image = $_FILES['image']['name'];

$slug = slugify($name);

// Ensure slug is unique
$check = $conn->prepare("SELECT id FROM products WHERE slug = ?");
$check->bind_param("s", $slug);
$check->execute();
$check->store_result();
if ($check->num_rows > 0) {
  $slug .= '-' . uniqid(); // make it unique
}

$target = "uploads/" . basename($image);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
  $stmt = $conn->prepare("INSERT INTO products (name, price, info, image, slug) VALUES (?, ?, ?, ?, ?)");
  $stmt->bind_param("sdsss", $name, $price, $info, $image, $slug);
  $stmt->execute();
  echo "Product uploaded successfully!";
} else {
  echo "Failed to upload image.";
}

$conn->close();
?>
