<?php
include 'db.php';

$meal_id = intval($_POST['meal_id'] ?? 0);
$people  = max(1,intval($_POST['people'] ?? 1));

if($meal_id <= 0) exit('No meal selected.');

// ================= MATERIALS PREVIEW ==================
$matQ = $conn->query("
    SELECT mp.material_id, p.name, mp.qty_per_people, mp.people_count,
           COALESCE(ps.quantity,0) AS stock_qty
    FROM meal_parameters mp
    JOIN products p ON mp.material_id=p.id
    LEFT JOIN product_stock ps
        ON p.id=ps.product_id AND ps.store_id=1
    WHERE mp.meal_id=$meal_id
    ORDER BY p.name
");

$materialsPreview = [];
while($row = $matQ->fetch_assoc()){
    $row['total_needed'] = $row['qty_per_people'] * ($people / $row['people_count']);
    $materialsPreview[] = $row;
}

// ================= DISPLAY MATERIALS =================
echo "<h5>📋 Materials Assigned to This Meal</h5>";

if(empty($materialsPreview)){
    echo "<div class='alert alert-warning'>No materials assigned to this meal yet.</div>";
} else {
    echo "<div class='table-responsive'><table class='table table-bordered table-striped'>";
    echo "<thead class='bg-success text-white'>
    <tr><th>#</th><th>Material</th><th>Qty (per {$row['people_count']} people)</th><th>Total Needed</th><th>Stock Available</th><th>Status</th><th>Action</th></tr></thead><tbody>";

    $i=1;
    foreach($materialsPreview as $m){
        $ok = $m['total_needed'] <= $m['stock_qty'];
        echo "<tr>
            <td>{$i}</td>
            <td><strong>".htmlspecialchars($m['name'])."</strong></td>
            <td>".number_format($m['qty_per_people'],3)."</td>
            <td class='text-primary'><strong>".number_format($m['total_needed'],3)."</strong></td>
            <td>".number_format($m['stock_qty'],3)."</td>
            <td>".($ok ? "<span class='badge bg-success'>OK</span>" : "<span class='badge bg-danger'>LOW</span>")."</td>
            <td><button class='btn btn-sm btn-danger removeMaterialBtn' data-meal='$meal_id' data-material='{$m['material_id']}'>Remove</button></td>
        </tr>";
        $i++;
    }
    echo "</tbody></table></div>";
}

// ================= ADD MATERIAL ==================
$newMaterials = $conn->query("
    SELECT id, name FROM products
    WHERE id NOT IN (SELECT material_id FROM meal_parameters WHERE meal_id=$meal_id)
    ORDER BY name
");

if($newMaterials->num_rows > 0){
    echo "<h5 class='mt-3'>➕ Add Material to This Meal</h5>";
    echo "<div class='input-group mb-3'>
            <select class='form-control' id='addMaterialSelect'>
                <option value=''>-- Select Material --</option>";
    while($nm = $newMaterials->fetch_assoc()){
        echo "<option value='{$nm['id']}'>".htmlspecialchars($nm['name'])."</option>";
    }
    echo "</select>
          <button class='btn btn-success' id='addMaterialBtn'>Add</button>
          </div>";
}
?>
<script>
$(document).ready(function(){
    // Remove material
    $('.removeMaterialBtn').click(function(){
        let mealId = $(this).data('meal');
        let materialId = $(this).data('material');
        if(!confirm('Remove this material from the meal?')) return;

        $.post('update_meal_parameters.php', {action:'remove', meal_id:mealId, material_id:materialId}, function(res){
            alert(res);
            $('#mealSelect').trigger('change'); // reload preview
        });
    });

    // Add material (uses pre-set system qty)
    $('#addMaterialBtn').click(function(){
        let mealId = <?= $meal_id ?>;
        let materialId = $('#addMaterialSelect').val();
        if(!materialId){
            alert('Select a material to add');
            return;
        }

        $.post('update_meal_parameters.php', {action:'add', meal_id:mealId, material_id:materialId}, function(res){
            alert(res);
            $('#mealSelect').trigger('change'); // reload preview
        });
    });
});
</script>
