<?php
$page_title = 'Material Calculator';
require_once('includes/load.php');
page_require_level(2);

$bom_structure = []; // Variabel untuk menyimpan struktur BOM
$selected_product_name = ''; // Variabel untuk nama produk yang dipilih

// Handling form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!empty($_POST['product']) && !empty($_POST['quantity'])) {
        $selected_product = $db->escape($_POST['product']);
        $quantity = floatval($_POST['quantity']); // Mengambil jumlah produk dari form

        $bom_structure = get_bom_structure($selected_product); // Ambil struktur BOM berdasarkan produk
        $selected_product_name = get_product_name_by_part_number($selected_product); // Ambil nama produk

        // Hitung kebutuhan bahan baku berdasarkan BOM dan jumlah produk
        foreach ($bom_structure as &$bom_item) {
            $bom_item['total_quantity'] = $bom_item['qty'] * $quantity;
        }
        unset($bom_item); // Hapus referensi terakhir agar tidak mempengaruhi iterasi berikutnya
    }
}

$products = find_all('products'); // Retrieve distinct products for dropdown

include_once('layouts/header.php');
?>

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">Material Calculator</h3>
            </div>
            <div class="panel-body">
                <form action="calculator_bom.php" method="post" class="form-inline">
                    <div class="form-group">
                        <label for="product">Select Product:</label>
                        <input type="text" class="form-control" name="product" id="product" placeholder="Type to search">
                        <div id="suggestions" class="suggestions"></div>
                    </div>
                    <div class="form-group">
                        <label for="quantity">Quantity:</label>
                        <input type="number" class="form-control" name="quantity" id="quantity" value="<?php echo isset($_POST['quantity']) ? htmlspecialchars($_POST['quantity']) : ''; ?>" step="any" required>
                    </div>
                    <button type="submit" name="calculate" class="btn btn-primary">Calculate</button>
                </form>
            </div>
        </div>
    </div>
</div>

<?php if (!empty($bom_structure)) : ?>
    <div class="row">
        <div class="col-md-12">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">Material Requirements for <?php echo htmlspecialchars($selected_product_name); ?></h3>
                </div>
                <div class="panel-body">
                    <table class="table table-bordered table-hover">
                        <thead>
                            <tr>
                                <th>Child BOM</th>
                                <th>Child Name</th>
                                <th>Quantity per Product</th>
                                <th>Total Quantity Needed</th>
                                <th>UoM</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($bom_structure as $bom_item) : ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($bom_item['child_bom']); ?></td>
                                    <td><?php echo htmlspecialchars($bom_item['child_name']); ?></td>
                                    <td><?php echo number_format($bom_item['qty'], 2); ?></td>
                                    <td><?php echo number_format($bom_item['total_quantity'], 2); ?></td>
                                    <td><?php echo htmlspecialchars($bom_item['uom']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>

<?php include_once('layouts/footer.php'); ?>

<style>
    .suggestions {
        position: absolute;
        width: 100%;
        max-height: 200px;
        overflow-y: auto;
        border: 1px solid #ccc;
        background-color: white;
        z-index: 1;
    }

    .suggestion {
        padding: 10px;
        cursor: pointer;
        transition: background-color 0.2s;
    }

    .suggestion:hover {
        background-color: #f5f5f5;
    }
</style>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const productInput = document.getElementById('product');
    const suggestionsContainer = document.getElementById('suggestions');

    productInput.addEventListener('input', function () {
        const query = productInput.value.toLowerCase();

        fetch(`autocomplete.php?query=${encodeURIComponent(query)}`)
            .then(response => response.json())
            .then(products => {
                suggestionsContainer.innerHTML = '';

                if (products.length > 0) {
                    products.forEach(product => {
                        const suggestionItem = document.createElement('div');
                        suggestionItem.classList.add('suggestion');
                        suggestionItem.textContent = `${product.part_number} - ${product.name}`;
                        suggestionItem.addEventListener('click', function () {
                            productInput.value = product.part_number;
                            suggestionsContainer.innerHTML = '';
                        });
                        suggestionsContainer.appendChild(suggestionItem);
                    });
                } else {
                    suggestionsContainer.innerHTML = '<div class="suggestion">No suggestions</div>';
                }
            })
            .catch(error => console.error(error));
    });
});
</script>
