<?php
$page_title = 'Transfer Product Location';
require_once('includes/load.php');
page_require_level(3); // Memerlukan level akses 3 untuk mengakses halaman ini

$msg = '';

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

    // Mulai transaksi
    $db->begin_transaction();

    // Loop through each transfer data
    foreach ($_POST['data'] as $data) {
        // Escape and extract data
        $productName = $db->escape($data['productName']);
        $quantity = (int) $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 transfer record into transfer_prod_loc table
            $partNumber = $product['part_number'];
            $sql_transfer = "INSERT INTO transfer_prod_loc (product_id, part_number, quantity, transfer_date, categorie_id, remark, loc) 
                             VALUES ('{$product['product_id']}', '{$partNumber}', '{$quantity}', '{$transactionDate}', '{$product['categorie_id']}', '{$remark}', '{$loc}')";

            if ($db->query($sql_transfer)) {
                // Update product quantity in prod_loc table (subtract)
                $new_quantity = $product['quantity'] - $quantity;
                $sql_update_product = "UPDATE prod_loc SET quantity = '{$new_quantity}' WHERE part_number = '{$partNumber}'";
                if ($db->query($sql_update_product)) {
                    $session->msg('s', 'Product location transferred successfully!');
                } else {
                    $db->rollback(); // Rollback transaction if update fails
                    $session->msg('d', 'Failed to update product quantity in prod_loc table.');
                    break; // Exit loop
                }
            } else {
                $db->rollback(); // Rollback transaction if insert fails
                $session->msg('d', 'Failed to transfer product location to transfer_prod_loc.');
                break; // Exit loop
            }
        } else {
            $session->msg('d', 'Product not found.');
            $db->rollback(); // Rollback transaction if product not found
            break; // Exit loop
        }
    }

    if ($db->commit()) {
        $session->msg('s', 'Transaction completed successfully!');
    } else {
        $db->rollback();
        $session->msg('d', 'Transaction failed.');
    }

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

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

<div class="row">
    <div class="col-md-12">
        <h2>Transfer Product Location</h2>
        <form id="transfer-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" 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">Transfer Product Location</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}`);

                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) {
                appendDataToForm(data);
            } else {
                alert('No valid data found in the CSV file.');
            }
        }

        function appendDataToForm(data) {
            const inputContainer = document.getElementById('input-container');
            inputContainer.innerHTML = ''; // Clear existing inputs

            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.setAttribute('value', item[fieldName]);

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

                    return formGroup;
                });

                inputRow.append(...formGroups);
                inputContainer.appendChild(inputRow);
            });

            inputCount = data.length; // Update inputCount to match the number of rows added
        }
    });
</script>

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

