<?php
include 'db.php';

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

$id = $_POST['id'];
$name = $_POST['name'];
$type = $_POST['type'];
$status = $_POST['status'];
$slug = $_POST['slug'];

/* SAFETY SLUG */
if(!$slug){
    $slug = strtolower($name);
    $slug = preg_replace('/[^a-z0-9]+/', '-', $slug);
    $slug = trim($slug, '-');
}

if(!$id){
    echo json_encode([
        "status" => "error",
        "message" => "Invalid ID"
    ]);
    exit;
}

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

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

/* UPDATE */
$update = mysqli_query($conn,"
UPDATE stone_materials 
SET 
    name='$name',
    slug='$slug',
    type='$type',
    status='$status'
WHERE id='$id'
");

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