
  <script>
      $(document).ready(function() {
    // Function to handle live search as user types
    $('#ingredientSearch').on('input', function() {
        var searchQuery = $(this).val().trim(); // Get the trimmed search query

        if (searchQuery.length > 0) {
            $.ajax({
                url: './database/search_ingredient.kts.php', // Replace with your PHP script path
                method: 'GET',
                data: { search: searchQuery },
                dataType: 'json',
                success: function(response) {
                    displayIngredientResults(response);
                },
                error: function(error) {
                    console.log('Error:', error);
                }
            });
        } else {
            $('#ingredientResults').empty(); // Clear results if search query is empty
        }
    });

    // Function to handle adding an ingredient
    function addIngredient(ingredient, quantity) {
        $.ajax({
            url: './database/add_to_recipe.kts.php',
            method: 'POST',
            data: {
                ingredient: ingredient,
                unit: ingredient.unit,
                quantity: quantity
            },
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    alert('Ingredient added to recipe successfully!');
                    fetchRecipeItems();
                } else {
                    alert('Failed to add ingredient to recipe.');
                }
            },
            error: function(error) {
                console.log('Error:', error);
            }
        });
    }

    // Function to display search results dynamically
    function displayIngredientResults(ingredients) {
        var resultsDiv = $('#ingredientResults');
        resultsDiv.empty();

        if (ingredients.length > 0) {
            var table = $('<table class="table table-striped"></table>');
            var tableHead = $('<thead><tr><th>Code</th><th>Name</th><th>Quantity</th><th>Action</th></tr></thead>');
            var tableBody = $('<tbody></tbody>');

            ingredients.forEach(function(ingredient) {
                var row = $('<tr></tr>');
                var idCell = $('<td>' + ingredient.id + '</td>');
                var nameCell = $('<td>' + ingredient.name + '</td>');
                var quantityCell = $('<td><input type="number" class="form-control" placeholder="Quantity"></td>');
                var addButton = $('<button class="btn btn-primary btn-sm">Add</button>');

                addButton.click(function() {
                    addIngredient({
                        id: ingredient.id,
                        name: ingredient.name,
                        unit: ingredient.unit
                    }, quantityCell.find('input').val());
                });

                var actionCell = $('<td></td>').append(addButton);
                row.append(idCell, nameCell, quantityCell, actionCell);
                tableBody.append(row);
            });

            table.append(tableHead, tableBody);
            resultsDiv.append(table);
        } else {
            resultsDiv.append('<p>No ingredients found.</p>');
        }
    }

    // Function to fetch recipe items
    function fetchRecipeItems() {
        $.ajax({
            url: './database/get_recipe.kts.php',
            method: 'GET',
            dataType: 'json',
            success: function(response) {
                var recipeItemsDiv = $('#recipe_items');
                recipeItemsDiv.empty();

                if (response.length > 0) {
                    var table = $('<table class="table table-striped"></table>');
                    var tableHead = $('<thead><tr><th>Name</th><th>Quantity</th><th>Unit</th><th>Action</th></tr></thead>');
                    var tableBody = $('<tbody></tbody>');

                    response.forEach(function(item, index) {
                        var row = $('<tr></tr>');
                        var nameCell = $('<td>' + item.name + '</td>');
                        var quantityCell = $('<td>' + item.quantity + '</td>');
                        var unitCell = $('<td>' + item.unit + '</td>');
                        var deleteIcon = $('<i class="fa fa-trash" style="cursor:pointer;"></i>');

                        deleteIcon.click(function() {
                            $.ajax({
                                url: './database/delete_from_recipe.kts.php',
                                method: 'POST',
                                data: { index: index },
                                dataType: 'json',
                                success: function(response) {
                                    if (response.status === 'success') {
                                        alert('Ingredient removed from recipe successfully!');
                                        fetchRecipeItems();
                                    } else {
                                        alert('Failed to remove ingredient from recipe.');
                                    }
                                },
                                error: function(error) {
                                    console.log('Error:', error);
                                }
                            });
                        });

                        var actionCell = $('<td></td>').append(deleteIcon);
                        row.append(nameCell, quantityCell, unitCell, actionCell);
                        tableBody.append(row);
                    });

                    table.append(tableHead, tableBody);
                    recipeItemsDiv.append(table);
                } else {
                    recipeItemsDiv.append('<p>No recipe items added.</p>');
                }
            },
            error: function(error) {
                console.log('Error:', error);
            }
        });
    }

    // Initial fetch to display recipe items when the page loads
    fetchRecipeItems();
});


  </script>


<script>
    $(document).ready(function() {
        // Function to handle food search on input change
        $('#foodSearch').on('input', function() {
            var searchTerm = $(this).val().trim();

             if (searchTerm.length > 0) {
            $.ajax({
                url: './database/search_food.kts.php', // Replace with your search food endpoint
                method: 'GET',
                data: { foodSearch: searchTerm },
                dataType: 'json',
                success: function(response) {
                    displayFoodResults(response); // Display search results
                },
                error: function(error) {
                    console.log('Error:', error);
                 }
            });
        } else {
            $('#foodResults').empty(); // Clear results if search query is empty
        }
    });

    // Function to handle adding an food
            function addFoodToSession(foodId, foodName, quantity) {
            $.ajax({
                url: './database/add_food_to_session.kts.php', 
                method: 'POST',
                data: {
                    food_id: foodId,
                    food_name: foodName,
                    quantity: quantity
                },
                dataType: 'json',
              success: function(response) {
                if (response.status === 'success') {
                    alert('Food added to plater successfully!');
                    fetchAndDisplayFoodItems();
                } else {
                    alert('Failed to add foods to platter.');
                }
            },
            error: function(error) {
                console.log('Error:', error);
            }
        });
    }

        // Function to display food search results
        function displayFoodResults(foods) {
            var resultsDiv = $('#foodResults');
            resultsDiv.empty();

            if (foods.length > 0) {
            var table = $('<table class="table table-striped"></table>');
            var tableHead = $('<thead><tr><th>Code</th><th>Name</th><th>Quantity</th><th>Action</th></tr></thead>');    
            var tableBody = $('<tbody></tbody>');

                foods.forEach(function(food) {
                    var row = $('<tr></tr>');
                    var foodCell = $('<td>' + food.food_id + '</td>');
                    var nameCell = $('<td>' + food.name + '</td>');
                    var idCell = $('<td>' + food.id + '</td>'); 
                    var quantityCell = $('<td><input type="number" class="form-control" placeholder="Quantity"></td>');
                    var addFoodButton = $('<button class="btn btn-primary btn-sm">Add</button>');

                    addFoodButton.click(function() {
                        var quantity = quantityCell.find('input').val();
                        addFoodToSession(food.id, food.name, quantity); // Pass food.id, food.name, and quantity
                    });

                    var actionCell = $('<td></td>').append(addFoodButton);
                    row.append(nameCell, idCell, quantityCell, actionCell);
                    tableBody.append(row);
                });

                table.append(tableBody);
                resultsDiv.append(table);
            } else {
                resultsDiv.append('<p>No foods found.</p>');
            }
        }
        
        

  // Function to fetch and display food items from session
        function fetchAndDisplayFoodItems() {
            $.ajax({
                url: './database/get_fooditems.kts.php', // Replace with your get food items from session endpoint
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    var tableHtml = '<table class="table table-striped">';
                    tableHtml += '<thead><tr><th>Name</th><th>Quantity</th><th>Action</th></tr></thead>';
                    tableHtml += '<tbody>';

                    if (response.length > 0) {
                        response.forEach(function(item) {
                            var row = '<tr>';
                            row += '<td>' + item.food_name + '</td>';
                            row += '<td>' + item.quantity + '</td>';
                            row += '<td><button class="btn btn-danger btn-sm delete-food-item" data-id="' + item.food_id + '">Delete</button></td>';
                            row += '</tr>';
                            tableHtml += row;
                        });
                    } else {
                        tableHtml += '<tr><td colspan="3">No food items selected.</td></tr>';
                    }

                    tableHtml += '</tbody></table>';

                    // Insert the dynamically created table HTML into the #foodItemsTableBody div
                    $('#foodItemsTable').html(tableHtml);

                    // Attach click event listener to delete icons
                    $('.delete-food-item').click(function() {
                        var foodId = $(this).data('id');
                        deleteFoodFromSession(foodId);
                    });
                },
                error: function(error) {
                    console.log('Error fetching food items:', error);
                    $('#foodItemsTable').html('<p>Error fetching food items.</p>');
                }
            });
        }
    
        // Function to delete food item from session
        function deleteFoodFromSession(foodId) {
            $.ajax({
                url: './database/delete_food_from_session.php', // Replace with your delete food from session endpoint
                method: 'POST',
                data: { food_id: foodId },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        fetchAndDisplayFoodItems(); // Refresh the table after deletion
                        alert('Food item deleted from session successfully!');
                    } else {
                        alert('Failed to delete food item from session.');
                    }
                },
                error: function(error) {
                    console.log('Error:', error);
                }
            });
        }

      
        // Initial fetch and display of food items from session when the page loads
        fetchAndDisplayFoodItems();
    });
</script>