<?php
ob_start();
requireAdmin();

// 仅超级管理员可访问
$user = currentUser();
if ($user['role'] !== 'admin') {
    header('Location: /admin.php');
    exit;
}

$message = '';
$error = '';

// 保存配置
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_config'])) {
    updateSiteConfig('smtp_host', trim($_POST['smtp_host']));
    updateSiteConfig('smtp_port', intval($_POST['smtp_port']));
    updateSiteConfig('smtp_user', trim($_POST['smtp_user']));
    updateSiteConfig('smtp_pass', trim($_POST['smtp_pass']));
    updateSiteConfig('smtp_from', trim($_POST['smtp_from']));
    updateSiteConfig('smtp_name', trim($_POST['smtp_name']));
    $message = '邮件配置已保存';
}

// 发送测试邮件
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['test_mail'])) {
    $test_email = trim($_POST['test_email']);
    if (empty($test_email)) {
        $error = '请输入测试邮箱';
    } else {
        require_once __DIR__ . '/../../includes/mail_helper.php';
        $subject = '邮件测试 - ' . (getSiteConfig('site_name') ?? '麟泓授权系统');
        $content = '
        <html>
        <head><style>
            body { font-family: Arial, sans-serif; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: linear-gradient(135deg, #667eea, #764ba2); color: white; padding: 20px; text-align: center; border-radius: 10px 10px 0 0; }
            .content { background: #f9fafb; padding: 20px; border: 1px solid #e5e7eb; }
            .footer { background: #f3f4f6; padding: 15px; text-align: center; font-size: 12px; color: #6b7280; border-radius: 0 0 10px 10px; }
        </style></head>
        <body>
        <div class="container">
            <div class="header">
                <h2>📧 邮件测试</h2>
            </div>
            <div class="content">
                <p>您好！</p>
                <p>这是一封来自 <strong>' . (getSiteConfig('site_name') ?? '麟泓授权系统') . '</strong> 的测试邮件。</p>
                <p>如果您收到此邮件，说明邮件配置正确，可以正常发送通知了。</p>
                <p>发送时间：' . date('Y-m-d H:i:s') . '</p>
            </div>
            <div class="footer">
                <p>此邮件由系统自动发送，请勿回复</p>
            </div>
        </div>
        </body>
        </html>
        ';
        
        if (sendMail($test_email, $subject, $content)) {
            $message = "测试邮件已发送至 {$test_email}，请查收";
        } else {
            $error = "测试邮件发送失败，请检查SMTP配置";
        }
    }
}

// 获取当前配置
$smtp_host = getSiteConfig('smtp_host') ?? '';
$smtp_port = getSiteConfig('smtp_port') ?? '465';
$smtp_user = getSiteConfig('smtp_user') ?? '';
$smtp_pass = getSiteConfig('smtp_pass') ?? '';
$smtp_from = getSiteConfig('smtp_from') ?? '';
$smtp_name = getSiteConfig('smtp_name') ?? '';
?>

<div class="mail-config-container">
    <div class="page-header">
        <h2>
            <img src="https://api.iconify.design/mdi:email.svg?color=%23667eea" width="26" height="26" style="vertical-align: middle; margin-right: 10px;" alt="">
            邮件配置
        </h2>
        <p class="page-desc">配置SMTP服务，用于发送购买确认、登录提醒等邮件</p>
    </div>
    
    <?php if ($message): ?>
        <div class="alert alert-success">
            <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="20" height="20" style="margin-right: 8px;" alt="">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>
    
    <?php if ($error): ?>
        <div class="alert alert-error">
            <img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23ef4444" width="20" height="20" style="margin-right: 8px;" alt="">
            <?php echo $error; ?>
        </div>
    <?php endif; ?>
    
    <div class="form-card">
        <!-- SMTP 配置表单 -->
        <form method="POST">
            <div class="section-title">
                <img src="https://api.iconify.design/mdi:server.svg?color=%23667eea" width="18" height="18" style="margin-right: 8px;" alt="">
                SMTP 服务器设置
            </div>
            
            <div class="form-row">
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:server-network.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        SMTP服务器
                    </label>
                    <input type="text" name="smtp_host" value="<?php echo htmlspecialchars($smtp_host); ?>" placeholder="smtp.qq.com" required>
                    <small>例如：smtp.qq.com、smtp.163.com</small>
                </div>
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:connection.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        SMTP端口
                    </label>
                    <input type="number" name="smtp_port" value="<?php echo $smtp_port; ?>" placeholder="465" required>
                    <small>通常使用 465（SSL）</small>
                </div>
            </div>
            
            <div class="form-group">
                <label>
                    <img src="https://api.iconify.design/mdi:email.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                    发件邮箱
                </label>
                <input type="email" name="smtp_user" value="<?php echo htmlspecialchars($smtp_user); ?>" placeholder="your@email.com" required>
                <small>完整的邮箱地址，用于登录SMTP</small>
            </div>
            
            <div class="form-group">
                <label>
                    <img src="https://api.iconify.design/mdi:key.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                    授权码 / 密码
                </label>
                <input type="password" name="smtp_pass" value="<?php echo htmlspecialchars($smtp_pass); ?>" placeholder="邮箱授权码" required>
                <small>不是登录密码，是SMTP授权码（QQ邮箱需要生成授权码）</small>
            </div>
            
            <div class="form-row">
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:email-send.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        发件人地址（可选）
                    </label>
                    <input type="email" name="smtp_from" value="<?php echo htmlspecialchars($smtp_from); ?>" placeholder="留空则使用发件邮箱">
                    <small>收件人看到的发件地址</small>
                </div>
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:account.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        发件人名称
                    </label>
                    <input type="text" name="smtp_name" value="<?php echo htmlspecialchars($smtp_name); ?>" placeholder="例如：麟泓授权系统">
                    <small>收件人看到的发件人名称</small>
                </div>
            </div>
            
            <button type="submit" name="save_config" class="btn btn-primary">
                <img src="https://api.iconify.design/mdi:content-save.svg?color=white" width="18" height="18" style="margin-right: 6px;" alt="">
                保存配置
            </button>
        </form>
        
        <div class="divider"></div>
        
        <!-- 测试邮件 -->
        <form method="POST">
            <div class="section-title">
                <img src="https://api.iconify.design/mdi:email-send.svg?color=%23667eea" width="18" height="18" style="margin-right: 8px;" alt="">
                发送测试邮件
            </div>
            
            <div class="form-row" style="align-items: flex-end;">
                <div class="form-group" style="flex: 1;">
                    <label>
                        <img src="https://api.iconify.design/mdi:email.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        接收测试邮件的邮箱
                    </label>
                    <input type="email" name="test_email" placeholder="your@email.com" required>
                </div>
                <div class="form-group">
                    <button type="submit" name="test_mail" class="btn btn-secondary">
                        <img src="https://api.iconify.design/mdi:send.svg?color=currentColor" width="16" height="16" style="margin-right: 4px;" alt="">
                        发送测试邮件
                    </button>
                </div>
            </div>
        </form>
        
        <div class="divider"></div>
        
        <!-- 使用说明 -->
        <div class="section-title">
            <img src="https://api.iconify.design/mdi:information.svg?color=%23667eea" width="18" height="18" style="margin-right: 8px;" alt="">
            常见邮箱SMTP配置
        </div>
        
        <div class="table-wrapper">
            <table class="info-table">
                <thead>
                    <tr>
                        <th>邮箱类型</th>
                        <th>SMTP服务器</th>
                        <th>端口</th>
                        <th>说明</th>
                    </tr>
                </thead>
                <tbody>
                    <tr><td>QQ邮箱</td><td>smtp.qq.com</td><td>465</td><td>需要生成授权码</td></tr>
                    <tr><td>163邮箱</td><td>smtp.163.com</td><td>465</td><td>需要开启客户端授权</td></tr>
                    <tr><td>腾讯企业邮</td><td>smtp.exmail.qq.com</td><td>465</td><td>使用企业邮箱密码</td></tr>
                    <tr><td>阿里企业邮</td><td>smtp.mxhichina.com</td><td>465</td><td>使用企业邮箱密码</td></tr>
                    <tr><td>Gmail</td><td>smtp.gmail.com</td><td>465</td><td>需要开启两步验证+应用专用密码</td></tr>
                </tbody>
            </table>
        </div>
        
        <div class="tips-box">
            <div class="tips-header">
                <img src="https://api.iconify.design/mdi:lightbulb.svg?color=%23f59e0b" width="18" height="18" style="margin-right: 6px;" alt="">
                温馨提示
            </div>
            <ul>
                <li>QQ邮箱需要登录网页版，进入设置 → 账户 → 开启POP3/SMTP服务 → 获取授权码</li>
                <li>授权码作为密码填入，不是QQ登录密码</li>
                <li>保存配置后，建议发送测试邮件验证是否正常</li>
                <li>配置完成后，用户购买服务、登录提醒等会自动发送邮件通知</li>
            </ul>
        </div>
    </div>
</div>

<style>
.mail-config-container {
    max-width: 720px;
    margin: 0 auto;
    padding: 4px;
}

.page-header {
    margin-bottom: 24px;
}
.page-header h2 {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0 0 6px;
}
.page-desc {
    color: var(--text-muted);
    font-size: 14px;
    margin-left: 36px;
}

.alert {
    display: flex;
    align-items: center;
    padding: 14px 20px;
    border-radius: 12px;
    margin-bottom: 24px;
    font-size: 14px;
}
.alert-success {
    background: #d1fae5;
    color: #065f46;
    border: 1px solid #a7f3d0;
}
.alert-error {
    background: #fef2f2;
    border: 1px solid #fecaca;
    color: #991b1b;
}

.form-card {
    background: var(--bg-primary);
    border-radius: 20px;
    padding: 32px;
    border: 1px solid var(--border-color);
    box-shadow: var(--shadow-sm);
}

.section-title {
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: 20px;
    padding-bottom: 12px;
    border-bottom: 1px solid var(--border-color);
}
.section-title:not(:first-child) {
    margin-top: 28px;
}

.form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
}

.form-group {
    margin-bottom: 22px;
}
.form-group label {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    font-weight: 500;
    font-size: 14px;
    color: var(--text-primary);
}
.form-group input {
    width: 100%;
    padding: 12px 16px;
    border: 1.5px solid var(--border-color);
    border-radius: 10px;
    font-size: 14px;
    background: var(--bg-primary);
    color: var(--text-primary);
    transition: all 0.2s;
}
.form-group input:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.form-group small {
    display: block;
    margin-top: 6px;
    font-size: 12px;
    color: var(--text-muted);
}

.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 12px 24px;
    border-radius: 10px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    border: none;
}
.btn-primary {
    background: var(--primary-color);
    color: white;
    box-shadow: 0 2px 4px rgba(102, 126, 234, 0.2);
}
.btn-primary:hover {
    background: var(--primary-hover);
    transform: translateY(-1px);
}
.btn-secondary {
    background: var(--bg-secondary);
    color: var(--text-primary);
    border: 1.5px solid var(--border-color);
}
.btn-secondary:hover {
    background: var(--border-color);
}

.divider {
    margin: 32px 0;
    border-top: 1px solid var(--border-color);
}

.table-wrapper {
    overflow-x: auto;
    margin-bottom: 24px;
}
.info-table {
    width: 100%;
    border-collapse: collapse;
}
.info-table th {
    padding: 12px 16px;
    text-align: left;
    font-weight: 600;
    font-size: 13px;
    color: var(--text-secondary);
    background: var(--bg-secondary);
    border-bottom: 1px solid var(--border-color);
}
.info-table td {
    padding: 10px 16px;
    border-bottom: 1px solid var(--border-color);
    font-size: 14px;
    color: var(--text-primary);
}
.info-table tbody tr:last-child td {
    border-bottom: none;
}

.tips-box {
    padding: 20px;
    background: var(--bg-secondary);
    border-radius: 14px;
}
.tips-header {
    display: flex;
    align-items: center;
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: 12px;
}
.tips-box ul {
    margin-left: 24px;
    color: var(--text-secondary);
    font-size: 13px;
}
.tips-box li {
    margin: 8px 0;
}

@media (max-width: 768px) {
    .form-card {
        padding: 20px;
    }
    .form-row {
        grid-template-columns: 1fr;
        gap: 0;
    }
}
</style>