<?php
include 'db.php';

header('Content-Type: application/json');

$name = $_POST['name'] ?? '';
$type = $_POST['type'] ?? '';
$status = $_POST['status'] ?? 'active';

/* GENERATE SLUG */
$slug = strtolower($name);
$slug = preg_replace('/[^a-z0-9]+/', '-', $slug);
$slug = trim($slug, '-');

if(!$name){
    echo json_encode([
        "status" => "error",
        "message" => "Material name required"
    ]);
    exit;
}

/* ✅ CHECK DUPLICATE (IMPORTANT FIX) */
$check = mysqli_query($conn,"
SELECT id FROM stone_materials 
WHERE slug='$slug' AND type='$type'
");

if(mysqli_num_rows($check) > 0){
    echo json_encode([
        "status" => "error",
        "message" => "Material already exists for this type"
    ]);
    exit;
}

/* INSERT */
$insert = mysqli_query($conn,"
INSERT INTO stone_materials (name,slug,type,status)
VALUES ('$name','$slug','$type','$status')
");

if($insert){
    echo json_encode([
        "status" => "success",
        "message" => "Material added successfully",
        "slug" => $slug
    ]);
} else {
    echo json_encode([
        "status" => "error",
        "message" => mysqli_error($conn)
    ]);
}