/* 
 * Author: NeeB Plugins
 * Author URI: https://neebplugins.com 
 * Description: This stylesheet contains scripts for the admin. 
 */

jQuery(document).ready(function ($) {
    $('.wc-enhanced-select').selectWoo();

    $('#aofwc-export-linemanager').on('click', function () {

        $.ajax({
            type: "POST",
            url: aofwc_admin_rest.restApiBase + 'export/manager-meta',
            xhrFields: { responseType: 'blob' },
            data: {
                format: 'csv',
            },
            beforeSend: function (xhr) {
                xhr.setRequestHeader('X-WP-Nonce', aofwc_admin_rest.nonce);
                $('#aofwc-export-loader').removeClass('d-none');
                $('#aofwc-export-linemanager').attr('disabled', true);
            },
            success: function (data, status, xhr) {
                let contentType = xhr.getResponseHeader('Content-Type');

                if (contentType && contentType.indexOf('application/json') !== -1) {
                    // Handle JSON response (no users)
                    let reader = new FileReader();
                    reader.onload = function () {
                        let json = JSON.parse(reader.result);
                        toastr.error(json.message || "No records found.", 'Error!');
                    };
                    reader.readAsText(data);
                } else {
                    // Handle CSV download
                    let disposition = xhr.getResponseHeader('Content-Disposition');
                    let filename = "users-export.csv";
                    if (disposition && disposition.indexOf('filename=') !== -1) {
                        filename = disposition.split('filename=')[1].replace(/"/g, '');
                    }

                    let blob = new Blob([data], { type: 'text/csv' });
                    let url = window.URL.createObjectURL(blob);
                    let a = document.createElement('a');
                    a.href = url;
                    a.download = filename;
                    document.body.appendChild(a);
                    a.click();
                    a.remove();
                    window.URL.revokeObjectURL(url);
                }

                $('#aofwc-export-loader').addClass('d-none');
                $('#aofwc-export-linemanager').attr('disabled', false);
            },
            error: function (xhr, status, error) {
                toastr.error('Some error occurred, please try again in some time!', 'Error!');
            }
        });

    })
});