<?php
include 'db.php';
header('Content-Type: application/json');

$product_id = $_POST['product_id'];
$material_id = $_POST['material_id'];
$calc_type = $_POST['calc_type'];
$sqft_value = $_POST['sqft_value'] ?? null;
$lnft_value = $_POST['lnft_value'] ?? null;

/* CHECK DUPLICATE */
$check = mysqli_query($conn,"
SELECT id FROM product_materials 
WHERE product_id='$product_id' AND material_id='$material_id'
");

if(mysqli_num_rows($check) > 0){
    echo json_encode([
        "status" => "error",
        "message" => "Already assigned"
    ]);
    exit;
}

$insert = mysqli_query($conn,"
INSERT INTO product_materials 
(product_id, material_id, calc_type, sqft_value, lnft_value)
VALUES 
('$product_id','$material_id','$calc_type','$sqft_value','$lnft_value')
");

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