<?php
include 'db.php';

$action = $_POST['action'] ?? '';
$meal_id = intval($_POST['meal_id'] ?? 0);

if($action=='remove'){
    $material_id = intval($_POST['material_id'] ?? 0);
    $conn->query("DELETE FROM meal_recipes WHERE meal_id=$meal_id AND material_id=$material_id");
    exit('Material removed successfully.');
}

if($action=='add'){
    $material_id = intval($_POST['material_id'] ?? 0);
    // Get pre-defined qty from products table
    $qty = $conn->query("SELECT qty_required FROM products WHERE id=$material_id")->fetch_assoc()['qty_required'] ?? 0;
    if($qty <= 0) exit('Material quantity is not set in system.');

    $conn->query("INSERT INTO meal_recipes (meal_id, material_id, qty_required) VALUES ($meal_id, $material_id, $qty)");
    exit('Material added successfully with pre-defined quantity.');
}
