<?php
include 'db.php';
$meal_id = intval($_POST['meal_id'] ?? 0);
if(!$meal_id) exit('Invalid meal');

// Already assigned
$assignedQ = $conn->query("
    SELECT mm.material_id, p.name, mp.qty_per_people, mp.people_count
    FROM meal_materials mm
    JOIN meal_parameters mp ON mp.material_id=mm.material_id
    JOIN products p ON p.id=mp.material_id
    WHERE mm.meal_id=$meal_id
    ORDER BY p.name
");

// Available (not assigned)
$availableQ = $conn->query("
    SELECT mp.material_id, p.name, mp.qty_per_people, mp.people_count
    FROM meal_parameters mp
    JOIN products p ON p.id=mp.material_id
    WHERE mp.material_id NOT IN (SELECT material_id FROM meal_materials WHERE meal_id=$meal_id)
    ORDER BY p.name
");

echo "<h5>✅ Assigned Materials</h5>";
if($assignedQ->num_rows == 0){
    echo "<div class='alert alert-warning'>No materials assigned yet.</div>";
} else {
    echo "<ul>";
    while($r = $assignedQ->fetch_assoc()){
        echo "<li>{$r['name']} ({$r['qty_per_people']} kg per {$r['people_count']} people) 
        <button class='btn btn-sm btn-danger removeBtn' data-material='{$r['material_id']}'>Remove</button></li>";
    }
    echo "</ul>";
}

if($availableQ->num_rows > 0){
    echo "<h5 class='mt-3'>➕ Assign More Materials</h5><ul>";
    while($r = $availableQ->fetch_assoc()){
        echo "<li>{$r['name']} ({$r['qty_per_people']} kg per {$r['people_count']} people) 
        <button class='btn btn-sm btn-success assignBtn' data-material='{$r['material_id']}'>Assign</button></li>";
    }
    echo "</ul>";
}
