/**
 * singleproduktimages.js
 *
 * Handles AJAX calls for fetching the Amazon image and setting it as the featured image.
 *
 * @package Boxyfy
 */

document.addEventListener("DOMContentLoaded", function() {
    var fetchButton = document.getElementById("fetch-amazon-image");
    if (fetchButton) {
        fetchButton.addEventListener("click", function() {
            var asin = document.getElementById("tsprodukt_asin2").value;
            var errorMessage = document.getElementById("error-message");
            var successMessage = document.getElementById("success-message");
            
            // Clear previous messages.
            errorMessage.innerHTML = "";
            successMessage.innerHTML = "";
            
            if (asin) {
                var xhr = new XMLHttpRequest();
				xhr.open("POST", boxyfyAmazonImage.ajax_url, true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        var response = JSON.parse(xhr.responseText);
                        if (response.success) {
                            successMessage.innerHTML = "Das Bild wurde erfolgreich als Beitragsbild gesetzt.";
                            errorMessage.innerHTML = "";
                            // Reload the page to reflect the new featured image.
                            location.reload();
                        } else {
                            errorMessage.innerHTML = response.data.message;
                            successMessage.innerHTML = "";
                        }
                    }
                };
                xhr.send(
                    "action=boxyfy_fetch_amazon_image" +
                    "&asin=" + encodeURIComponent(asin) +
                    "&post_id=" + boxyfyAmazonImage.post_id +
					"&nonce=" + boxyfyAmazonImage.nonce

                );
            } else {
                errorMessage.innerHTML = "Bitte geben Sie eine ASIN ein.";
                successMessage.innerHTML = "";
            }
        });
    }
});
