jQuery(document).ready(function ($) {
    $('#fleximp-install-plugins').on('click', function () {
        this.disabled = true;
        this.innerText = 'Installing...';
        $.ajax({
            url: fleximp_admin_ajax_object.ajax_url,
            method: 'POST',
            data: {
                action: 'fleximp_get_required_plugins',
                _ajax_nonce: fleximp_admin_ajax_object.fleximp_nonce
            },
            success: function (response) {
                if (response.success) {
                    const plugins = response.data;
                    installPlugin(plugins, 0);
                } else {
                    const errorMessage = response.data ? response.data : 'An unexpected error occurred while fetching plugins.';
                    alert(errorMessage);
                }
            },
            error: function () {
                alert('An error occurred while fetching the plugins.');
            }
        });

        function installPlugin(plugins, index) {
            if (index >= plugins.length) {
                $('#fleximp-install-plugins').text('All plugins installed successfully.');
                return;
            }

            const plugin = plugins[index];
            const statusElement = $(`#plugin-status-${plugin.slug}`);
            statusElement.html('<span class="spinner is-active"></span> Installing...');

            $.ajax({
                url: fleximp_admin_ajax_object.ajax_url,
                method: 'POST',
                data: {
                    action: 'fleximp_install_single_plugin',
                    plugin_slug: plugin.slug,
                    _ajax_nonce: fleximp_admin_ajax_object.fleximp_nonce
                },
                success: function (response) {
                    const statusElement = $(`#plugin-status-${plugin.slug}`);

                    if (typeof response === 'string') {
                        const jsonResponseMatch = response.match(/(\{.*\})$/);

                        if (jsonResponseMatch) {
                            try {
                                const jsonResponse = JSON.parse(jsonResponseMatch[0]);

                                if (jsonResponse.success) {
                                    statusElement.html('<span class="dashicons dashicons-yes"></span> ' + (jsonResponse.data.message || 'success.'));
                                } else {
                                    const errorMessage = jsonResponse.data.message || 'fail.';
                                    statusElement.html(`<span class="dashicons dashicons-no-alt"></span> ${errorMessage}`);
                                }
                            } catch (e) {
                                statusElement.html('<span class="dashicons dashicons-no-alt"></span> Fail.');
                            }
                        } else {
                            statusElement.html('<span class="dashicons dashicons-no-alt"></span> Fail.');
                        }
                    } else if (typeof response === 'object' && response !== null) {
                        if (response.success) {
                            statusElement.html('<span class="dashicons dashicons-yes"></span> ' + (response.data.message || 'success.'));
                        } else {
                            const errorMessage = response.data.message || 'An unknown error occurred during installation.';
                            statusElement.html(`<span class="dashicons dashicons-no-alt"></span> ${errorMessage}`);
                        }
                    } else {
                        statusElement.html('<span class="dashicons dashicons-no-alt"></span> Fail.');
                    }

                    installPlugin(plugins, index + 1);
                },


                error: function () {
                    const statusElement = $(`#plugin-status-${plugin.slug}`);
                    statusElement.html('<span class="dashicons dashicons-no-alt"></span> Installation failed.');
                    installPlugin(plugins, index + 1); // Continue with the next plugin
                }
            });
        }
    });
});



jQuery(document).ready(function ($) {
    $(document).on('click', '.download-btn', function (e) {
        e.preventDefault();

        const $button = $(this);
        const pluginSlug = $button.data('plugin-url').split('/').pop().replace('.latest-stable.zip', '');
        const pluginName = $button.data('plugin-name');
        const pluginMainFile = $button.data('plugin-main-file');

        $button.addClass('installing').prop('disabled', true);

        $.ajax({
            url: fleximp_admin_ajax_object.ajax_url,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'fleximp_install_plugin',
                security: fleximp_admin_ajax_object.fleximp_nonce,
                plugin_slug: pluginSlug,
                plugin_name: pluginName,
                plugin_main_file: pluginMainFile,
            },
            success: function (response) {
                const $status = $(`#plugin-status-${pluginSlug}`);
                if (response.success) {
                    $button.removeClass('installing').addClass('activated').prop('disabled', true);
                    $status.text('Activated');
                } else {
                    alert(response.data.message || 'Failed to install the plugin.');
                    $button.removeClass('installing').prop('disabled', false);
                    $status.text('Failed to install');
                }
            },
            error: function () {
                $button.removeClass('installing').addClass('activated').prop('disabled', true);
                const $status = $(`#plugin-status-${pluginSlug}`);
                $status.text('');

            },
        });
    });

    $('#install-all-btn').on('click', function () {
        const selectedPlugins = [];

        $('.plugin-checkbox:checked').each(function () {
            const $checkbox = $(this);
            selectedPlugins.push({
                pluginSlug: $checkbox.data('plugin-url').split('/').pop().replace('.latest-stable.zip', ''),
                pluginName: $checkbox.data('plugin-name'),
                pluginMainFile: $checkbox.data('plugin-main-file')
            });
        });

        if (selectedPlugins.length === 0) {
            alert('Please select at least one plugin to install.');
            return;
        }

        installPluginsInSequence(selectedPlugins);

        $('#install-all-btn').text('Installing All...').prop('disabled', true);

        $('#install-all-btn').text('Install All Selected').prop('disabled', false);
    });


    // Function to install plugins sequentially
    function installPluginsInSequence(plugins) {
        // if (plugins.length === 0) return;
        if (plugins.length === 0) {
            $('#install-all-btn').text('Install All Selected').prop('disabled', false);
            return;
        }

        const currentPlugin = plugins.shift();
        const $status = $(`#plugin-status-${currentPlugin.pluginSlug}`);
        //new const $button = $(`.download-btn[data-plugin-url*="${currentPlugin.pluginSlug}"]`);
        const $button = $(`.download-btn[data-plugin-url*="${currentPlugin.pluginSlug}"]`);
        $status.text('Installing...');
        $button.addClass('installing').prop('disabled', true);

        fetch(fleximp_admin_ajax_object.ajax_url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `action=fleximp_install_plugin&security=${fleximp_admin_ajax_object.fleximp_nonce}&plugin_slug=${currentPlugin.pluginSlug}&plugin_name=${currentPlugin.pluginName}&plugin_main_file=${currentPlugin.pluginMainFile}`
        })
            .then(response => {
                // Check if the response is JSON
                const contentType = response.headers.get('content-type');
                if (contentType && contentType.includes('application/json')) {
                    return response.json();
                } else {
                    return response.text();
                }
            })
            .then(data => {
                if (typeof data === 'object' && data.success) {
                    $status.text('Activated');
                    $button.removeClass('installing').addClass('activated').prop('disabled', true);

                } else if (typeof data === 'string') {
                    console.log('Plugin installation message:', data);
                    $status.text('Check console for details'); 
                    $button.removeClass('installing').addClass('activated').prop('disabled', true);
                } else {
                    $status.text('Failed to install/activate');
                }
                installPluginsInSequence(plugins); 
            })
            .catch(error => {
                console.error('Error installing plugin:', error);
                $status.text('Error occurred');
                installPluginsInSequence(plugins); 
            });
    }
});

// code for metafield in theme 
jQuery(document).ready(function ($) {
    var mediaUploader;
    $('.custom_media_button').click(function (e) {
        e.preventDefault();
        if (mediaUploader) {
            mediaUploader.open();
            return;
        }
        mediaUploader = wp.media.frames.file_frame = wp.media({
            title: 'Select Image',
            button: { text: 'Use this image' },
            multiple: false
        });
        mediaUploader.on('select', function () {
            var attachment = mediaUploader.state().get('selection').first().toJSON();
            $('#service_category_image').val(attachment.id);
            $('#service_category_image_preview').html('<img src="' + attachment.url + '" style="max-width:100px;" />');
        });
        mediaUploader.open();
    });
});


jQuery(document).ready(function ($) {
    var mediaUploader;
    $('.custom_media_button').click(function (e) {
        e.preventDefault();
        if (mediaUploader) {
            mediaUploader.open();
            return;
        }
        mediaUploader = wp.media.frames.file_frame = wp.media({
            title: 'Select Image',
            button: { text: 'Use this image' },
            multiple: false
        });
        mediaUploader.on('select', function () {
            var attachment = mediaUploader.state().get('selection').first().toJSON();
            $('#service_category_image').val(attachment.id);
            $('#service_category_image_preview').html('<img src="' + attachment.url + '" style="max-width:100px;" />');
        });
        mediaUploader.open();
    });
});