<?php
include("../db/cn.php");

if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

// Fetch distinct product names for live search
$sql12 = "SELECT DISTINCT name FROM products";
$result12 = $connection->query($sql12);

$categories = [];
if ($result12->num_rows > 0) {
    while ($row12 = $result12->fetch_assoc()) {
        $categories[] = $row12['name'];
    }
}

// Check if a name is provided to fetch product details
if (isset($_GET['name'])) {
    $name = $connection->real_escape_string($_GET['name']);
    $sql = "SELECT * FROM products WHERE name = '$name'";
    $result = $connection->query($sql);

    if ($result->num_rows > 0) {
        $productDetails = $result->fetch_assoc();
        echo json_encode($productDetails);
    } else {
        echo json_encode(['error' => 'Product not found']);
    }
    exit; // Ensure no further processing occurs for AJAX requests
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Live Search</title>
<style>
    #searchResults {
        position: absolute;
        background-color: #f9f9f9;
        border: 1px solid #ddd;
        max-height: 200px;
        overflow-y: auto;
        width: 85%;
        display: none;
    }
    #searchResults div {
        padding: 10px;
        cursor: pointer;
    }
    #searchResults div:hover {
        background-color: #f1f1f1;
    }
</style>
</head>
<body>
<h2>Live Search</h2>
<input type="text" id="searchInput" autocomplete="off" class="form-control" placeholder="Search Company">
<div id="searchResults"></div>

<div class="row">
    <div class="col-sm-4">
        <form id="productForm" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
            <div class="form-group">
                <label>Product ID</label>
                <input type="text" name="product_id" id="product_id" class="form-control" />
            </div>
            <div class="form-group">
                <label>Product</label>
                <input type="text" name="name1" id="name1" class="form-control" />
            </div>
            <div class="form-group">
                <label>Company</label>
                <input type="text" name="category1" id="category1" class="form-control" />
            </div>
            <div class="form-group">
                <label>Category</label>
                <input type="text" name="company_category" id="company_category" class="form-control" />
            </div>
            <div class="form-group">
                <label>Pack Quantity</label>
                <input type="text" name="stock_qty1" id="stock_qty1" class="form-control" onkeyup="calculateQtyPerUnit(); calculateTotalAmount();" />
            </div>
            <div class="form-group">
                <label>Free / Loose Quantity</label>
                <input type="text" name="free_sample" id="free_sample" class="form-control" onkeyup="calculateQtyPerUnit()" />
            </div>
            <div class="form-group">
                <label>Retail Price Per Pack</label>
                <input type="text" name="retail_price" id="retail_price" class="form-control" onkeyup="calculateTradePrice(); calculateRetailAmount();" />
            </div>
            <!-- Add more fields as necessary -->
        </form>
    </div>
    <div class="col-sm-4">
        <div class="form-group">
            <label>% Apply</label>
            <input type="text" name="percentage" id="percentage" class="form-control" onkeyup="calculateTradePrice()" />
        </div>
        <div class="form-group">
            <label>% Extra </label>
            <input type="text" class="form-control" name="extra_percentage" id="extra_percentage" onkeyup="calculateTradePrice()" />
        </div>
        <div class="form-group">
            <label>Trade Price Per Pack</label>
            <input type="text" name="trade_price" id="trade_price" class="form-control" onkeyup="calculateTotalAmount()" />
        </div>
        <div class="form-group">
            <label>No of Unit Per Pack</label>
            <input type="text" name="number_unit" id="number_unit" class="form-control" onkeyup="calculatePricePerUnit(); calculateQtyPerUnit(); calculateRetailAmount();" />
        </div>
        <div class="form-group">
            <label>R.P Per Unit</label>
            <input type="text" name="rp_number_unit" id="rp_number_unit" class="form-control" />
        </div>
        <div class="form-group">
            <label>T.P Per Unit</label>
            <input type="text" name="price1" id="price1" class="form-control" />
        </div>
        <div class="form-group">
            <label>Product Unit</label>
            <input type="text" name="unit_pr1" id="unit_pr1" class="form-control" />
        </div>
    </div>
    <div class="col-sm-4">
        <div class="form-group">
            <label>Total Quantity</label>
            <input type="text" name="total_quantity" id="total_quantity" class="form-control" />
        </div>
        <div class="form-group">
            <label>Total Amount</label>
            <input type="text" name="total_amount" id="total_amount" class="form-control" />
        </div>
        <div class="form-group">
            <label>Supplier</label>
            <input type="text" name="supplier_name" id="supplier_name" class="form-control" onkeyup="searchSupplier(this.value)" />
        </div>
        <div class="form-group">
            <label>Expiry</label>
            <input type="date" name="expiry" id="expiry" class="form-control" />
        </div>
        <div class="form-group">
            <label>Payment Method</label>
            <select name="paid_by" id="paid_by" class="form-control">
                <option value="">Select Payment</option>
                <option value="cash">Cash</option>
                <option value="credit">Credit</option>
            </select>
        </div>
        <button type="submit" name="submit2" class="btn btn-dark form-control">Enter</button>
    </div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const categories = <?php echo json_encode($categories); ?>;
    const searchInput = document.getElementById('searchInput');
    const searchResults = document.getElementById('searchResults');
    const productForm = document.getElementById('productForm');

    searchInput.addEventListener('input', function () {
        const query = this.value.trim().toLowerCase();
        if (query === '') {
            searchResults.style.display = 'none';
            return;
        }
        const filteredCategories = categories.filter(category => category.toLowerCase().includes(query));
        renderResults(filteredCategories);
    });

    searchInput.addEventListener('blur', function () {
        setTimeout(() => {
            searchResults.style.display = 'none';
        }, 200); // Delay hiding dropdown to allow click event on dropdown items
    });

    searchResults.addEventListener('mousedown', function (e) {
        if (e.target.tagName === 'DIV') {
            searchInput.value = e.target.textContent;
            fetchProductDetails(e.target.textContent);
            searchResults.style.display = 'none';
        }
    });

    function renderResults(results) {
        let html = '';
        results.forEach(result => {
            html += `<div>${result}</div>`;
        });
        searchResults.innerHTML = html;
        searchResults.style.display = 'block';
    }

    function fetchProductDetails(name) {
        fetch(`<?php echo $_SERVER['PHP_SELF']; ?>?name=${encodeURIComponent(name)}`)
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    alert(data.error);
                } else {
                    populateForm(data);
                }
            })
            .catch(error => {
                console.error('Error fetching product details:', error);
            });
    }

    function populateForm(data) {
        document.getElementById('product_id').value = data.product_id || '';
        document.getElementById('name1').value = data.name || '';
        document.getElementById('category1').value = data.category || '';
        document.getElementById('company_category').value = data.company_category || '';
        document.getElementById('stock_qty1').value = data.stock_qty || '';
        document.getElementById('free_sample').value = data.free_sample || '';
        document.getElementById('retail_price').value = data.retail_price || '';
        document.getElementById('percentage').value = data.percentage || '';
        document.getElementById('extra_percentage').value = data.extra_percentage || '';
        document.getElementById('trade_price').value = data.trade_price || '';
        document.getElementById('number_unit').value = data.number_unit || '';
        document.getElementById('rp_number_unit').value = data.rp_number_unit || '';
        document.getElementById('price1').value = data.price1 || '';
        document.getElementById('unit_pr1').value = data.unit_pr1 || '';
        document.getElementById('total_quantity').value = data.total_quantity || '';
        document.getElementById('total_amount').value = data.total_amount || '';
        document.getElementById('supplier_name').value = data.supplier_name || '';
        document.getElementById('expiry').value = data.expiry || '';
        document.getElementById('paid_by').value = data.paid_by || '';
    }
});
</script>
</body>
</html>
