
<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.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.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_food_items_from_session.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>