<?php
require_once __DIR__ . '/../MPHX/common.php';

// 禁用缓存
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

// 如果已经验证过，跳转到首页
if (isset($_SESSION['admin_email_verified']) && $_SESSION['admin_email_verified'] === true) {
    header('Location: index.php');
    exit;
}

// 检查是否开启了邮箱验证
if (!isset($conf['admin_email_verify']) || $conf['admin_email_verify'] !== 'true') {
    $_SESSION['admin_email_verified'] = true;
    header('Location: index.php');
    exit;
}

// 检查是否设置了管理员邮箱
if (empty($conf['admin_email'])) {
    $_SESSION['admin_email_verified'] = true;
    header('Location: index.php');
    exit;
}

$admin_email = $conf['admin_email'];
$email_masked = substr($admin_email, 0, 3) . '***' . substr($admin_email, strpos($admin_email, '@'));

?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <title>安全验证 - 宝塔主机管理系统</title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css?v=<?php echo time(); ?>">
    <link rel="stylesheet" href="/static/css/all.min.css?v=<?php echo time(); ?>">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', Arial, sans-serif;
            background: #f5f7fa;
            color: #333;
            line-height: 1.5;
            font-size: 13px;
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .verify-box {
            background: #fff;
            padding: 32px;
            border-radius: 6px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            width: 380px;
            border: 1px solid #e8eaed;
        }
        
        .verify-header {
            text-align: center;
            margin-bottom: 24px;
        }
        
        .verify-header h2 {
            color: #202124;
            font-size: 20px;
            font-weight: 500;
            margin-bottom: 6px;
        }
        
        .verify-header p {
            color: #5f6368;
            font-size: 13px;
            margin: 0;
        }
        
        .verify-header i {
            color: #1a73e8;
            font-size: 32px;
            margin-bottom: 12px;
            display: block;
        }
        
        /* 邮箱信息 */
        .email-info {
            background: #f8f9fa;
            border-radius: 4px;
            padding: 12px 16px;
            margin-bottom: 16px;
            text-align: center;
        }
        
        .email-label {
            font-size: 12px;
            color: #5f6368;
            margin-bottom: 4px;
        }
        
        .email-value {
            font-size: 14px;
            font-weight: 500;
            color: #202124;
            word-break: break-all;
        }
        
        /* 提示信息 */
        .alert {
            padding: 10px 12px;
            border-radius: 4px;
            margin-bottom: 16px;
            font-size: 12px;
            display: none;
            text-align: left;
        }
        
        .alert-success {
            background: #e6f4ea;
            color: #188038;
            border: 1px solid #34a853;
            display: block;
        }
        
        .alert-error {
            background: #fce8e8;
            color: #d93025;
            border: 1px solid #ea4335;
            display: block;
        }
        
        /* 表单样式 */
        .form-group {
            margin-bottom: 16px;
        }
        
        .form-group label {
            font-weight: 500;
            color: #202124;
            font-size: 12px;
            margin-bottom: 5px;
            display: block;
        }
        
        .form-control {
            border-radius: 4px;
            border: 1px solid #dadce0;
            padding: 10px 12px;
            font-size: 13px;
            transition: border-color 0.2s;
            text-align: center;
            letter-spacing: 4px;
        }
        
        .form-control:focus {
            border-color: #1a73e8;
            outline: none;
            box-shadow: 0 0 0 2px rgba(26, 115, 232, 0.1);
        }
        
        .form-control::placeholder {
            color: #9aa0a6;
            letter-spacing: 2px;
        }
        
        /* 按钮样式 */
        .btn {
            border: none;
            padding: 10px;
            font-size: 13px;
            font-weight: 500;
            border-radius: 4px;
            width: 100%;
            transition: background 0.2s;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }
        
        .btn-primary {
            background: #1a73e8;
            color: #fff;
            margin-bottom: 12px;
        }
        
        .btn-primary:hover {
            background: #1557b0;
        }
        
        .btn-primary:disabled {
            opacity: 0.7;
            cursor: not-allowed;
        }
        
        .btn-secondary {
            background: #f1f3f4;
            color: #5f6368;
        }
        
        .btn-secondary:hover {
            background: #e8eaed;
        }
        
        .btn-secondary:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        /* 加载动画 */
        .btn-loading {
            position: relative;
            pointer-events: none;
            color: transparent !important;
        }
        
        .btn-loading::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 16px;
            height: 16px;
            margin: -8px 0 0 -8px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        /* 底部链接 */
        .text-center {
            text-align: center;
        }
        
        .mt-3 {
            margin-top: 16px;
        }
        
        .text-muted {
            color: #5f6368;
            font-size: 12px;
            text-decoration: none;
            transition: color 0.2s;
        }
        
        .text-muted:hover {
            color: #1a73e8;
        }
        
        /* 响应式适配 */
        @media (max-width: 480px) {
            body {
                padding: 16px;
            }
            
            .verify-box {
                width: 100%;
                max-width: 380px;
                padding: 28px 24px;
            }
            
            .verify-header i {
                font-size: 28px;
            }
            
            .verify-header h2 {
                font-size: 18px;
            }
        }
    </style>
</head>
<body>
    <div class="verify-box">
        <!-- 头部 -->
        <div class="verify-header">
            <i class="fas fa-shield-alt"></i>
            <h2>安全验证</h2>
            <p>为了保护您的账户安全，请完成邮箱验证</p>
        </div>
        
        <!-- 邮箱信息 -->
        <div class="email-info">
            <div class="email-label">验证码将发送至</div>
            <div class="email-value"><?php echo $email_masked; ?></div>
        </div>
        
        <!-- 提示信息 -->
        <div id="alertBox" class="alert"></div>
        
        <!-- 验证码输入 -->
        <div class="form-group">
            <label for="verifyCode">验证码</label>
            <input type="text" id="verifyCode" class="form-control" placeholder="000000" maxlength="6" inputmode="numeric" pattern="[0-9]*">
        </div>
        
        <!-- 验证按钮 -->
        <button type="button" class="btn btn-primary" onclick="verifyCode()">
            <i class="fas fa-check"></i> 验证
        </button>
        
        <!-- 发送验证码按钮 -->
        <button type="button" id="sendBtn" class="btn btn-secondary" onclick="sendVerifyCode()">
            <i class="fas fa-paper-plane"></i> 发送验证码
        </button>
        
        <!-- 底部链接 -->
        <div class="text-center mt-3">
            <a href="login.php" class="text-muted">
                <i class="fas fa-arrow-left"></i> 返回登录
            </a>
        </div>
    </div>
    
    <script src="/static/js/jquery.min.js"></script>
    <script>
        let countdown = 0;
        let countdownTimer = null;
        
        // 页面加载完成后检查是否已经发送过验证码
        $(document).ready(function() {
            const lastSendTime = sessionStorage.getItem('verify_code_sent_time');
            const now = Date.now();
            
            if (lastSendTime && (now - parseInt(lastSendTime)) < 60000) {
                const elapsed = Math.floor((now - parseInt(lastSendTime)) / 1000);
                countdown = 60 - elapsed;
                if (countdown > 0) {
                    startCountdownFrom(countdown);
                }
            } else {
                sendVerifyCode();
            }
            $('#verifyCode').focus();
        });
        
        // 回车键提交
        $('#verifyCode').on('keypress', function(e) {
            if (e.which === 13) {
                verifyCode();
            }
        });
        
        // 只允许输入数字
        $('#verifyCode').on('input', function() {
            this.value = this.value.replace(/[^0-9]/g, '');
        });
        
        function showAlert(message, type) {
            const alertBox = $('#alertBox');
            alertBox.removeClass('alert-success alert-error').addClass('alert-' + type);
            alertBox.text(message).show();
            if (type === 'success') {
                setTimeout(() => {
                    alertBox.hide();
                }, 5000);
            }
        }
        
        function hideAlert() {
            $('#alertBox').hide();
        }
        
        function sendVerifyCode() {
            if (countdown > 0) return;
            
            const btn = $('#sendBtn');
            const originalText = btn.html();
            btn.addClass('btn-loading').prop('disabled', true);
            hideAlert();
            
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {egn: 'send_admin_verify_code'},
                dataType: 'json',
                success: function(data) {
                    btn.removeClass('btn-loading').prop('disabled', false);
                    if (data.code === 'success') {
                        showAlert('验证码已发送，请查收邮件', 'success');
                        startCountdown();
                        $('#verifyCode').focus();
                    } else {
                        showAlert(data.message || '发送失败，请重试', 'error');
                        btn.html(originalText);
                    }
                },
                error: function() {
                    btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                    showAlert('网络错误，请检查网络连接', 'error');
                }
            });
        }
        
        function startCountdown() {
            countdown = 60;
            sessionStorage.setItem('verify_code_sent_time', Date.now());
            startCountdownFrom(countdown);
        }
        
        function startCountdownFrom(seconds) {
            countdown = seconds;
            const btn = $('#sendBtn');
            btn.prop('disabled', true).removeClass('btn-loading');
            
            countdownTimer = setInterval(function() {
                countdown--;
                if (countdown <= 0) {
                    clearInterval(countdownTimer);
                    btn.html('<i class="fas fa-paper-plane"></i> 重新发送').prop('disabled', false);
                    sessionStorage.removeItem('verify_code_sent_time');
                } else {
                    btn.html('<i class="fas fa-clock"></i> ' + countdown + '秒后重试');
                }
            }, 1000);
        }
        
        function verifyCode() {
            const code = $('#verifyCode').val().trim();
            
            if (!code || code.length !== 6) {
                showAlert('请输入6位验证码', 'error');
                $('#verifyCode').focus();
                return;
            }
            
            const btn = $('.btn-primary');
            const originalText = btn.html();
            btn.addClass('btn-loading').prop('disabled', true);
            hideAlert();
            
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {
                    egn: 'verify_admin_code',
                    code: code
                },
                dataType: 'json',
                success: function(data) {
                    btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                    if (data.code === 'success') {
                        showAlert('验证成功，正在跳转...', 'success');
                        setTimeout(function() {
                            window.location.href = 'index.php';
                        }, 800);
                    } else {
                        showAlert(data.message || '验证失败', 'error');
                        $('#verifyCode').select().focus();
                    }
                },
                error: function() {
                    btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                    showAlert('网络错误，请重试', 'error');
                }
            });
        }
    </script>
</body>
</html>
