const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const page = urlParams.get('page')
const tab = urlParams.get('tab')
const section = urlParams.get('section')

if (page != null && page.match('cardealerpress_admin')) {
    // Hide Save button on Help and Log page.
    let help_or_log_page = window.location.search.match(/help|log/)
    if ( help_or_log_page ){
        jQuery('#submit').hide();
    }
}
const modified_inputs = new Set;
let allow_reload_submit = false;

if (page != null && page.match('cardealerpress_theme|cardealerpress_shortcode')) { //prevents js from running on all wp-admin pages, issue with the cdp admin page and the manual refresh buttons, because of no changes.
    "use strict";
    (() => {
        const defaultValue = "defaultValue";
// store default values
        addEventListener("beforeinput", (evt) => {
            const target = evt.target;
            if (!(defaultValue in target || defaultValue in target.dataset)) {
                target.dataset[defaultValue] = ("" + (target.value || target.textContent)).trim();
            }
        });
// detect input modifications
        addEventListener("input", (evt) => {
            const target = evt.target;
            let original;
            if (defaultValue in target) {
                original = target[defaultValue];
            } else {
                original = target.dataset[defaultValue];
            }
            if (target.type.match(/checkbox|textarea|radio/i)) {
                if (original === '') {
                    original = 'on';
                } else {
                    original = '';
                }
            }
            if (original !== ("" + (target.value || target.textContent)).trim()) {
                if (!modified_inputs.has(target)) {
                    modified_inputs.add(target);
                }
            } else if (modified_inputs.has(target)) {
                modified_inputs.delete(target);
            }
        });
        jQuery(".drag-table").on("sortstart", function (event, ui) {
            modified_inputs.add(ui.item);
        });
        jQuery("#excludeTagsSelect2").on('change.select2', function(event){
            modified_inputs.add(event);
        });
// clear modified inputs upon form submission
        addEventListener("submit", (evt) => {
            // If no inputs were modified, block submit + alert user
            if ( modified_inputs.size === 0) {
                evt.preventDefault();
                alert("No changes made.");
            } else {
                // Allow form submit, then clear the set
                modified_inputs.clear();
                // optional: evt.target.reset();  // resets form after submit
            }
        });
// warn before closing if any inputs are modified
        addEventListener("beforeunload", (evt) => {
            if (!allow_reload_submit && modified_inputs.size ) {
                const unsaved_changes_warning = "Changes you made will not be saved.";
                evt.preventDefault();
                window.alert(unsaved_changes_warning);
            }
        });
    })();
}

if (jQuery('#maps-key-status').length) {
    let map_key_status = jQuery('#maps-key-status').text();
    if (map_key_status.toLowerCase() != 'ok') {
        jQuery('#submit').attr('disabled', true);
        jQuery('#map-key').css("background-color", "#FFFFCC");
    } else {
        jQuery('#submit').attr('disabled', false);
        jQuery('#map-key').css("background-color", "#FFFFFF");
    }
}


jQuery('#add-map-key-button').on('click', (function (e) {
    let key = jQuery('#map-key').val();
    let dealer_id = jQuery('#cdp-previous-id').val();
    let searchParams = location.search
        .slice(1)
        .split('&')
        .map(p => p.split('='))
        .reduce((obj, [key, value]) => ({...obj, [key]: value}), {});
    if (key) {
        allow_reload_submit = true;
        let data = {'key': key, 'dealer_id': dealer_id};
        let obj = jQuery().extend(data, searchParams);
        //jQuery('#dealer-ajax-message-advanced').removeClass('error').text('');
        cdp_ajax_call('map_population', obj, '#cdp-content-wrapper').done(function (result) {
            if (result['error']) {
                jQuery('#maps-key-status').addClass('cdp-map-status').text(result['status']);
                jQuery('#maps-key-error-message').addClass('.cdp-settings-error-message').text(result['error_message']);
            }
        }).complete(function () {
            location.reload();
        }).fail(function () {
            jQuery('#maps-key-error-message').addClass('.cdp-settings-error-message').text('Ajax Failed. Try again.');
        });
    } else {
        jQuery('#maps-key-error-message').addClass('.cdp-settings-error-message').text('Please enter a key.');
    }
}));

jQuery('#cdp-content-wrapper-default').on('change', '.cdp-input', function (e) {
    if (jQuery(e.target).attr('type') == 'checkbox' && !jQuery(e.target).is(':checked')) {
        jQuery(e.target).val('').focus();
        jQuery(e.target).next().val('').focus();
    } else if (jQuery(e.target).attr('type') == 'checkbox' && jQuery(e.target).is(':checked')) {
        jQuery(e.target).val('on').focus();
        jQuery(e.target).next().val('on').focus();
    }
});

jQuery('.toggle-row').click(function (e) {
    e.preventDefault();
    jQuery(this).next("div").slideToggle('slow');
    let setting = jQuery('.toggle-row').parent('section').attr('id');
    if (setting == 'new-tag' || setting == 'default-image') {
        custom_media_upload(setting);
    }
});

// rows
jQuery('.edit-row').click(function (e) { // TODO possible rework
    e.preventDefault();
    let editing_row = jQuery(this).parents('tr');
    let inner_row = jQuery(this).closest('tr').next('.detail');
    editing_row.addClass('active');
    inner_row.addClass('active');
    //inner_row.find('.cdp-row input').prop('required',true);
    inner_row.show().find('div').slideToggle('slow', function () {
        if (!jQuery(this).is(':visible')) {
            editing_row.removeClass('active');
            inner_row.removeClass('active');
            inner_row.hide();
            //inner_row.find('.cdp-row input').removeAttr('required');
        }
    });
});

jQuery('.close-row').click(function (e) {
    e.preventDefault();
    let id = jQuery(this).attr('name');
    close_row(id)
});

function close_row(id) {
    let editing_row = jQuery('#outer-' + id + '');
    let inner_row = jQuery('#inner-' + id + '');
    inner_row.show().find('div').slideToggle('slow', function () {
        if (!jQuery(this).is(':visible')) {
            editing_row.removeClass('active');
            inner_row.removeClass('active');
            inner_row.hide();
            //inner_row.find('.cdp-row input').removeAttr('required');
        }
    });
}

jQuery('.delete-row').click(function (e) {
    e.preventDefault();
    let searchParams = new URLSearchParams(window.location.search)
    let page = {'page': '' + searchParams.get('page') + ''};
    let button_data = jQuery(e.target).data();
    let row_id = button_data['rowId'];
    let row_data = jQuery('#outer-' + row_id + '').data();
    let obj = jQuery().extend(row_data, button_data);
    obj = jQuery().extend(obj, page);
    let result = window.confirm("Are you sure, you want to delete " + obj['labelName'] + "?");
    let fn = jQuery(this).attr('id');
    if (result === true) {
        cdp_ajax_call(fn, obj, '').done(function (result) { // removes from cdp_*_options in wp_options table
            jQuery(e.target).parents('tr').next('tr').remove();
            jQuery(e.target).parents('tr').remove();
            location.reload();
        }).fail(function () {
            alert(name + " not removed");
        });
    }
});

jQuery('.update-row').click(function (e) {
    e.preventDefault();
    let row_id = jQuery(this).attr('name');
    let label_name = jQuery('#outer-' + row_id + '').attr('data-label-name');
    let any_errors = [];
    let maps = window.location.search.includes('maps');
    jQuery('#inner-' + row_id + ' input').each(function () {
        if (jQuery(this).attr('required')) {
            if (jQuery(this).val() == '') {
                let field = jQuery(this).closest('tr').find('th label').text()
                any_errors.push(window.confirm("Field " + field + " Required"));
            }
        }
    });
    if (jQuery.isEmptyObject(any_errors)) {
        let result = window.confirm("Are you sure, you want to update: " + label_name + "?");
        if (result === true) {
            if (maps) {
                allow_reload_submit = true;
                jQuery('#submit').attr('disabled', true);
                //recheck maps
                let dealer_id = jQuery('#' + row_id + '-dealer-id').val();
                let street = jQuery('#' + row_id + '-street').val();
                let city = jQuery('#' + row_id + '-city').val();
                let state = jQuery('#' + row_id + '-state').val();
                let zip = jQuery('#' + row_id + '-zip').val();
                let zoom = jQuery('#' + row_id + '-zoom').val();
                let name = jQuery('#' + row_id + '-name').val();
                let address = street + ' ' + city + ' ' + state + ' ' + zip;
                let searchParams = location.search
                    .slice(1)
                    .split('&')
                    .map(p => p.split('='))
                    .reduce((obj, [key, value]) => ({...obj, [key]: value}), {});
                let data = {
                    'dealer_id': dealer_id, 'name': name, 'address': address, 'street': street, 'city': city,
                    'state': state, 'zip': zip, 'zoom': zoom, 'row_id': row_id
                };
                let obj = jQuery().extend(data, searchParams);
                cdp_ajax_call('update_map_address', obj, '#cdp-content-wrapper').done(function (result) {
                    if (result['error']) {
                        jQuery('#maps-key-status').addClass('cdp-map-status').text(result['status']);
                        jQuery('#maps-key-error-message').addClass('.cdp-settings-error-message').text(result['error_message']);
                    }
                }).complete(function () {
                    location.reload();
                }).fail(function () {
                    jQuery('#maps-key-error-message').addClass('.cdp-settings-error-message').text('Ajax Failed. Try again.');
                });
            } else {
                jQuery('#submit').click();
            }
        }
    }
});

/**
 Admin manual inventory update
 **/
function change_company_id() {
    jQuery('#company_id').change(function (e) {
        let previous_id = jQuery('#cdp-previous-id').val();
        let new_id = jQuery('input#company_id').val();
        if (new_id != 0 && previous_id != new_id) {
            jQuery('#cdp-form-post-action').val('dealerChange');
            jQuery('#cdp-new-value').val(new_id);
            jQuery('#cdp-path-value').val(jQuery('input#company_id').attr('name'));
            jQuery('#cdp-key-value').val('dealer');
            let data = {'company_id': new_id};
            cdp_ajax_call('dealerChange', data, '#cdp-content-wrapper').done(function (result) {
                if (result['key'] === 'error') {
                    let message = result["content"];
                    let content = '<span class="error" style="color: red;font-weight: bold;">' + message + '</span>';
                    jQuery('#company_id').parents('tr').append(content);
                    jQuery('#submit').addClass('disabled');
                } else {
                    jQuery('#submit').removeClass('disabled');
                    //jQuery('#submit').click();
                }
            }).fail(function () {
            });
        }
    });
}

function manual_inventory_updates() {
    jQuery('.cdp-run-input').click(function (e) {
        jQuery('#cdp-content-wrapper').addClass('running');
        let id = jQuery(e.target).attr('id');
        switch (id) {
            case 'manually-run-import-job-all':
                jQuery('#manually-run-import-job-confirm').slideDown();
                break;
            case 'manually-run-company-job':
                jQuery('#cdp-form-post-action').val('companyRefresh');
                jQuery('#cdp-admin-form-post').submit();
                jQuery('#submit').click();
                break;
            case 'manually-run-dealer-inventory-purge':
                jQuery('#cdp-form-post-action').val('dealerImportPurge');
                jQuery('#cdp-form-post-data').val(jQuery(this).attr('data-dealer'));
                jQuery('#cdp-admin-form-post').submit();
                jQuery('#submit').click();
                break;
            case 'manually-run-dealer-inventory':
                jQuery('#cdp-form-post-action').val('dealerImport');
                jQuery('#cdp-form-post-data').val(jQuery(this).attr('data-dealer'));
                jQuery('#cdp-admin-form-post').submit();
                jQuery('#submit').click();
                break;
        }
    });
    jQuery('#confirm-full-manual-run').click(function (e) {
        jQuery('#cdp-content-wrapper').addClass('running');
        jQuery('#cdp-form-post-action').val('fullImport');
        jQuery('#cdp-form-post-data').val('00');
        jQuery('#cdp-admin-form-post').submit();
        jQuery('#submit').click();
    });
    jQuery('#decline-full-manual-run').click(function (e) {
        jQuery('#manually-run-import-job-confirm').slideUp();
    });
}

/**
 Admin manual inventory END
 **/

jQuery(document).ready(function () {
    start_select2(); //pages: keywords, tags
    get_sort_count(); //pages: sort
    change_company_id(); // pages: admin
    manual_inventory_updates(); // pages: admin
});

// actions within the row add button
jQuery('#addNewTableButton').on('click', function (e) {
    let maps = jQuery(this).hasClass('maps');
    if (maps) {
        jQuery('#submit').attr('disabled', true);
    }
    jQuery(document).ready(function () {
    start_select2(); //pages: Theme Settings:keywords, tags;
    get_sort_count(); //pages: sort
    add_additional_map();
    jQuery("#addNewTable .add-dealer").focusin(function () {
        jQuery('#submit').attr('disabled', true);
        jQuery(this).css("background-color", "#FFFFCC");
    });

    /*jQuery("#addNewTable input").focusout(function(){
        jQuery(this).css("background-color", "#FFFFFF");
        jQuery('#submit').attr('onclick','return true');
    });*/

    // Admin Advanced page adding of a dealer.
    jQuery('#add-dealer-button').click(function (e) {
        let row_id = jQuery(e.target).attr('data-row-id');
        let dealer = jQuery('#advanced-dealer-' + row_id + '').val();
        if (jQuery.isNumeric(dealer)) {
            let data = {'key': 'dealer_check', 'value': dealer};
            jQuery('#dealer-ajax-message-advanced').removeClass('error').text('');
            cdp_ajax_call('manual_dealer_check', data, '#cdp-content-wrapper').done(function (result) {
                if (data['key'] == 'dealer_check' && result['key'] != 'error') {
                    jQuery('#cdp-add-new-dealer-value').val(dealer);
                    jQuery('#cdp-form-post-action').val('dealerAdd');
                    jQuery('#submit').attr('disabled', false);
                    jQuery('#submit').click();
                }
                jQuery('#dealer-ajax-message-advanced').addClass(result['key']).text(result['content']);

            }).fail(function () {
                jQuery('#dealer-ajax-message-advanced').addClass('error').text('Ajax Failed. Try again.');
            });
        } else {
            jQuery('#dealer-ajax-message-advanced').addClass('error').text('Not a valid Dealer Value');
        }
    });
    });
})

function add_additional_map(){

    jQuery('#add-additional-dealer-map-button').on('click', (function () {
        jQuery('#submit').attr('disabled', true);
            let row_id = jQuery(this).attr('data-row-id');
                let key = jQuery('#map-key').val();
                let dealer_id = jQuery('#' + row_id + '-dealer-id').val();
                let searchParams = location.search
                    .slice(1)
                    .split('&')
                    .map(p => p.split('='))
                    .reduce((obj, [key, value]) => ({...obj, [key]: value}), {});
                if (key) {
                    let data = {'key': key, 'dealer_id': dealer_id, 'rowId': row_id};
                    let obj = jQuery().extend(data, searchParams);
                    cdp_ajax_call('check_for_dealer', obj, '#cdp-content-wrapper').done(function (result) {
                        if (result['error']) {
                            window.confirm("Failed: " + result['error_message']);
                        } else {
                            cdp_ajax_call('map_population', obj, '#cdp-content-wrapper').done(function (result) {
                                allow_reload_submit = true;
                                location.reload();
                            });
                        }
                    })
                } else {
                    jQuery('#maps-key-error-message').addClass('.cdp-settings-error-message').text('Please enter a key.');
                }
            })
        );
}



function get_sort_count() {
    jQuery('.sort-tag').change(function (e) {
        let id = jQuery(this).attr('id');
        let row = jQuery(this).attr('data-row');
        let filters = {};
        jQuery('.table-' + row + ' .sort-filter').each(function () {
            if (jQuery(this).val() != '') {
                filters[jQuery(this).attr('data-name')] = jQuery(this).val();
            }
        })
        let data = {'filters': filters}
        cdp_ajax_call('dbGetCount', data, '').done(function (result) {
            jQuery('#found-' + row + ' .current-sort-count-value').text(result['content']);
        }).fail(function () {
            //alert('Data Note Saved...');
        });
    });
}


// AJAX Call
function cdp_ajax_call(fn, params, wrapper) {
    return jQuery.ajax({
        url: ajax_object.ajax_url,
        type: 'GET',
        headers: {Accept: 'application/json'},
        contentType: 'application/json',
        data: {
            'action': 'admin_handle_request',
            'nonce': ajax_object.nonce,
            'fn': fn,
            'params': params
        },
        dataType: 'json',
        beforeSend: function () {
            if (wrapper != 'skip') {
                jQuery(wrapper).addClass('saving');
                jQuery(wrapper).removeClass('not-saved');
            }
        },
        success: function (data) {
            let sucless = true;
            if (!jQuery.isEmptyObject(data['id'])) {
                jQuery('#' + data['id']).append(data['content']);

            }
        },
        complete: function () {
            if (fn == 'updateTableRow') {
                close_row(params['id']);
                //location.reload();
            }
            if (wrapper != 'skip') {
                jQuery(wrapper).addClass('saved');
                jQuery(wrapper).removeClass('saving');
                setTimeout('cdp_aftersave("' + wrapper + '")', 500);
            }

        },
        error: function (xhr, status, error) {
            alert('Ajax call failed, error: ' + error);
        }
    });
}

function cdp_aftersave(wrapper) {
    if (jQuery(wrapper).hasClass('saved')) {
        jQuery(wrapper).removeClass('saved');
    }
}

// Controls inner tabs
jQuery('.inner-tab-button').click(function () {
    let button_id = jQuery(this).attr('id');
    jQuery(this).siblings('.active').removeClass('active');
    jQuery(this).addClass('active');
    jQuery(this).parents('#content-loan').find('.tab-inner-content.active').removeClass('active');
    jQuery('.' + button_id).addClass('active');
});


// move keywords between pot and exclude
jQuery('.keywords').on('select2:unselect', function (e) {
    let keyword_type = jQuery(this).attr('data-keyword');
    let keyword = e.params.data;
    let data = {
        id: keyword.id,
        text: keyword.text
    };
    let newOption = new Option(data.text, data.id, false, true);
    if (keyword_type == 'pot') {
        jQuery('.exclude').append(newOption).trigger('change');
    } else {
        jQuery('.pot').append(newOption).trigger('change');
    }
})


// Select2
function start_select2() {
    jQuery('.basic-multiple').select2({
            placeholder: "Select"
        }
    );
}


// Call Media Upload | tags
function custom_media_upload(setting) {
    jQuery('.table-wrap').on('click', '.custom_media_upload', function (e) {
        if (setting.match('new-tag')) {
            var title = 'Upload Icon';
            var text = 'Apply Icon';
        } else {
            var title = 'Upload Default No Image';
            var text = 'Default No Image';
        }
        e.preventDefault();
        var media_id = e.target.id;

        var custom_uploader = wp.media({
            title: title,
            width: 200,
            height: 200,
            button: {
                text: text
            },
            multiple: false  // Set this to true to allow multiple files to be selected
        })
            .on('select', function () {
                let attachment = custom_uploader.state().get('selection').first().toJSON();
                if (setting == 'new-tag') {
                    jQuery('.custom_media_image.' + media_id).attr('src', attachment.url);
                    jQuery('.custom_media_url.' + media_id).val(attachment.url).change().select();
                } else {
                    jQuery('.custom_media_url.' + media_id).val(attachment.url).change().select();
                }

            })
            .open();
    });
}

// Call Media Upload | Default No Image
jQuery('.custom-media-upload-default-image').click(function (e) {
    e.preventDefault();
    //media_id = jQuery(this).attr('id');

    var custom_uploader = wp.media({
        title: 'Upload Default No Image',
        width: 200,
        height: 200,
        button: {
            text: 'Default No Image'
        },
        multiple: false  // Set this to true to allow multiple files to be selected
    })
        .on('select', function () {
            var attachment = custom_uploader.state().get('selection').first().toJSON();
            jQuery('#overrides-default-no-image').val(attachment.url).change().select();
        })
        .open();
});

// Admin Help page
jQuery('.do-action-button').click(function (e) {
    e.preventDefault();
    var id = jQuery(e.target).parent('div').attr('id');
    var target_url = jQuery(e.target).attr('name');
    var ajax_fn = jQuery(e.target).attr('data-fn');
    var message = jQuery(e.target).attr('data-message');
    let result = window.confirm(message + "\nAre you sure you want to do this?");
    if (result === true) {
        cdp_ajax_call(ajax_fn, '', '').done(function (result) {
            if (ajax_fn === 'runCleanReset') {
                window.location = target_url;
            } else {
                location.reload();
            }
        }).fail(function () {
            alert(name + " not removed");
        });
    }

});
// End Admin Help Page

//https://jqueryui.com/sortable/
jQuery(document).ready(function() {
    jQuery(".drag-table").sortable({
        items: 'tr',
        dropOnEmpty: false,
        start: function (event, ui) {
            ui.item.addClass("select");
        },
        stop: function (event, ui) {
            ui.item.removeClass("select");
            reorder_attributes();
        }
    });
});

function reorder_attributes() {
    jQuery('.drag-table').each(function () {
        let positions = jQuery(".input-position")
            .map(function () {
                return jQuery(this).val();
            }).get();
        let postions_reorderd = positions;
        postions_reorderd.sort(function (a, b) {
            return a - b;
        });
        jQuery(".input-position")
            .map(function (index) {
                jQuery(this).val(postions_reorderd[index]);
            });
    })
}