$(document).ready(function () {
    $('#mapButton').click(function () {
        handleMapping();
    });

    function handleMapping() {
        var fileInput = document.getElementById('file');

        if (fileInput.files.length > 0) {
            var file = fileInput.files[0];
            var reader = new FileReader();
  
            reader.onload = function (e) {
                var data = new Uint8Array(e.target.result);
                var workbook = XLSX.read(data, { type: 'array' });
                var sheet = workbook.Sheets[workbook.SheetNames[0]];
                var headers = [];

                for (var key in sheet) {
                    if (sheet.hasOwnProperty(key) && parseInt(key.substring(1)) === 1) {
                        headers.push(sheet[key].v);
                    }
                }

                displayHeadersInTable(headers);
            };

            reader.readAsArrayBuffer(file);
        } else {
            alert('Please select a file.');
        }
    }

    function displayHeadersInTable(headers) {
        var table = $('#headersTable');

        table.html('');

        headers.forEach(function (header) {
            var row = $('<tr>');
            var headerCell = $('<th>').text(header);
            row.append(headerCell);
            createDropdownForHeader(header, row);
            table.append(row);
        });
    }

    function createDropdownForHeader(header, row) {
        $.ajax({
            url: 'getDropdownData.php',
            method: 'POST',
            data: { tableName: 'test_table', columnName: header },
            success: function (data) {
                var options = JSON.parse(data);
                var select = $('<select>').attr('name', 'mapping[' + header + ']');

                options.forEach(function (option) {
                    var optionElement = $('<option>').val(option).text(option);
                    select.append(optionElement);
                });

                var dropdownCell = $('<td>').append(select);
                row.append(dropdownCell);
            },
            error: function (xhr, status, error) {
                console.error('AJAX Error:', error);
            }
        });
    }
});
