<?php
require_once 'db.php'; // PDO connection, no credentials here

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

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

$slug = slugify($name);

try {
    // Ensure slug is unique
    $stmt = $conn->prepare("SELECT id FROM products WHERE slug = :slug");
    $stmt->bindValue(':slug', $slug, PDO::PARAM_STR);
    $stmt->execute();
    if ($stmt->fetch()) {
        $slug .= '-' . uniqid();
    }
    $stmt = null;

    $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 (:name, :price, :info, :image, :slug)");
        $stmt->bindValue(':name', $name, PDO::PARAM_STR);
        $stmt->bindValue(':price', $price, PDO::PARAM_STR);
        $stmt->bindValue(':info', $info, PDO::PARAM_STR);
        $stmt->bindValue(':image', $image, PDO::PARAM_STR);
        $stmt->bindValue(':slug', $slug, PDO::PARAM_STR);
        $stmt->execute();
        $stmt = null;
        echo "Product uploaded successfully!";
    } else {
        echo "Failed to upload image.";
    }
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>
