<?php
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 = null;
    if (isset($new_expire)) {
        $mail_expire_date = $new_expire;
    } elseif (isset($expire_date)) {
        $mail_expire_date = $expire_date;
    }
    
    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-container">
    <div class="buy-wrapper">
        <div class="card buy-card">
            
            <h2 class="buy-title">
                <?php echo $is_renew ? '🔄 续费加密服务' : '✨ 选择加密服务套餐'; ?>
            </h2>
            <p class="buy-subtitle">
                <?php if ($is_renew): ?>
                    当前服务剩余 <strong class="renew-days"><?php echo $remaining_days; ?> 天</strong>，续费后可延长有效期
                <?php else: ?>
                    不限加密次数，永久有效或按需选择
                <?php endif; ?>
            </p>
            
            <?php if ($success): ?>
                <div class="alert alert-success">
                    ✅ <?php echo $success; ?>
                </div>
                <div class="text-center">
                    <a href="/encrypt/encrypt.php" class="btn btn-primary">立即加密 →</a>
                </div>
            <?php elseif ($error && strpos($error, '永久') !== false): ?>
                <div class="alert alert-error">
                    ❌ <?php echo $error; ?>
                </div>
                <div class="text-center">
                    <a href="/encrypt/encrypt.php" class="btn btn-primary">前往加密 →</a>
                </div>
            <?php elseif ($error): ?>
                <div class="alert alert-error">
                    ❌ <?php echo $error; ?>
                </div>
                <div class="text-center">
                    <a href="/modules/user/recharge.php" class="btn btn-primary">去充值 →</a>
                </div>
            <?php else: ?>
                <?php if ($is_renew && $existing_service): ?>
                    <div class="renew-info">
                        <span>📅 当前服务到期时间：</span>
                        <strong><?php echo date('Y-m-d H:i:s', strtotime($existing_service['expire_date'])); ?></strong>
                        <span class="renew-info-badge">剩余 <strong><?php echo $remaining_days; ?> 天</strong></span>
                    </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) echo '👑';
                                elseif ($package['days'] <= 7) echo '📅';
                                elseif ($package['days'] <= 30) echo '📆';
                                elseif ($package['days'] <= 90) echo '📊';
                                else echo '⭐';
                                ?>
                            </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">
                                <?php 
                                if ($package['days'] === null) {
                                    echo '永久有效';
                                } else {
                                    echo $package['days'] . '天有效期';
                                }
                                ?>
                            </div>
                            <?php if ($is_renew && $package['days'] !== null): ?>
                                <div class="package-renew-badge">
                                    ➕ 续费延长 <?php echo $package['days']; ?> 天
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
                
                <!-- 优惠码区域 -->
                <div class="coupon-section">
                    <div class="coupon-header">
                        <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">验证</button>
                    </div>
                    <div id="coupon_message" class="coupon-message" style="display: none;"></div>
                </div>
                
                <div class="balance-card">
                    <div class="balance-info">
                        <strong>💰 订单金额：</strong>
                        <span class="order-amount" id="order_amount">¥0.00</span>
                    </div>
                    <div class="balance-info" id="discount_row" style="display: none;">
                        <strong>🎁 优惠：</strong>
                        <span class="discount-amount" id="discount_amount">-¥0.00</span>
                    </div>
                    <div class="balance-info">
                        <strong>💎 应付金额：</strong>
                        <span class="final-amount" id="final_amount">¥0.00</span>
                    </div>
                    <div class="balance-info">
                        <strong>💰 当前余额：</strong>
                        <span class="balance-amount">¥<?php echo number_format($user['balance'], 2); ?></span>
                    </div>
                    <div>
                        <a href="/modules/user/recharge.php" class="btn btn-secondary">充值</a>
                    </div>
                </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;">
                        <p>✅ 已选择：<strong id="selectedName"></strong> - ¥<span id="selectedPrice"></span></p>
                    </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="text-center skip-renew">
                        <a href="/encrypt/encrypt.php" class="btn btn-link">暂不续费，前往加密 →</a>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<style>
/* buy.php 专用样式 */
.buy-wrapper {
    max-width: 900px;
    margin: 0 auto;
}

.buy-card {
    background: var(--bg-primary);
    border-radius: 24px;
    padding: 32px;
    border: 1px solid var(--border-color);
    box-shadow: 0 4px 20px rgba(0,0,0,0.05);
}

.buy-title {
    text-align: center;
    margin-bottom: 8px;
    font-size: 28px;
    font-weight: 700;
    background: linear-gradient(135deg, #667eea, #764ba2);
    background-clip: text;
    -webkit-background-clip: text;
    color: transparent;
}

.buy-subtitle {
    text-align: center;
    color: var(--text-secondary);
    margin-bottom: 32px;
    font-size: 14px;
}

.renew-days {
    color: #f59e0b;
    font-size: 18px;
}

.renew-info {
    background: rgba(245,158,11,0.1);
    border: 1px solid #f59e0b;
    border-radius: 12px;
    padding: 14px 20px;
    margin-bottom: 28px;
    text-align: center;
    font-size: 14px;
}

.renew-info-badge {
    margin-left: 15px;
    background: #f59e0b;
    color: white;
    padding: 2px 10px;
    border-radius: 20px;
    font-size: 12px;
}

/* 套餐网格 */
.packages-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.package-card {
    background: var(--bg-secondary);
    border-radius: 16px;
    padding: 20px 16px;
    text-align: center;
    cursor: pointer;
    border: 2px solid transparent;
    transition: all 0.25s ease;
}

.package-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 25px rgba(0,0,0,0.1);
}

.package-card.selected {
    border-color: #667eea;
    background: linear-gradient(135deg, rgba(102,126,234,0.1), rgba(118,75,162,0.08));
    box-shadow: 0 4px 15px rgba(102,126,234,0.2);
}

.package-icon {
    font-size: 36px;
    margin-bottom: 10px;
}

.package-name {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 8px;
}

.package-price {
    font-size: 24px;
    font-weight: 700;
    color: #667eea;
}

.package-days {
    font-size: 12px;
    color: var(--text-muted);
    margin-top: 6px;
}

.package-renew-badge {
    margin-top: 8px;
    font-size: 11px;
    color: #10b981;
    background: rgba(16,185,129,0.1);
    display: inline-block;
    padding: 2px 8px;
    border-radius: 20px;
}

/* 优惠码区域 */
.coupon-section {
    margin: 20px 0;
    padding: 16px;
    background: var(--bg-secondary);
    border-radius: 14px;
}

.coupon-header {
    font-weight: 600;
    margin-bottom: 12px;
}

.coupon-input-group {
    display: flex;
    gap: 12px;
}

.coupon-input {
    flex: 1;
    padding: 10px 14px;
    background: var(--bg-primary);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    color: var(--text-primary);
    font-size: 14px;
}

.coupon-input:focus {
    outline: none;
    border-color: #667eea;
}

.coupon-message {
    margin-top: 10px;
    font-size: 12px;
    padding: 8px 12px;
    border-radius: 8px;
}

.coupon-message.success {
    background: rgba(16,185,129,0.1);
    color: #10b981;
}

.coupon-message.error {
    background: rgba(239,68,68,0.1);
    color: #ef4444;
}

/* 余额卡片 */
.balance-card {
    margin: 20px 0;
    padding: 18px 24px;
    background: var(--bg-secondary);
    border-radius: 14px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 15px;
}

.balance-info {
    display: flex;
    align-items: center;
    gap: 8px;
}

.balance-amount, .final-amount {
    font-size: 20px;
    font-weight: 700;
    color: #667eea;
}

.order-amount {
    font-size: 16px;
    font-weight: 600;
    text-decoration: line-through;
    color: var(--text-muted);
}

.discount-amount {
    font-size: 16px;
    font-weight: 600;
    color: #10b981;
}

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

/* 提交按钮 */
.buy-submit-btn {
    width: 100%;
    padding: 14px;
    font-size: 16px;
    font-weight: 600;
    transition: all 0.2s;
}

.buy-submit-btn:not(:disabled):hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(102,126,234,0.4);
}

.buy-submit-btn:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.skip-renew {
    margin-top: 20px;
}

.btn-link {
    background: transparent;
    color: var(--text-secondary);
    box-shadow: none;
}

.btn-link:hover {
    color: #667eea;
    background: transparent;
    transform: none;
}

.text-center {
    text-align: center;
}

/* 响应式 */
@media (max-width: 640px) {
    .buy-card {
        padding: 20px;
    }
    
    .packages-grid {
        grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
        gap: 12px;
    }
    
    .package-card {
        padding: 14px 10px;
    }
    
    .balance-card {
        flex-direction: column;
        align-items: stretch;
        text-align: center;
    }
    
    .balance-info {
        justify-content: space-between;
    }
}
</style>

<script>
    let selectedPackageId = null;
    let selectedPackagePrice = 0;
    let selectedPackageName = '';
    let currentCouponValid = false;
    let currentDiscount = 0;
    let currentFinalPrice = 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 = 'block';
            
            // 更新价格显示
            updatePriceDisplay(price, 0);
            
            const buyBtn = document.getElementById('buyBtn');
            buyBtn.disabled = false;
            buyBtn.innerText = '<?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;
        currentFinalPrice = finalPrice;
        
        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) {
                const buyBtn = document.getElementById('buyBtn');
                buyBtn.innerText = '<?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');
        msgDiv.innerHTML = type === 'success' ? '✅ ' + msg : '❌ ' + msg;
        msgDiv.className = 'coupon-message ' + type;
        msgDiv.style.display = 'block';
        
        // 3秒后自动隐藏
        setTimeout(() => {
            msgDiv.style.opacity = '0';
            setTimeout(() => {
                msgDiv.style.display = 'none';
                msgDiv.style.opacity = '1';
            }, 300);
        }, 3000);
    }
    
    // AJAX 验证优惠码
    function validateCouponCode(code) {
        if (!selectedPackageId) {
            showCouponMessage('请先选择套餐', 'error');
            return;
        }
        
        // 显示加载状态
        const checkBtn = document.getElementById('check_coupon_btn');
        const originalText = checkBtn.innerText;
        checkBtn.disabled = true;
        checkBtn.innerText = '验证中...';
        
        // 发送 AJAX 请求
        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.innerText = originalText;
            
            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.innerText = originalText;
            showCouponMessage('网络错误，请重试', 'error');
            console.error('Error:', 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;
    const buyForm = document.getElementById('buyForm');
    if (buyForm) {
        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> 处理中...';
        });
    }
    
    // 页面加载完成后的初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 如果有预设的优惠码，自动验证
        const presetCode = document.getElementById('coupon_code').value;
        if (presetCode && selectedPackageId) {
            validateCouponCode(presetCode);
        }
    });
</script>
<?php include 'footer.php'; ?>