<?php
$page_title = 'Request Material';
require_once('includes/sql.php');
page_require_level(3);

// Function to get the next request number
function get_next_request_number() {
    global $db;
    $sql = "SELECT MAX(SUBSTRING(request_number, 10)) AS max_number FROM request_material";
    $result = $db->query($sql);
    $row = $db->fetch_assoc($result);

    if ($row['max_number'] === null) {
        return 1;
    } else {
        return intval($row['max_number']) + 1;
    }
}

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

    // Loop through each requested material data
    foreach ($_POST['data'] as $data) {
        // Escape and extract data
        $productName = $db->escape($data['productName']);
        $requestedQuantity = (int) $data['requestedQuantity'];
        $remark = $db->escape($data['remark']);

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

        if ($product) {
            // Insert request material record
            $sql = "INSERT INTO request_material (request_number, product_id, requested_quantity, request_date, status, remark) 
                    VALUES ('PPIC/REQ/{$nextRequestNumber}', '{$product['id']}', '{$requestedQuantity}', '{$requestDate}', 'pending', '{$remark}')";

            if ($db->query($sql)) {
                $session->msg('s', 'Material request added successfully!');
            } else {
                $session->msg('d', 'Failed to add material request.');
            }
        } else {
            $session->msg('d', 'Product not found.');
        }
    }

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

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

// Get the next request number
$nextRequestNumber = get_next_request_number();
?>

<div class="row">
    <div class="col-md-12">
        <h2>Request Material</h2>
        <h4>Request Number: PPIC/REQ/<?php echo $nextRequestNumber; ?></h4>
        <form id="material-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="requestedQuantity">Requested Quantity:</label>
                        <input class="quantity form-control" type="number" name="data[0][requestedQuantity]" placeholder="Requested 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>
            </div>
            <div class="form-group">
                <label for="request-date">Request Date:</label>
                <input type="date" id="request-date" name="requestDate" required>
            </div>
            <button type="button" class="btn btn-success" id="add-input">Add Input</button>
            <button type="submit" class="btn btn-primary">Request Material</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 requestDateInput = document.getElementById('request-date');

        let inputCount = 1;

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

            const formGroups = ['productName', 'requestedQuantity', 'remark'].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 === 'requestedQuantity' ? '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, requestedQuantity, remark] = columns.map(column => column.trim());
                if (partNumber && requestedQuantity && remark) {
                    data.push({ productName: partNumber, requestedQuantity, remark });
                }
            });

            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', 'requestedQuantity', 'remark'].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 === 'requestedQuantity' ? 'number' : 'text');
                    input.setAttribute('name', `data[${index}][${fieldName}]`);
                    input.setAttribute('placeholder', `Enter ${fieldName}`);
                    input.value = item[fieldName];

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

                    return formGroup;
                });

                inputRow.append(...formGroups);

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

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