<?php
include 'db.php';

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

if($action === 'list'){
    $meals_res = $conn->query("SELECT id, meal_name FROM meals ORDER BY meal_name ASC");
    $data = [];

    while($meal = $meals_res->fetch_assoc()){
        $meal_id = $meal['id'];

        $ingredients_stmt = $conn->prepare("
            SELECT ma.id AS assign_id, mp.id AS parameter_id, mp.material_id, mp.qty_per_people, mp.people_count, mp.meal_type, p.name AS material_name
            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
            WHERE ma.meal_id = ?
            ORDER BY ma.id ASC
        ");
        $ingredients_stmt->bind_param("i", $meal_id);
        $ingredients_stmt->execute();
        $res = $ingredients_stmt->get_result();

        $ingredients = [];
        while($ing = $res->fetch_assoc()){
            $ingredients[] = [
                'id' => $ing['assign_id'], // assignment id for remove button
                'parameter_id' => $ing['parameter_id'],
                'material_id' => $ing['material_id'],
                'material_name' => $ing['material_name'],
                'qty_per_people' => floatval($ing['qty_per_people']),
                'people_count' => intval($ing['people_count']),
                'meal_type' => $ing['meal_type']
            ];
        }

        if(count($ingredients) > 0){
            // Use the first ingredient's meal_type as meal type for the table
            $meal['meal_type'] = $ingredients[0]['meal_type'];
            $meal['ingredients'] = $ingredients;
            $data[] = $meal;
        }
    }

    echo json_encode($data);
    exit;
}

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;
    }

    if(!in_array($meal_type, ['Walk-in','Conference'])){
        echo "Invalid meal type"; exit;
    }

    foreach(explode(',', $parameter_ids) as $param_id){
        $param_id = intval($param_id);
        if($param_id > 0){
            // Update the 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();

            // Check if already assigned
            $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;
}

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

else{
    echo "Invalid action";
}
