"use strict";
$(document).ready(function () {
    $("#UploadFile").on("click", function () {
        let btn = document.querySelector('#UploadFile').textContent;
        var formData = new FormData(document.forms.namedItem("FromID"));
        var urlInsert = $('#FromID').data('urlinsert');
        var fileInput = document.getElementById('file');
        var filePath = fileInput.value;
        var allowedExtensions = /(\.csv|\.xlsx|\.txt)$/i;

        if (!allowedExtensions.exec(filePath)) {
            sAlert('info', 'Invalid file type. Please upload .txt, .csv or .xlsx file only.');
            fileInput.value = '';
            return false;
        }

        $.ajax({
            url: urlInsert,
            type: "POST",
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            beforeSend: function () {
                $("#UploadFile").html('Please Wait...');
            },
            success: function (response) {
                if (response.status == 200) {
                    // Show column mapping interface
                    showColumnMappingModal(response.columns, response.suggested_email, response.suggested_name, response.mapping_url);
                } else {
                    sAlert('error', response.msg);
                    document.getElementById("FromID").reset();
                }
            },
            complete: function () {
                document.querySelector('#UploadFile').textContent = btn;
            },
        });
    });

    // Function to display column mapping modal
    function showColumnMappingModal(columns, suggestedEmail, suggestedName, mappingUrl) {
        // Create the modal HTML
        var modalHtml = `
        <div class="modal fade" id="columnMappingModal" tabindex="-1" role="dialog" aria-labelledby="columnMappingModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="columnMappingModalLabel">Map Your File Columns</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <p>Please select which column contains email addresses:</p>
                        <form id="columnMappingForm">
                        <input type="hidden" name="_token" value="${$('meta[name="csrf-token"]').attr('content')}">
                            <div class="form-group row">
                                <label for="emailColumn" class="col-sm-3 col-form-label">Email Column:</label>
                                <div class="col-sm-9">
                                    <select class="form-control" id="emailColumn" name="email_column">
                                        <option value="">-- Select Email Column --</option>
                                        ${generateColumnOptions(columns, suggestedEmail)}
                                    </select>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-primary" id="saveColumnMapping">Process Data</button>
                    </div>
                </div>
            </div>
        </div>
        `;

        // Add modal to page
        $('body').append(modalHtml);

        // Show the modal
        $('#columnMappingModal').modal('show');

        // Handle save button click
        $('#saveColumnMapping').on('click', function() {
            var formData = new FormData(document.getElementById('columnMappingForm'));

            $.ajax({
                url: mappingUrl,
                type: "POST",
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                beforeSend: function () {
                    $("#saveColumnMapping").html('Processing...');
                    $("#saveColumnMapping").attr("disabled", "disabled");
                },
                success: function (response) {
                    $('#columnMappingModal').modal('hide');

                    if (response.status == 200) {
                        sAlert('success', response.msg, response.url);
                        document.getElementById("FromID").reset();
                    } else {
                        sAlert('error', response.msg);
                    }
                },
                complete: function () {
                    $("#saveColumnMapping").html('Process Data');
                    $("#saveColumnMapping").removeAttr("disabled");
                    $('#columnMappingModal').remove();
                },
            });
        });
    }

    // Helper function to generate column options
    function generateColumnOptions(columns, selectedIndex) {
        let options = '';
        columns.forEach((column, index) => {
            const selected = index === selectedIndex ? 'selected' : '';
            options += `<option value="${index}" ${selected}>${column}</option>`;
        });
        return options;
    }



    $("#SubmitEmailcleaner").on("click", function () {
        let btn = document.querySelector('#SubmitEmailcleaner').textContent;
        var formData = new FormData(document.forms.namedItem("FromID2"));
        var urlInsert = $('#FromID2').data('urlinsert');
        $("#SubmitEmailcleaner").attr("disabled", "disabled");

        $.ajax({
            url: urlInsert,
            type: "POST",
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            beforeSend: function () {
                $("#SubmitEmailcleaner").html('Please Wait...');
            },
            success: function (response) {
                $("#SubmitEmailcleaner").removeAttr("disabled");
                if (response.status == 200) {
                    $('.ValidEmailsRow').removeClass('d-none');
                    $('#Valid').val(response.data);
                    $('#invalid').val(response.InvalidEmail);
                }
            },
            complete: function () {
                document.querySelector('#SubmitEmailcleaner').textContent = btn;
            },
        });
    });


    $(".copy-mail").on('click', function () {
        // Get the text content from the textarea
        var textToCopy = $("#Valid").val();
        // Create a temporary input element to hold the text and copy it to the clipboard
        var tempInput = $("<input>");
        $("body").append(tempInput);
        tempInput.val(textToCopy).select();
        document.execCommand("copy");
        tempInput.remove();

        sAlert('success', 'Valid emails copied to clipboard!');
    });

    $(".copy-mail-Invalid").on('click', function () {
        // Get the text content from the textarea
        var textToCopy = $("#invalid").val();
        // Create a temporary input element to hold the text and copy it to the clipboard
        var tempInput = $("<input>");
        $("body").append(tempInput);
        tempInput.val(textToCopy).select();
        document.execCommand("copy");
        tempInput.remove();

        sAlert('success', 'invalid emails copied to clipboard!');
    });

    // file
    $('body').on('change', '#file', function () {
        var formData = new FormData(document.forms.namedItem("FromID"));
        var urlInsert = $('#FromID').attr('data-urlMapping');
        var fileInput = document.getElementById('file');
        var filePath = fileInput.value;
        var allowedExtensions = /(\.csv|\.xlsx|\.txt)$/i;

        if (!allowedExtensions.exec(filePath)) {
            sAlert('info', 'Invalid file type. Please upload .txt, .csv or .xlsx file only.');
            fileInput.value = '';
            return false;
        }
    });

});
