<script>
document.addEventListener('DOMContentLoaded', function () {
    const form = document.getElementById('sigmaweb-coupon-form');
    const messageDiv = document.getElementById('sigmaweb-coupon-message');
    const formContainer = document.getElementById('sigmaweb-coupon-form-container');
    const ajax_url = "https://demo.sigma-webproject.ir/wp-admin/admin-ajax.php";

    if (!form) return;

    form.addEventListener('submit', function (e) {
        e.preventDefault();
        const email = form.querySelector('input[name="sigmaweb_email"]').value;

        messageDiv.innerHTML = '⏳ در حال پردازش...';
        messageDiv.className = 'sigmaweb-message sigmaweb-loading';

        fetch(ajax_url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                action: 'sigmaweb_generate_coupon',
                email: email
            })
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                formContainer.style.display = 'none';
                messageDiv.className = 'sigmaweb-message sigmaweb-success';
                messageDiv.innerHTML = `
                    <strong class="copy-coupon-text">${data.data}</strong>
                    <button class="copy-coupon-button">کپی کردن</button>
                `;

                const copyButton = document.querySelector(".copy-coupon-button");
                const textToCopy = document.querySelector(".copy-coupon-text");

                copyButton.addEventListener("click", function (event) {
                    var text = textToCopy.innerText;
                    var textArea = document.createElement("textarea");
                    textArea.value = text;
                    document.body.appendChild(textArea);
                    textArea.select();
                    document.execCommand("copy");
                    document.body.removeChild(textArea);
                    alert("کد تخفیف کپی شد: " + text);
                    event.preventDefault();
                });
            } else {
                messageDiv.className = 'sigmaweb-message sigmaweb-error';
                messageDiv.innerHTML = data.data;
            }
        })
        .catch(() => {
            messageDiv.className = 'sigmaweb-message sigmaweb-error';
            messageDiv.innerHTML = 'مشکلی در ارتباط رخ داده است.';
        });
    });

    // اضافه کردن کد جدید
    document.querySelector('.sigmaweb-close-gift-container').addEventListener('click', function () {
        const giftContainer = document.querySelector('.sigmaweb-gift-container');
        if (giftContainer) {
            giftContainer.remove();
        }
    });
});
</script>