<?php
ob_start();
require_once 'config.php';
requireEncryptLogin();

$user = getEncryptUser();
$packages = getEncryptPackages();
$error = '';
$success = '';
$is_renew = false;
$existing_service = null;
$remaining_days = 0;

// 优惠码相关
$coupon_code = '';
$coupon_info = null;
$discount_amount = 0;

// 检查是否已有有效服务
$existing_service = getUserEncryptService($user);
if ($existing_service) {
    if (is_null($existing_service['expire_date'])) {
        header('Location: /encrypt/encrypt.php');
        exit;
    } else {
        $remaining_days = getServiceRemainingDays($existing_service);
        $is_renew = true;
    }
}

// 处理优惠码提交
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['check_coupon'])) {
    $coupon_code = trim($_POST['coupon_code'] ?? '');
    $package_id = intval($_POST['package_id'] ?? 0);
    $selected_package = getPackageById($package_id);
    
    if ($selected_package) {
        $price = floatval($selected_package['price']);
        $coupon_info = validateCoupon($coupon_code, $user['id'], $price);
        if (!$coupon_info['valid']) {
            $error = $coupon_info['message'];
        }
    }
}

// 防重复提交锁
$lock_key = "encrypt_buy_lock_{$user['id']}";

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['check_coupon'])) {
    $package_id = intval($_POST['package_id'] ?? 0);
    $coupon_code = trim($_POST['coupon_code'] ?? '');
    $selected_package = getPackageById($package_id);
    
    if (!$selected_package) {
        $error = '请选择有效的套餐';
    } elseif (isset($_SESSION[$lock_key]) && $_SESSION[$lock_key] > time() - 5) {
        $error = '操作过于频繁，请稍后再试';
    } else {
        $_SESSION[$lock_key] = time();
        
        $price = floatval($selected_package['price']);
        
        // 验证优惠码
        if ($coupon_code) {
            $coupon_info = validateCoupon($coupon_code, $user['id'], $price);
            if ($coupon_info['valid']) {
                $price = $coupon_info['final_amount'];
                $discount_amount = $coupon_info['discount'];
            } else {
                $error = $coupon_info['message'];
                unset($_SESSION[$lock_key]);
            }
        }
        
        if (!$error && $user['balance'] < $price) {
            $error = '余额不足，请先充值';
            unset($_SESSION[$lock_key]);
        }
        
        if (!$error) {
            $db->query("START TRANSACTION");
            
            try {
                $check = $db->fetchOne("SELECT balance FROM users WHERE id = {$user['id']} FOR UPDATE");
                if ($check['balance'] < $price) {
                    throw new Exception('余额不足');
                }
                
                $remark = "购买PHP加密服务 - {$selected_package['name']}";
                if ($coupon_info && $coupon_info['valid']) {
                    $remark .= " [优惠码: {$coupon_code} 优惠¥{$discount_amount}]";
                }
                updateUserBalance($user['id'], -$price, $remark);
                
                if ($coupon_info && $coupon_info['valid']) {
                    recordCouponUsage($coupon_info['coupon_id'], $user['id'], $selected_package['price'], $discount_amount);
                }
                
                $expire_date = null;
                if (!is_null($selected_package['days'])) {
                    $expire_date = date('Y-m-d H:i:s', strtotime("+{$selected_package['days']} days"));
                }
                
                $exist = $db->fetchOne("SELECT id, expire_date FROM encrypt_services WHERE user_id = {$user['id']} AND service_name = 'php_encrypt'");
                
                if ($exist) {
                    if (is_null($expire_date)) {
                        $db->query("UPDATE encrypt_services SET expire_date = NULL, status = 1 WHERE user_id = {$user['id']} AND service_name = 'php_encrypt'");
                    } else {
                        $current_expire = $exist['expire_date'];
                        if ($current_expire && strtotime($current_expire) > time()) {
                            $new_expire = date('Y-m-d H:i:s', strtotime($current_expire . " + {$selected_package['days']} days"));
                        } else {
                            $new_expire = $expire_date;
                        }
                        $db->query("UPDATE encrypt_services SET expire_date = '{$new_expire}', status = 1 WHERE user_id = {$user['id']} AND service_name = 'php_encrypt'");
                    }
                } else {
                    if (is_null($expire_date)) {
                        $db->query("INSERT INTO encrypt_services (user_id, service_name, status, expire_date) VALUES ({$user['id']}, 'php_encrypt', 1, NULL)");
                    } else {
                        $db->query("INSERT INTO encrypt_services (user_id, service_name, status, expire_date) VALUES ({$user['id']}, 'php_encrypt', 1, '{$expire_date}')");
                    }
                }
                
                $db->query("COMMIT");
                
                $user_email = $user['email'] ?? '';
                if (!empty($user_email) && ($user['email_notify'] ?? 1)) {
                    $mail_expire_date = isset($new_expire) ? $new_expire : (isset($expire_date) ? $expire_date : null);
                    sendPurchaseNotification($user, $selected_package['name'], $mail_expire_date, $selected_package['price'], $discount_amount);
                }
                
                unset($_SESSION[$lock_key]);
                
                $success = '购买成功！' . ($exist ? '服务已续费，' : '您已获得 ') . $selected_package['name'] . ' 加密服务';
                if ($discount_amount > 0) {
                    $success .= " (优惠 ¥{$discount_amount})";
                }
                $user = getEncryptUser();
                
                echo '<script>setTimeout(function(){ window.location.href = "/encrypt/encrypt.php"; }, 1500);</script>';
                
            } catch (Exception $e) {
                $db->query("ROLLBACK");
                $error = $e->getMessage();
                unset($_SESSION[$lock_key]);
            }
        }
    }
}
?>
<?php include 'header.php'; ?>

<div class="encrypt-buy-container">
    <div class="buy-wrapper">
        <div class="buy-card">
            <!-- 页面头部 -->
            <div class="page-header">
                <h2>
                    <?php if ($is_renew): ?>
                        <img src="https://api.iconify.design/mdi:refresh-circle.svg?color=%23667eea" width="28" height="28" style="margin-right: 8px;" alt="">
                        续费加密服务
                    <?php else: ?>
                        <img src="https://api.iconify.design/mdi:crown.svg?color=%23fbbf24" width="28" height="28" style="margin-right: 8px;" alt="">
                        选择加密服务套餐
                    <?php endif; ?>
                </h2>
                <p class="buy-subtitle">
                    <?php if ($is_renew): ?>
                        当前服务剩余 <strong class="renew-days"><?php echo $remaining_days; ?> 天</strong>，续费后可延长有效期
                    <?php else: ?>
                        不限加密次数，永久有效或按需选择
                    <?php endif; ?>
                </p>
            </div>
            
            <?php if ($success): ?>
                <div class="alert alert-success">
                    <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="24" height="24" alt="">
                    <?php echo $success; ?>
                </div>
                <div class="action-center">
                    <a href="/encrypt/encrypt.php" class="btn btn-primary btn-lg">
                        立即加密
                        <img src="https://api.iconify.design/mdi:arrow-right.svg?color=white" width="20" height="20" alt="">
                    </a>
                </div>
            <?php elseif ($error && strpos($error, '永久') !== false): ?>
                <div class="alert alert-error">
                    <img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23ef4444" width="24" height="24" alt="">
                    <?php echo $error; ?>
                </div>
                <div class="action-center">
                    <a href="/encrypt/encrypt.php" class="btn btn-primary btn-lg">
                        前往加密
                        <img src="https://api.iconify.design/mdi:arrow-right.svg?color=white" width="20" height="20" alt="">
                    </a>
                </div>
            <?php elseif ($error): ?>
                <div class="alert alert-error">
                    <img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23ef4444" width="24" height="24" alt="">
                    <?php echo $error; ?>
                </div>
                <div class="action-center">
                    <a href="/admin.php?page=recharge" class="btn btn-primary btn-lg">
                        <img src="https://api.iconify.design/mdi:wallet-plus.svg?color=white" width="20" height="20" alt="">
                        去充值
                    </a>
                </div>
            <?php else: ?>
                <?php if ($is_renew && $existing_service): ?>
                    <div class="renew-info-card">
                        <div class="renew-info-item">
                            <img src="https://api.iconify.design/mdi:calendar.svg?color=%236b7280" width="18" height="18" alt="">
                            <span>当前服务到期时间：</span>
                            <strong><?php echo date('Y-m-d H:i', strtotime($existing_service['expire_date'])); ?></strong>
                        </div>
                        <div class="renew-info-item">
                            <span class="renew-badge">
                                <img src="https://api.iconify.design/mdi:clock-outline.svg?color=%23f59e0b" width="14" height="14" alt="">
                                剩余 <strong><?php echo $remaining_days; ?> 天</strong>
                            </span>
                        </div>
                    </div>
                <?php endif; ?>
                
                <!-- 套餐列表 -->
                <div class="packages-grid">
                    <?php foreach ($packages as $package): ?>
                        <div class="package-card" 
                             data-id="<?php echo $package['id']; ?>"
                             data-name="<?php echo htmlspecialchars($package['name']); ?>"
                             data-price="<?php echo $package['price']; ?>">
                            <div class="package-icon">
                                <?php if ($package['days'] === null): ?>
                                    <img src="https://api.iconify.design/mdi:crown.svg?color=%23fbbf24" width="32" height="32" alt="">
                                <?php elseif ($package['days'] <= 7): ?>
                                    <img src="https://api.iconify.design/mdi:calendar-today.svg?color=%23667eea" width="32" height="32" alt="">
                                <?php elseif ($package['days'] <= 30): ?>
                                    <img src="https://api.iconify.design/mdi:calendar-month.svg?color=%23667eea" width="32" height="32" alt="">
                                <?php elseif ($package['days'] <= 90): ?>
                                    <img src="https://api.iconify.design/mdi:calendar-range.svg?color=%23667eea" width="32" height="32" alt="">
                                <?php else: ?>
                                    <img src="https://api.iconify.design/mdi:star.svg?color=%23fbbf24" width="32" height="32" alt="">
                                <?php endif; ?>
                            </div>
                            <h3 class="package-name"><?php echo htmlspecialchars($package['name']); ?></h3>
                            <div class="package-price" data-original-price="<?php echo $package['price']; ?>">
                                ¥<?php echo number_format($package['price'], 2); ?>
                            </div>
                            <div class="package-days">
                                <img src="https://api.iconify.design/mdi:clock-outline.svg?color=%236b7280" width="14" height="14" alt="">
                                <?php echo $package['days'] === null ? '永久有效' : $package['days'] . '天有效期'; ?>
                            </div>
                            <?php if ($is_renew && $package['days'] !== null): ?>
                                <div class="package-renew-badge">
                                    <img src="https://api.iconify.design/mdi:plus-circle.svg?color=%2310b981" width="14" height="14" alt="">
                                    续费延长 <?php echo $package['days']; ?> 天
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
                
                <!-- 优惠码区域 -->
                <div class="coupon-section">
                    <div class="coupon-header">
                        <img src="https://api.iconify.design/mdi:ticket-percent.svg?color=%23667eea" width="20" height="20" alt="">
                        <span>优惠码</span>
                    </div>
                    <div class="coupon-input-group">
                        <input type="text" id="coupon_code" class="coupon-input" placeholder="请输入优惠码" value="<?php echo htmlspecialchars($coupon_code); ?>">
                        <button type="button" id="check_coupon_btn" class="btn btn-outline">
                            <img src="https://api.iconify.design/mdi:check.svg?color=currentColor" width="18" height="18" alt="">
                            验证
                        </button>
                    </div>
                    <div id="coupon_message" class="coupon-message" style="display: none;"></div>
                </div>
                
                <!-- 订单金额卡片 -->
                <div class="order-summary">
                    <div class="order-row">
                        <span class="order-label">
                            <img src="https://api.iconify.design/mdi:tag.svg?color=%236b7280" width="16" height="16" alt="">
                            订单金额：
                        </span>
                        <span class="order-amount" id="order_amount">¥0.00</span>
                    </div>
                    <div class="order-row" id="discount_row" style="display: none;">
                        <span class="order-label">
                            <img src="https://api.iconify.design/mdi:ticket-percent.svg?color=%2310b981" width="16" height="16" alt="">
                            优惠：
                        </span>
                        <span class="discount-amount" id="discount_amount">-¥0.00</span>
                    </div>
                    <div class="order-row final-row">
                        <span class="order-label">
                            <img src="https://api.iconify.design/mdi:cash.svg?color=%23667eea" width="16" height="16" alt="">
                            应付金额：
                        </span>
                        <span class="final-amount" id="final_amount">¥0.00</span>
                    </div>
                    <div class="order-row balance-row">
                        <span class="order-label">
                            <img src="https://api.iconify.design/mdi:wallet.svg?color=%236b7280" width="16" height="16" alt="">
                            当前余额：
                        </span>
                        <span class="balance-amount">¥<?php echo number_format($user['balance'], 2); ?></span>
                    </div>
                    <a href="/admin.php?page=recharge" class="recharge-link">
                        <img src="https://api.iconify.design/mdi:wallet-plus.svg?color=%23667eea" width="16" height="16" alt="">
                        余额不足？立即充值
                    </a>
                </div>
                
                <form method="POST" id="buyForm">
                    <input type="hidden" name="package_id" id="package_id" value="">
                    <input type="hidden" name="coupon_code" id="hidden_coupon_code" value="">
                    <div id="selectedInfo" class="selected-info" style="display: none;">
                        <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="18" height="18" alt="">
                        <span>已选择：<strong id="selectedName"></strong> - ¥<span id="selectedPrice"></span></span>
                    </div>
                    <button type="submit" class="btn btn-primary buy-submit-btn" id="buyBtn" disabled>
                        <?php echo $is_renew ? '确认续费' : '确认购买'; ?>
                    </button>
                </form>
                
                <?php if ($is_renew): ?>
                    <div class="skip-renew">
                        <a href="/encrypt/encrypt.php" class="btn btn-link">
                            暂不续费，前往加密
                            <img src="https://api.iconify.design/mdi:arrow-right.svg?color=currentColor" width="16" height="16" alt="">
                        </a>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<style>
.encrypt-buy-container {
    max-width: 900px;
    margin: 0 auto;
    padding: 20px;
}

.buy-wrapper {
    max-width: 900px;
    margin: 0 auto;
}

.buy-card {
    background: var(--bg-primary);
    border-radius: 28px;
    padding: 36px 32px;
    border: 1px solid var(--border-color);
    box-shadow: var(--shadow-lg);
}

.page-header {
    text-align: center;
    margin-bottom: 16px;
}
.page-header h2 {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28px;
    font-weight: 700;
    background: linear-gradient(135deg, #667eea, #764ba2);
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
}
.buy-subtitle {
    text-align: center;
    color: var(--text-secondary);
    margin-bottom: 32px;
    font-size: 15px;
}
.renew-days {
    color: #f59e0b;
    font-size: 20px;
}

/* 提示消息 */
.alert {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 16px 20px;
    border-radius: 16px;
    margin-bottom: 24px;
}
.alert-success {
    background: #d1fae5;
    color: #065f46;
    border: 1px solid #a7f3d0;
}
.alert-error {
    background: #fee2e2;
    color: #991b1b;
    border: 1px solid #fecaca;
}
.action-center {
    text-align: center;
    margin-top: 24px;
}

/* 续费信息卡片 */
.renew-info-card {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 16px;
    background: linear-gradient(135deg, rgba(245,158,11,0.08), rgba(245,158,11,0.02));
    border: 1px solid rgba(245,158,11,0.3);
    border-radius: 16px;
    padding: 16px 24px;
    margin-bottom: 32px;
}
.renew-info-item {
    display: flex;
    align-items: center;
    gap: 8px;
    color: var(--text-secondary);
}
.renew-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: #f59e0b;
    color: white;
    padding: 6px 14px;
    border-radius: 30px;
    font-size: 13px;
}

/* 套餐网格 */
.packages-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 20px;
    margin-bottom: 32px;
}
.package-card {
    background: var(--bg-secondary);
    border-radius: 20px;
    padding: 24px 16px;
    text-align: center;
    cursor: pointer;
    border: 2px solid transparent;
    transition: all 0.25s ease;
}
.package-card:hover {
    transform: translateY(-4px);
    box-shadow: var(--shadow-md);
}
.package-card.selected {
    border-color: #667eea;
    background: linear-gradient(135deg, rgba(102,126,234,0.1), rgba(118,75,162,0.08));
}
.package-icon {
    margin-bottom: 12px;
}
.package-name {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 8px;
    color: var(--text-primary);
}
.package-price {
    font-size: 28px;
    font-weight: 700;
    color: #667eea;
    margin-bottom: 6px;
}
.package-days {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
    font-size: 13px;
    color: var(--text-muted);
}
.package-renew-badge {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
    margin-top: 10px;
    font-size: 12px;
    color: #10b981;
    background: rgba(16,185,129,0.1);
    padding: 4px 10px;
    border-radius: 30px;
}

/* 优惠码区域 */
.coupon-section {
    margin-bottom: 24px;
}
.coupon-header {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    margin-bottom: 12px;
    color: var(--text-primary);
}
.coupon-input-group {
    display: flex;
    gap: 12px;
}
.coupon-input {
    flex: 1;
    padding: 12px 16px;
    background: var(--bg-primary);
    border: 1.5px solid var(--border-color);
    border-radius: 12px;
    color: var(--text-primary);
    font-size: 14px;
}
.coupon-input:focus {
    outline: none;
    border-color: #667eea;
}
.btn-outline {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 12px 20px;
    background: var(--bg-secondary);
    border: 1.5px solid var(--border-color);
    border-radius: 12px;
    color: var(--text-primary);
    font-weight: 500;
    cursor: pointer;
}
.coupon-message {
    margin-top: 10px;
    font-size: 13px;
    padding: 8px 14px;
    border-radius: 10px;
}
.coupon-message.success {
    background: rgba(16,185,129,0.1);
    color: #10b981;
}
.coupon-message.error {
    background: rgba(239,68,68,0.1);
    color: #ef4444;
}

/* 订单汇总 */
.order-summary {
    background: var(--bg-secondary);
    border-radius: 20px;
    padding: 24px;
    margin-bottom: 28px;
}
.order-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
}
.order-label {
    display: flex;
    align-items: center;
    gap: 8px;
    color: var(--text-secondary);
}
.order-amount {
    font-size: 16px;
    color: var(--text-muted);
    text-decoration: line-through;
}
.discount-amount {
    font-size: 16px;
    color: #10b981;
    font-weight: 600;
}
.final-row {
    padding-top: 16px;
    margin-top: 8px;
    border-top: 1px dashed var(--border-color);
}
.final-amount {
    font-size: 28px;
    font-weight: 700;
    color: #667eea;
}
.balance-row {
    margin-top: 8px;
}
.balance-amount {
    font-size: 18px;
    font-weight: 600;
    color: var(--text-primary);
}
.recharge-link {
    display: flex;
    align-items: center;
    gap: 6px;
    margin-top: 16px;
    color: #667eea;
    text-decoration: none;
    font-size: 14px;
}

/* 选中信息 */
.selected-info {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    margin-bottom: 20px;
    padding: 12px 20px;
    background: rgba(102,126,234,0.1);
    border-radius: 30px;
    color: #667eea;
}

/* 提交按钮 */
.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 12px 24px;
    border-radius: 14px;
    font-weight: 600;
    text-decoration: none;
    transition: all 0.2s;
    cursor: pointer;
    border: none;
}
.btn-primary {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
}
.btn-primary:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(102,126,234,0.4);
}
.btn-primary:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}
.btn-lg {
    padding: 14px 32px;
    font-size: 16px;
}
.buy-submit-btn {
    width: 100%;
    padding: 16px;
    font-size: 16px;
}
.btn-link {
    background: transparent;
    color: var(--text-secondary);
}
.btn-link:hover {
    color: #667eea;
}
.skip-renew {
    text-align: center;
    margin-top: 20px;
}

/* 响应式 */
@media (max-width: 768px) {
    .buy-card {
        padding: 24px 20px;
    }
    .packages-grid {
        grid-template-columns: 1fr;
    }
    .renew-info-card {
        flex-direction: column;
        align-items: flex-start;
    }
}
</style>

<script>
    let selectedPackageId = null;
    let selectedPackagePrice = 0;
    let selectedPackageName = '';
    let currentCouponValid = false;
    let currentDiscount = 0;
    let currentCouponCode = '';
    
    document.querySelectorAll('.package-card').forEach(card => {
        card.addEventListener('click', function(e) {
            const id = this.dataset.id;
            const name = this.dataset.name;
            const price = parseFloat(this.dataset.price);
            
            selectedPackageId = id;
            selectedPackagePrice = price;
            selectedPackageName = name;
            
            document.getElementById('package_id').value = id;
            document.getElementById('selectedName').innerText = name;
            document.getElementById('selectedPrice').innerText = price.toFixed(2);
            document.getElementById('selectedInfo').style.display = 'flex';
            
            updatePriceDisplay(price, 0);
            
            const buyBtn = document.getElementById('buyBtn');
            buyBtn.disabled = false;
            buyBtn.innerHTML = '<?php echo $is_renew ? "确认续费" : "确认购买"; ?> ' + name + '（¥' + price.toFixed(2) + '）';
            
            document.querySelectorAll('.package-card').forEach(c => c.classList.remove('selected'));
            this.classList.add('selected');
            
            const couponCode = document.getElementById('coupon_code').value;
            if (couponCode) validateCouponCode(couponCode);
        });
    });
    
    function updatePriceDisplay(originalPrice, discount) {
        const finalPrice = originalPrice - discount;
        document.getElementById('order_amount').innerHTML = '¥' + originalPrice.toFixed(2);
        if (discount > 0) {
            document.getElementById('discount_row').style.display = 'flex';
            document.getElementById('discount_amount').innerHTML = '-¥' + discount.toFixed(2);
            document.getElementById('final_amount').innerHTML = '¥' + finalPrice.toFixed(2);
            if (selectedPackageName) {
                document.getElementById('buyBtn').innerHTML = '<?php echo $is_renew ? "确认续费" : "确认购买"; ?> ' + selectedPackageName + '（¥' + finalPrice.toFixed(2) + '）';
            }
        } else {
            document.getElementById('discount_row').style.display = 'none';
            document.getElementById('final_amount').innerHTML = '¥' + finalPrice.toFixed(2);
        }
    }
    
    function showCouponMessage(msg, type) {
        const msgDiv = document.getElementById('coupon_message');
        const icon = type === 'success' 
            ? '<img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="16" height="16" alt="">'
            : '<img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23ef4444" width="16" height="16" alt="">';
        msgDiv.innerHTML = icon + ' ' + msg;
        msgDiv.className = 'coupon-message ' + type;
        msgDiv.style.display = 'block';
        setTimeout(() => msgDiv.style.display = 'none', 3000);
    }
    
    function validateCouponCode(code) {
        if (!selectedPackageId) {
            showCouponMessage('请先选择套餐', 'error');
            return;
        }
        const checkBtn = document.getElementById('check_coupon_btn');
        const originalHtml = checkBtn.innerHTML;
        checkBtn.disabled = true;
        checkBtn.innerHTML = '<span class="spinner"></span> 验证中...';
        
        fetch('/encrypt/api_coupon.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'code=' + encodeURIComponent(code) + '&package_id=' + selectedPackageId
        })
        .then(response => response.json())
        .then(data => {
            checkBtn.disabled = false;
            checkBtn.innerHTML = originalHtml;
            if (data.valid) {
                currentCouponValid = true;
                currentDiscount = data.discount;
                currentCouponCode = code;
                showCouponMessage(data.message, 'success');
                updatePriceDisplay(selectedPackagePrice, data.discount);
                document.getElementById('hidden_coupon_code').value = code;
            } else {
                currentCouponValid = false;
                currentDiscount = 0;
                currentCouponCode = '';
                showCouponMessage(data.message, 'error');
                updatePriceDisplay(selectedPackagePrice, 0);
                document.getElementById('hidden_coupon_code').value = '';
            }
        })
        .catch(error => {
            checkBtn.disabled = false;
            checkBtn.innerHTML = originalHtml;
            showCouponMessage('网络错误，请重试', 'error');
        });
    }
    
    document.getElementById('check_coupon_btn').addEventListener('click', function() {
        const code = document.getElementById('coupon_code').value;
        if (!code) { showCouponMessage('请输入优惠码', 'error'); return; }
        validateCouponCode(code);
    });
    
    document.getElementById('coupon_code').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            const code = this.value;
            if (code) validateCouponCode(code);
        }
    });
    
    let isSubmitting = false;
    document.getElementById('buyForm')?.addEventListener('submit', function(e) {
        if (!selectedPackageId) {
            e.preventDefault();
            alert('请先选择套餐');
            return;
        }
        if (isSubmitting) {
            e.preventDefault();
            alert('正在处理中，请勿重复提交');
            return;
        }
        const couponCode = document.getElementById('coupon_code').value;
        if (couponCode && currentCouponValid) {
            document.getElementById('hidden_coupon_code').value = couponCode;
        }
        isSubmitting = true;
        const btn = document.getElementById('buyBtn');
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner"></span> 处理中...';
    });
    
    const style = document.createElement('style');
    style.textContent = `.spinner{display:inline-block;width:16px;height:16px;border:2px solid rgba(255,255,255,0.3);border-radius:50%;border-top-color:white;animation:spin 0.6s linear infinite;margin-right:8px;}@keyframes spin{to{transform:rotate(360deg);}}`;
    document.head.appendChild(style);
</script>
<?php include 'footer.php'; ?>