add_action('wp_ajax_sigmaweb_generate_coupon', 'sigmaweb_generate_coupon_ajax');
add_action('wp_ajax_nopriv_sigmaweb_generate_coupon', 'sigmaweb_generate_coupon_ajax');

function sigmaweb_generate_coupon_ajax() {
    if (!isset($_POST['email']) || !is_email($_POST['email'])) {
        wp_send_json_error('ایمیل وارد شده نامعتبر است.');
    }

    $email = sanitize_email($_POST['email']);

    // بررسی وجود کوپن قبلی برای این ایمیل
    $existing_coupons = get_posts([
        'post_type'   => 'shop_coupon',
        'numberposts' => 1,
        'meta_query'  => [
            [
                'key'     => 'sigmaweb_coupon_email',
                'value'   => $email,
                'compare' => '='
            ]
        ]
    ]);

    if (!empty($existing_coupons)) {
        $coupon_title = $existing_coupons[0]->post_title;
        wp_send_json_success($coupon_title); // فقط خود کد
    }

    // ساخت کد جدید
    $code = 'SIGMAWEB-' . strtoupper(wp_generate_password(6, false));

    $coupon = [
        'post_title'  => $code,
        'post_status' => 'publish',
        'post_type'   => 'shop_coupon',
        'post_author' => 1,
    ];

    $new_coupon_id = wp_insert_post($coupon);

    // تنظیمات کوپن
    update_post_meta($new_coupon_id, 'discount_type', 'percent');
    update_post_meta($new_coupon_id, 'coupon_amount', '10'); // درصد تخفیف
    update_post_meta($new_coupon_id, 'individual_use', 'yes');
    update_post_meta($new_coupon_id, 'usage_limit', '1');
    update_post_meta($new_coupon_id, 'customer_email', [$email]);
    update_post_meta($new_coupon_id, 'sigmaweb_coupon_email', $email);

    // ارسال ایمیل
    $subject = 'کد تخفیف اختصاصی شما از SigmaWeb 🌟';
    $headers = ['Content-Type: text/html; charset=UTF-8'];
    $discount = '10%';
    $usage_limit = '1';

    $message = "
        <div style='font-family:Tahoma; direction:rtl;'>
            <h2 style='color:#2c3e50;'>کد تخفیف شما آماده است 🎉</h2>
            <p>سلام دوست خوب ما،</p>
            <p>برای شما، که همراه ما هستید، یک کد تخفیف اختصاصی ایجاد کردیم:</p>
            <ul>
                <li>🔐 <strong>کد:</strong> {$code}</li>
                <li>🎁 <strong>میزان تخفیف:</strong> {$discount}</li>
                <li>🔄 <strong>تعداد استفاده:</strong> فقط {$usage_limit} بار</li>
                <li>📩 <strong>ایمیل:</strong> {$email}</li>
            </ul>
            <p style='margin-top:20px;'>باشد که این تخفیف، لبخندی هرچند کوچک بر لبانتان بنشاند 😊</p>
            <p>با احترام فراوان<br>تیم SigmaWeb</p>
        </div>
    ";

    wp_mail($email, $subject, $message, $headers);

    // فقط خود کد را برگردان
    wp_send_json_success($code);
}

function sigmaweb_generate_coupon_form_ajax_shortcode() {
    ob_start();
    ?>
    <div id="sigmaweb-coupon-form-container" class="sigmaweb-form-wrapper">
        <form id="sigmaweb-coupon-form" class="sigmaweb-form">
            <input type="email" name="sigmaweb_email" placeholder="ایمیل خود را وارد کنید" required class="sigmaweb-input">
            <button type="submit" class="sigmaweb-button">دریافت کد تخفیف</button>
        </form>
    </div>
    <div id="sigmaweb-coupon-message" class="sigmaweb-message"></div>

    <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');

        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('<?php echo admin_url('admin-ajax.php'); ?>', {
                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;
                        copyTextToClipboard(text);
                        event.preventDefault();
                    });

                    function copyTextToClipboard(text) {
                        var textArea = document.createElement("textarea");
                        textArea.value = text;
                        document.body.appendChild(textArea);
                        textArea.select();
                        document.execCommand("copy");
                        document.body.removeChild(textArea);
                        alert("کد تخفیف کپی شد: " + text);
                    }
                } 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>
    <?php
    return ob_get_clean();
}
add_shortcode('sigmaweb_generate_coupon_form', 'sigmaweb_generate_coupon_form_ajax_shortcode');