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>
    <?php
    return ob_get_clean();
}
add_shortcode('sigmaweb_generate_coupon_form', 'sigmaweb_generate_coupon_form_ajax_shortcode');