<?php
$page_title = 'Add Incoming Goods';
require_once('includes/sql.php');
page_require_level(3);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $transactionDate = $_POST['transactionDate'];

    // Loop through each incoming product data
    foreach ($_POST['data'] as $data) {
        // Escape and extract data
        $productName = $db->escape($data['productName']);
        $quantity = floatval($data['quantity']);
        $remark = $db->escape($data['remark']);
        $loc = $db->escape($data['loc']);

        // Check if the product exists
        $product = find_product_by_part_number($productName);

        if ($product) {
            // Insert incoming goods record
            $partNumber = $product['part_number'];
            $categoryId = $product['categorie_id'];
            $sql = "INSERT INTO incoming_goods (product_id, part_number, quantity, arrival_date, categorie_id, remark, loc) 
                    VALUES ('{$product['id']}', '{$partNumber}', '{$quantity}', '{$transactionDate}', '{$categoryId}', '{$remark}', '{$loc}')";

            if ($db->query($sql)) {
                // If category is 7, allow negative stock in prod_loc and update products
                if ($categoryId == 7) {
                    // Directly decrease quantity from prod_loc, allowing negative stock
                    $updateProdLocSql = "UPDATE prod_loc SET quantity = quantity - {$quantity} WHERE part_number = '{$partNumber}'";
                    $db->query($updateProdLocSql);
                }

                // Increase quantity in products table (for all categories)
                insertStockHistory($partNumber, "Sidoarjo", "IN", $quantity, $remark, 1, "products", "OTHER");
                $updateProductSql = "UPDATE products SET quantity = quantity + {$quantity} WHERE part_number = '{$partNumber}'";
                $db->query($updateProductSql);

                $session->msg('s', 'Incoming goods data added successfully!');
            } else {
                $session->msg('d', 'Failed to add incoming goods.');
            }
        } else {
            $session->msg('d', 'Product not found.');
        }
    }

    // Redirect after processing
    redirect('add_incoming_goods.php', false);
}

// Display form
include_once('layouts/header.php');
echo display_msg($msg);
?>

<div class="row">
    <div class="col-md-12">
        <h2>Add Incoming Goods</h2>
        <form id="goods-form" method="post">
            <div id="input-container">
                <div class="input-row">
                    <div class="form-group">
                        <label for="product">Product:</label>
                        <input type="text" class="form-control product-search" name="data[0][productName]"
                            placeholder="Search for a product">
                        <div class="suggestions"></div>
                    </div>
                    <div class="form-group">
                        <label for="quantity">Quantity:</label>
                        <input class="quantity form-control" type="number" step="any" name="data[0][quantity]"
                            placeholder="Quantity">
                    </div>
                    <div class="form-group">
                        <label for="remark">Remark:</label>
                        <input type="text" class="form-control" name="data[0][remark]" placeholder="Enter remark">
                    </div>
                    <div class="form-group">
                        <label for="loc">Location:</label>
                        <input type="text" class="form-control" name="data[0][loc]" placeholder="Enter location">
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label for="transaction-date">Transaction Date:</label>
                <input type="date" id="transaction-date" name="transactionDate">
            </div>
            <button type="button" class="btn btn-success" id="add-input">Add Input</button>
            <button type="submit" class="btn btn-primary">Add Incoming Goods</button>
            <div class="form-group">
                <label for="csv-file">Import CSV:</label>
                <input type="file" class="form-control-file" id="csv-file" accept=".csv">
            </div>
        </form>
    </div>
</div>

<style>
    .input-row {
        display: flex;
        flex-wrap: wrap;
        gap: 1rem;
        margin-bottom: 1rem;
    }

    .input-row .form-group {
        flex: 1;
        min-width: 200px;
    }

    .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 inputContainer = document.getElementById('input-container');
        const addButton = document.getElementById('add-input');
        const transactionDateInput = document.getElementById('transaction-date');

        let inputCount = 1;

        addButton.addEventListener('click', function() {
            const inputRow = document.createElement('div');
            inputRow.classList.add('input-row');

            const formGroups = ['productName', 'quantity', 'remark', 'loc'].map(fieldName => {
                const formGroup = document.createElement('div');
                formGroup.classList.add('form-group');

                const label = document.createElement('label');
                label.setAttribute('for', fieldName);
                label.textContent = fieldName.charAt(0).toUpperCase() + fieldName.slice(1);

                const input = document.createElement('input');
                input.classList.add('form-control');
                input.setAttribute('type', fieldName === 'quantity' ? 'number' :
                    'text');
                input.setAttribute('name', `data[${inputCount}][${fieldName}]`);
                input.setAttribute('placeholder', `Enter ${fieldName}`);
                input.setAttribute('step', 'any'); // Tambahkan ini untuk menerima nilai desimal

                formGroup.appendChild(label);
                formGroup.appendChild(input);

                return formGroup;
            });

            inputRow.append(...formGroups);

            inputContainer.appendChild(inputRow);
            inputCount++;
        });

        const productSearchInputs = document.querySelectorAll('.product-search');
        productSearchInputs.forEach(input => {
            const suggestionsContainer = input.nextElementSibling;

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

                if (query.length >= 2) {
                    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() {
                                        input.value = product.part_number;
                                        suggestionsContainer.innerHTML = '';
                                    });
                                    suggestionsContainer.appendChild(suggestionItem);
                                });
                            } else {
                                suggestionsContainer.innerHTML = '<div class="suggestion">No suggestions</div>';
                            }
                        })
                        .catch(error => console.error(error));
                } else {
                    suggestionsContainer.innerHTML = '';
                }
            });
        });

        // CSV import functionality
        const csvFileInput = document.getElementById('csv-file');

        csvFileInput.addEventListener('change', function(event) {
            const file = event.target.files[0];
            if (!file) return;

            const reader = new FileReader();

            reader.onload = function(e) {
                const contents = e.target.result;
                processData(contents);
            };

            reader.readAsText(file);
        });

        function processData(csvData) {
            const rows = csvData.split('\n');
            const data = [];

            rows.forEach(row => {
                const columns = row.split(';');
                const [partNumber, quantity, remark, loc] = columns.map(column => column.trim());
                if (partNumber && quantity && remark && loc) {
                    data.push({
                        productName: partNumber,
                        quantity,
                        remark,
                        loc
                    });
                }
            });

            if (data.length > 0) {
                data.forEach((item, index) => {
                    const inputRow = document.createElement('div');
                    inputRow.classList.add('input-row');

                    const formGroups = ['productName', 'quantity', 'remark', 'loc'].map(fieldName => {
                        const formGroup = document.createElement('div');
                        formGroup.classList.add('form-group');

                        const label = document.createElement('label');
                        label.setAttribute('for', fieldName);
                        label.textContent = fieldName.charAt(0).toUpperCase() + fieldName.slice(1);

                        const input = document.createElement('input');
                        input.classList.add('form-control');
                        input.setAttribute('type', fieldName === 'quantity' ? 'number' : 'text');
                        input.setAttribute('name', `data[${index}][${fieldName}]`);
                        input.value = item[fieldName];
                        input.setAttribute('step', 'any');

                        formGroup.appendChild(label);
                        formGroup.appendChild(input);

                        return formGroup;
                    });

                    inputRow.append(...formGroups);
                    inputContainer.appendChild(inputRow);
                });
            }
        }
    });
</script>

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