<?php
include 'db.php';

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

if($action === 'list'){
    $meal_id = intval($_POST['meal_id'] ?? 0);
    $meal_type = $_POST['meal_type'] ?? '';

    if(!$meal_id || !$meal_type){ echo json_encode([]); exit; }

    // Get assigned ingredients along with available stock
    $stmt = $conn->prepare("
     SELECT 
    ma.id AS assign_id,
    mp.id AS parameter_id,
    mp.material_id,
    mp.qty_per_people,
    mp.meal_type,
    p.name AS material_name,
    p.quantity + ps.quantity AS available_qty,
    COALESCE(ps.quantity,0) AS production_stock_qty
FROM meal_assignments ma
INNER JOIN meal_parameters mp ON mp.id = ma.parameter_id
LEFT JOIN products p ON p.id = mp.material_id
LEFT JOIN product_stock ps ON ps.product_id = mp.material_id
WHERE ma.meal_id = ? 
  AND mp.meal_type = ?
ORDER BY ma.id ASC;
    ");
    $stmt->bind_param("is", $meal_id, $meal_type);
    $stmt->execute();
    $res = $stmt->get_result();

    $data = [];
    while($row = $res->fetch_assoc()){
        $data[] = [
            'id' => intval($row['assign_id']),
            'parameter_id' => intval($row['parameter_id']),
            'material_id' => intval($row['material_id']),
            'material_name' => $row['material_name'],
            'qty_per_people' => floatval($row['qty_per_people']),
            'meal_type' => $row['meal_type'],
            'available_qty' => floatval($row['available_qty'])  // <-- include available stock
        ];
    }

    echo json_encode($data);
    exit;
}

// ================== Assign ingredients to meal ==================
elseif($action === 'assign'){
    $meal_id = intval($_POST['meal_id'] ?? 0);
    $meal_type = $_POST['meal_type'] ?? '';
    $parameter_ids = $_POST['parameter_ids'] ?? '';

    if(!$meal_id || !$meal_type || !$parameter_ids){ echo "Invalid input"; exit; }

    foreach(explode(',', $parameter_ids) as $param_id){
        $param_id = intval($param_id);
        if($param_id > 0){
            // Update meal_type in meal_parameters
            $stmt1 = $conn->prepare("UPDATE meal_parameters SET meal_type=? WHERE id=?");
            $stmt1->bind_param("si", $meal_type, $param_id);
            $stmt1->execute();

            // Insert assignment if not exists
            $stmt2 = $conn->prepare("SELECT id FROM meal_assignments WHERE meal_id=? AND parameter_id=? LIMIT 1");
            $stmt2->bind_param("ii", $meal_id, $param_id);
            $stmt2->execute();
            $res2 = $stmt2->get_result();
            if($res2->num_rows == 0){
                $stmt3 = $conn->prepare("INSERT INTO meal_assignments (meal_id, parameter_id) VALUES (?,?)");
                $stmt3->bind_param("ii", $meal_id, $param_id);
                $stmt3->execute();
            }
        }
    }
    echo "Ingredients assigned successfully";
    exit;
}

// ================== Remove ingredient ==================
elseif($action === 'remove'){
    $param_id = intval($_POST['param_id'] ?? 0);
    if($param_id > 0){
        $stmt = $conn->prepare("DELETE FROM meal_assignments WHERE id=?");
        $stmt->bind_param("i", $param_id);
        $stmt->execute();
        echo "Ingredient removed successfully";
    } else { echo "Invalid request"; }
    exit;
}

else{
    echo "Invalid action";
}