<?php
include 'db.php';

$action = $_POST['action'] ?? '';

if($action == 'remove'){
    $id = intval($_POST['id'] ?? 0);
    if($id > 0){
        $conn->query("DELETE FROM meal_parameters WHERE id=$id");
        echo "Parameter removed successfully";
    } else {
        echo "Invalid parameter ID";
    }
}

elseif($action == 'add'){
    $material_id = intval($_POST['material_id'] ?? 0);
    $qty = floatval($_POST['qty_per_people'] ?? 0);
    $people = intval($_POST['people_count'] ?? 0);

    if(!$material_id || !$qty || !$people){
        echo "Invalid input";
        exit;
    }

    // Check if already exists
    $check = $conn->query("SELECT id FROM meal_parameters WHERE material_id=$material_id LIMIT 1");
    if($check->num_rows > 0){
        // Update existing
        $conn->query("UPDATE meal_parameters SET qty_per_people=$qty, people_count=$people WHERE material_id=$material_id");
        echo "Parameter updated successfully";
    } else {
        // Insert new
        $conn->query("INSERT INTO meal_parameters (meal_id, material_id, qty_per_people, people_count) VALUES (0, $material_id, $qty, $people)");
        echo "Parameter added successfully";
    }
} else {
    echo "Invalid action";
}
