<?php
// Assuming you have a database connection established
require_once('shikanisha.kts.php');

if (isset($_POST['searchTerm'])) {
    $searchTerm = $_POST['searchTerm'];

    // Assuming your database table is named 'products'
    $query = "SELECT `product_id`, `product_name`, `buying_price` FROM `products` WHERE `product_name` LIKE '%$searchTerm%'";
    
    // Execute the query and fetch results
    $result = mysqli_query($conn, $query);

    if ($result) {
        echo '<div class="table-responsive">';
        echo '<table class="table">';
        echo '<thead>';
        echo '<tr>';
        echo '<th>Product Name</th>';
        echo '<th>Buying Price</th>';
        echo '<th>Quantity</th>';
        echo '<th>Action</th>';
        echo '</tr>';
        echo '</thead>';
        echo '<tbody>';
        
        while ($row = mysqli_fetch_assoc($result)) {
            echo '<tr>';
            echo '<td>' . $row['product_name'] . '</td>';
            echo '<td><input type="text" class="form-control input-rounded buying-price" placeholder="Buying Price" value="' . $row['buying_price'] . '"/></td>';
            echo '<td><input type="text" class="form-control input-rounded quantity" placeholder="Quantity" /></td>';
            echo '<td><button class="btn btn-secondary" onclick="addToCart(' . $row['product_id'] . ', \'' . $row['product_name'] . '\')">Add to Cart</button></td>';
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
        echo '</div>';
    }
}
?>
<script>
function addToCart(productId, productName) {
    var buyingPrice = parseFloat($('.buying-price').val());
    var quantity = parseInt($('.quantity').val());

    if (!isNaN(buyingPrice) && !isNaN(quantity) && quantity > 0) {
        // AJAX request to the server-side script (update_cart.php)
        $.ajax({
            url: './database/update_cart.kts.php',
            method: 'POST',
            data: {
                productId: productId,
                productName: productName,
                buyingPrice: buyingPrice,
                quantity: quantity
            },
            success: function (response) {
                console.log(response);
                // You can update the UI here if needed
                // Clear the input values
                $('.buying-price').val('');
                $('.quantity').val('');
                 $('#searchInput').val('');
               $('#searchResults').empty().hide();
            }
        });
    } else {
        alert('Please enter valid values for Buying Price and Quantity.');
    }
}
</script>
