jQuery(document).ready(function($) {
    $('#confirm-button').on('click', function(e) {
        e.preventDefault();
        
        // Extract ID from the URL
        var href = $(this).attr('href');
        var urlParams = new URLSearchParams(href.split('?')[1]);
        var id = urlParams.get('id');

		// Display loader on click
		$('#TB_ajaxContent').html('<span class="loader-adfw"></span>');

        // Check if ID is available
        if (id) {
            $.ajax({
                url: adfw_ajax_object.ajax_url,
                method: 'POST',
                data: {
                    action: 'update_option_with_id',
                    id: id,
					security: adfw_ajax_object.nonce
                },
                success: function(response) {
                    if (response.success) {
						$('#TB_ajaxContent').html('<h2>' + adfw_ajax_object.update_successfull + '</h2>');

						// Reload page
						setTimeout(function(){
							location.reload();
						}, 3000);

                    } else {
						$('#TB_ajaxContent').html('<h2>' + adfw_ajax_object.update_fail + ' : ' + response.data + '</h2>');
                    }
                },
                error: function(error) {
					$('#TB_ajaxContent').html(  adfw_ajax_object.update_error + ': ' + error);
                }
            });
        }
    });
});




document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('a.thickbox').forEach(function(element) {
        element.addEventListener('click', function() {
            // Extract the identifier from the URL fragment
            const hash = element.href.split('#')[1];
            const params = new URLSearchParams(hash.split('?')[1]);
            const identifier = params.get('identifier');

            // Use the identifier to update the href of the confirm button
            if (identifier) {
                document.getElementById('confirm-button').href = `update-design?id=${identifier}`;
            }
        });
    });
});
