<?php
define('IN_ADMIN', true);
include("../includes/common.php");
$title='邮箱配置 - 彩虹外链网盘管理中心';

$emailVerify = new \lib\EmailVerify();

if($_SERVER['REQUEST_METHOD'] == 'POST'){
    @header('Content-Type: application/json; charset=UTF-8');
    
    if(!checkRefererHost())exit(json_encode(['code'=>-1, 'msg'=>'请求来源非法']));
    
    $action = isset($_POST['action'])?$_POST['action']:'';
    
    switch($action){
        case 'save_config':
            $smtp_server = trim($_POST['smtp_server']);
            $smtp_port = intval($_POST['smtp_port']);
            $smtp_user = trim($_POST['smtp_user']);
            $smtp_pass = trim($_POST['smtp_pass']);
            $smtp_secure = trim($_POST['smtp_secure']);
            $from_email = trim($_POST['from_email']);
            $from_name = trim($_POST['from_name']);
            $is_enabled = isset($_POST['is_enabled'])?1:0;
            
            if(empty($smtp_server) || empty($smtp_user) || empty($smtp_pass) || empty($from_email)){
                exit(json_encode(['code'=>-1, 'msg'=>'请填写完整配置信息']));
            }
            
            if($smtp_port <= 0 || $smtp_port > 65535){
                exit(json_encode(['code'=>-1, 'msg'=>'SMTP端口不正确']));
            }
            
            $result = $DB->exec(
                "UPDATE pre_email_config SET 
                    smtp_server=:smtp_server,
                    smtp_port=:smtp_port,
                    smtp_user=:smtp_user,
                    smtp_pass=:smtp_pass,
                    smtp_secure=:smtp_secure,
                    from_email=:from_email,
                    from_name=:from_name,
                    is_enabled=:is_enabled,
                    updated_at=NOW()
                WHERE id=1",
                [
                    ':smtp_server' => $smtp_server,
                    ':smtp_port' => $smtp_port,
                    ':smtp_user' => $smtp_user,
                    ':smtp_pass' => $smtp_pass,
                    ':smtp_secure' => $smtp_secure,
                    ':from_email' => $from_email,
                    ':from_name' => $from_name,
                    ':is_enabled' => $is_enabled
                ]
            );
            
            if($result !== false){
                exit(json_encode(['code'=>0, 'msg'=>'配置保存成功']));
            } else {
                exit(json_encode(['code'=>-1, 'msg'=>'配置保存失败']));
            }
            break;
            
        case 'test_email':
            $test_email = trim($_POST['test_email']);
            
            if(empty($test_email) || !filter_var($test_email, FILTER_VALIDATE_EMAIL)){
                exit(json_encode(['code'=>-1, 'msg'=>'请输入正确的测试邮箱地址']));
            }
            
            $result = $emailVerify->sendCode($test_email, 'bind');
            exit(json_encode($result));
            break;
            
        case 'cleanup_codes':
            $days = intval($_POST['days']);
            if($days < 1) $days = 7;
            
            $result = $emailVerify->cleanupExpiredCodes($days);
            exit(json_encode(['code'=>0, 'msg'=>'已清理 '.$result.' 条过期记录']));
            break;
    }
}

include './head.php';
if($islogin==1){}else exit("<script language='javascript'>window.location.href='./login.php';</script>");

// 获取配置
$config = $DB->getRow("SELECT * FROM pre_email_config WHERE id=1 LIMIT 1");
if(!$config){
    $DB->exec("INSERT INTO pre_email_config (id, smtp_server, smtp_port, smtp_user, smtp_pass, smtp_secure, from_email, from_name, is_enabled, updated_at) 
               VALUES (1, 'smtp.qq.com', 587, '', '', 'tls', '', '彩虹外链网盘', 0, NOW())");
    $config = $DB->getRow("SELECT * FROM pre_email_config WHERE id=1 LIMIT 1");
}

// 获取验证码统计
$stats = [
    'total' => $DB->getColumn("SELECT COUNT(*) FROM pre_email_verify"),
    'used' => $DB->getColumn("SELECT COUNT(*) FROM pre_email_verify WHERE is_used=1"),
    'unused' => $DB->getColumn("SELECT COUNT(*) FROM pre_email_verify WHERE is_used=0"),
    'expired' => $DB->getColumn("SELECT COUNT(*) FROM pre_email_verify WHERE expire_at < NOW() AND is_used=0"),
];
?>
<link rel="stylesheet" href="./assets/css/email_config.css">

<div class="main-content">
    <div class="page-header">
        <h1 class="page-title"><i class="fa fa-envelope"></i> 邮箱配置</h1>
        <p class="page-desc">配置邮件发送服务，用于用户注册、找回密码等功能的邮箱验证</p>
    </div>

    <div class="content-grid">
        <!-- 配置表单 -->
        <div class="config-section">
            <div class="section-header">
                <h2><i class="fa fa-cog"></i> SMTP配置</h2>
            </div>
            <form id="emailConfigForm">
                <div class="form-group">
                    <label>SMTP服务器</label>
                    <input type="text" name="smtp_server" value="<?php echo htmlspecialchars($config['smtp_server']); ?>" placeholder="smtp.qq.com">
                    <span class="help-text">QQ邮箱为 smtp.qq.com，163邮箱为 smtp.163.com</span>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label>SMTP端口</label>
                        <input type="number" name="smtp_port" value="<?php echo htmlspecialchars($config['smtp_port']); ?>" placeholder="587">
                        <span class="help-text">TLS: 587, SSL: 465</span>
                    </div>
                    <div class="form-group">
                        <label>加密方式</label>
                        <select name="smtp_secure">
                            <option value="tls" <?php echo $config['smtp_secure']=='tls'?'selected':''; ?>>TLS</option>
                            <option value="ssl" <?php echo $config['smtp_secure']=='ssl'?'selected':''; ?>>SSL</option>
                            <option value="none" <?php echo $config['smtp_secure']=='none'?'selected':''; ?>>无加密</option>
                        </select>
                    </div>
                </div>
                
                <div class="form-group">
                    <label>SMTP用户名</label>
                    <input type="email" name="smtp_user" value="<?php echo htmlspecialchars($config['smtp_user']); ?>" placeholder="your-email@qq.com">
                    <span class="help-text">通常是完整的邮箱地址</span>
                </div>
                
                <div class="form-group">
                    <label>SMTP密码/授权码</label>
                    <input type="password" name="smtp_pass" value="<?php echo htmlspecialchars($config['smtp_pass']); ?>" placeholder="请输入SMTP密码或授权码">
                    <span class="help-text">QQ邮箱需要使用授权码，不是QQ密码</span>
                </div>
                
                <div class="form-group">
                    <label>发件人邮箱</label>
                    <input type="email" name="from_email" value="<?php echo htmlspecialchars($config['from_email']); ?>" placeholder="noreply@example.com">
                    <span class="help-text">实际发送邮件的邮箱地址</span>
                </div>
                
                <div class="form-group">
                    <label>发件人名称</label>
                    <input type="text" name="from_name" value="<?php echo htmlspecialchars($config['from_name']); ?>" placeholder="彩虹外链网盘">
                    <span class="help-text">邮件中显示的发件人名称</span>
                </div>
                
                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="is_enabled" value="1" <?php echo $config['is_enabled']==1?'checked':''; ?>>
                        <span>启用邮件功能</span>
                    </label>
                </div>
                
                <div class="form-actions">
                    <button type="submit" class="btn-save"><i class="fa fa-save"></i> 保存配置</button>
                </div>
            </form>
        </div>

        <!-- 测试和统计 -->
        <div class="sidebar">
            <!-- 状态卡片 -->
            <div class="status-card <?php echo $config['is_enabled']==1?'enabled':'disabled'; ?>">
                <div class="status-icon">
                    <i class="fa <?php echo $config['is_enabled']==1?'fa-check-circle':'fa-times-circle'; ?>"></i>
                </div>
                <div class="status-info">
                    <div class="status-title">邮件功能</div>
                    <div class="status-text"><?php echo $config['is_enabled']==1?'已启用':'已禁用'; ?></div>
                </div>
            </div>

            <!-- 测试发送 -->
            <div class="test-card">
                <div class="section-header">
                    <h3><i class="fa fa-paper-plane"></i> 测试发送</h3>
                </div>
                <form id="testForm">
                    <div class="form-group">
                        <input type="email" name="test_email" placeholder="输入测试邮箱地址">
                    </div>
                    <button type="submit" class="btn-test"><i class="fa fa-send"></i> 发送测试邮件</button>
                </form>
            </div>

            <!-- 验证码统计 -->
            <div class="stats-card">
                <div class="section-header">
                    <h3><i class="fa fa-bar-chart"></i> 验证码统计</h3>
                </div>
                <div class="stats-grid">
                    <div class="stat-item">
                        <div class="stat-value"><?php echo $stats['total']; ?></div>
                        <div class="stat-label">总记录</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value"><?php echo $stats['used']; ?></div>
                        <div class="stat-label">已使用</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value"><?php echo $stats['unused']; ?></div>
                        <div class="stat-label">未使用</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value"><?php echo $stats['expired']; ?></div>
                        <div class="stat-label">已过期</div>
                    </div>
                </div>
                <div class="cleanup-form">
                    <select id="cleanupDays">
                        <option value="7">7天前</option>
                        <option value="30">30天前</option>
                        <option value="90">90天前</option>
                    </select>
                    <button type="button" onclick="cleanupCodes()"><i class="fa fa-trash"></i> 清理过期记录</button>
                </div>
            </div>

            <!-- 使用说明 -->
            <div class="guide-card">
                <div class="section-header">
                    <h3><i class="fa fa-question-circle"></i> 使用说明</h3>
                </div>
                <div class="guide-content">
                    <h4>QQ邮箱配置步骤：</h4>
                    <ol>
                        <li>登录QQ邮箱网页版</li>
                        <li>进入【设置】→【账户】</li>
                        <li>找到【POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务】</li>
                        <li>开启 <strong>SMTP服务</strong></li>
                        <li>点击【生成授权码】</li>
                        <li>将授权码填入上方【SMTP密码/授权码】</li>
                    </ol>
                    <div class="warning-box">
                        <i class="fa fa-exclamation-triangle"></i>
                        <div>
                            <strong>注意事项：</strong><br>
                            • 授权码不是QQ密码<br>
                            • 授权码只能生成一次，请妥善保存<br>
                            • 如果更换邮箱需要重新配置
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://s4.zstatic.net/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://s4.zstatic.net/ajax/libs/layer/2.3/layer.js"></script>
<script>
$(document).ready(function(){
    $('#emailConfigForm').on('submit', function(e){
        e.preventDefault();
        var submitBtn = $(this).find('button[type="submit"]');
        var originalText = submitBtn.html();
        
        submitBtn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> 保存中...');
        
        $.ajax({
            type: 'POST',
            url: 'set_email.php',
            data: $(this).serialize() + '&action=save_config',
            dataType: 'json',
            success: function(response) {
                if(response.code === 0){
                    layer.msg(response.msg, {icon: 1});
                } else {
                    layer.alert(response.msg, {icon: 2});
                }
                submitBtn.prop('disabled', false).html(originalText);
            },
            error: function() {
                layer.alert('网络错误，请稍后重试', {icon: 2});
                submitBtn.prop('disabled', false).html(originalText);
            }
        });
    });
    
    $('#testForm').on('submit', function(e){
        e.preventDefault();
        var testEmail = $(this).find('input[name="test_email"]').val();
        
        if(!testEmail){
            layer.msg('请输入测试邮箱地址', {icon: 2});
            return;
        }
        
        var submitBtn = $(this).find('button[type="submit"]');
        var originalText = submitBtn.html();
        
        submitBtn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> 发送中...');
        
        $.ajax({
            type: 'POST',
            url: 'set_email.php',
            data: {action: 'test_email', test_email: testEmail},
            dataType: 'json',
            success: function(response) {
                if(response.code === 0){
                    layer.msg(response.msg, {icon: 1});
                } else {
                    layer.alert('发送失败: ' + response.msg, {icon: 2});
                }
                submitBtn.prop('disabled', false).html(originalText);
            },
            error: function() {
                layer.alert('网络错误，请稍后重试', {icon: 2});
                submitBtn.prop('disabled', false).html(originalText);
            }
        });
    });
});

function cleanupCodes() {
    var days = $('#cleanupDays').val();
    
    layer.confirm('确定要清理 '+days+' 天前的过期验证码记录吗？', {icon: 3, title:'提示'}, function(index){
        $.ajax({
            type: 'POST',
            url: 'set_email.php',
            data: {action: 'cleanup_codes', days: days},
            dataType: 'json',
            success: function(response) {
                if(response.code === 0){
                    layer.msg(response.msg, {icon: 1}, function(){
                        location.reload();
                    });
                } else {
                    layer.alert('清理失败: ' + response.msg, {icon: 2});
                }
            },
            error: function() {
                layer.alert('网络错误，请稍后重试', {icon: 2});
            }
        });
        layer.close(index);
    });
}
</script>

<?php include './foot.php'; ?>
