<?php
require_once 'config.php';

// 如果已经登录，跳转到首页
if (isEncryptLoggedIn()) {
    header('Location: /encrypt/index.php');
    exit;
}

$error = '';
$login_method = $_GET['method'] ?? 'code'; // code=验证码登录, password=密码登录

// 处理密码登录
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $login_method === 'password') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';

    if (empty($username) || empty($password)) {
        $error = '请输入用户名和密码';
    } else {
        // 通过用户名查询用户（改为 username）
        $user = $db->fetchOne("SELECT * FROM users WHERE username = '$username'");
        
        if (!$user) {
            $error = '用户名不存在';
        } elseif ($user['status'] != 1) {
            $error = '账号已被禁用';
        } elseif (!password_verify($password, $user['password'])) {
            $error = '密码错误';
        } else {
            // 登录成功
            $_SESSION['encrypt_user_id'] = $user['id'];
            $_SESSION['encrypt_username'] = $user['username'];
            $_SESSION['encrypt_role'] = $user['role'];
            $_SESSION['encrypt_is_agent'] = $user['is_agent'];
            
            header('Location: /encrypt/index.php');
            exit;
        }
    }
}

// 处理验证码登录
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $login_method === 'code') {
    $email = trim($_POST['email'] ?? '');
    $code = trim($_POST['code'] ?? '');

    if (empty($email) || empty($code)) {
        $error = '请输入邮箱和验证码';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = '邮箱格式不正确';
    } else {
        // 验证验证码
        $record = $db->fetchOne("SELECT * FROM email_verify_codes 
                                  WHERE email = '$email' 
                                  AND code = '$code' 
                                  AND type = 'login' 
                                  AND used = 0 
                                  AND expired_at > NOW()");
        
        if (!$record) {
            $error = '验证码错误或已过期';
        } else {
            // 标记验证码已使用
            $db->query("UPDATE email_verify_codes SET used = 1 WHERE id = {$record['id']}");
            
            // 获取用户信息
            $user = $db->fetchOne("SELECT * FROM users WHERE email = '$email'");
            
            if (!$user) {
                $error = '该邮箱未注册';
            } elseif ($user['status'] != 1) {
                $error = '账号已被禁用';
            } else {
                // 登录成功
                $_SESSION['encrypt_user_id'] = $user['id'];
                $_SESSION['encrypt_username'] = $user['username'];
                $_SESSION['encrypt_role'] = $user['role'];
                $_SESSION['encrypt_is_agent'] = $user['is_agent'];
                
                header('Location: /encrypt/index.php');
                exit;
            }
        }
    }
}

// 获取公告
$announcement = getEncryptAnnouncement();
?>
<?php include 'header.php'; ?>
<div class="encrypt-container">
    <div class="login-wrapper" style="max-width: 450px; margin: 0 auto;">
        <div class="card" style="background: var(--bg-primary); border-radius: 24px; padding: 40px; border: 1px solid var(--border-color);">
            <h2 style="text-align: center; margin-bottom: 10px;">登录加密工具</h2>
            <p style="text-align: center; color: var(--text-secondary); margin-bottom: 30px;">选择您的方式登录</p>
            
            <!-- 切换标签 -->
            <div class="login-tabs" style="display: flex; margin-bottom: 30px; border-bottom: 1px solid var(--border-color);">
                <div class="login-tab <?php echo $login_method == 'code' ? 'active' : ''; ?>" data-method="code" style="flex: 1; text-align: center; padding: 12px; cursor: pointer; color: var(--text-secondary); border-bottom: 2px solid <?php echo $login_method == 'code' ? 'var(--primary-color)' : 'transparent'; ?>; <?php echo $login_method == 'code' ? 'color: var(--primary-color);' : ''; ?>">
                    验证码登录
                </div>
                <div class="login-tab <?php echo $login_method == 'password' ? 'active' : ''; ?>" data-method="password" style="flex: 1; text-align: center; padding: 12px; cursor: pointer; color: var(--text-secondary); border-bottom: 2px solid <?php echo $login_method == 'password' ? 'var(--primary-color)' : 'transparent'; ?>; <?php echo $login_method == 'password' ? 'color: var(--primary-color);' : ''; ?>">
                    密码登录
                </div>
            </div>
            
            <?php if ($announcement): ?>
                <div class="alert alert-info" style="background: rgba(59,130,246,0.1); border: 1px solid #3b82f6; border-radius: 12px; padding: 12px; margin-bottom: 20px; font-size: 13px;">
                    <?php echo $announcement; ?>
                </div>
            <?php endif; ?>
            
            <?php if ($error): ?>
                <div class="alert alert-error" style="background: rgba(239,68,68,0.1); border: 1px solid #ef4444; border-radius: 12px; padding: 12px; margin-bottom: 20px; color: #ef4444;">
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>
            
            <!-- 验证码登录表单 -->
            <form method="POST" id="codeLoginForm" style="display: <?php echo $login_method == 'code' ? 'block' : 'none'; ?>;">
                <div class="form-group" style="margin-bottom: 20px;">
                    <label style="display: block; margin-bottom: 8px; font-weight: 500;">邮箱</label>
                    <div class="code-input-group" style="display: flex; gap: 10px;">
                        <input type="email" id="email" name="email" class="form-control" style="flex: 1; padding: 12px; border-radius: 12px; border: 1px solid var(--border-color); background: var(--bg-primary);" placeholder="请输入邮箱" required>
                        <button type="button" id="sendCodeBtn" class="btn btn-secondary" style="white-space: nowrap; padding: 0 20px; border-radius: 12px;">发送验证码</button>
                    </div>
                </div>
                <div class="form-group" style="margin-bottom: 25px;">
                    <label style="display: block; margin-bottom: 8px; font-weight: 500;">验证码</label>
                    <input type="text" id="code" name="code" class="form-control" style="width: 100%; padding: 12px; border-radius: 12px; border: 1px solid var(--border-color); background: var(--bg-primary);" placeholder="请输入6位验证码" required>
                </div>
                <button type="submit" class="btn btn-primary" style="width: 100%; padding: 14px; border-radius: 12px; font-size: 16px; font-weight: 600;">验证码登录</button>
            </form>
            
            <!-- 密码登录表单 -->
<form method="POST" id="passwordLoginForm" action="?method=password" style="display: <?php echo $login_method == 'password' ? 'block' : 'none'; ?>;">
    <div class="form-group" style="margin-bottom: 20px;">
        <label style="display: block; margin-bottom: 8px; font-weight: 500;">用户名</label>
        <input type="text" name="username" class="form-control" style="width: 100%; padding: 12px; border-radius: 12px; border: 1px solid var(--border-color); background: var(--bg-primary);" placeholder="请输入用户名" required>
    </div>
    <div class="form-group" style="margin-bottom: 25px;">
        <label style="display: block; margin-bottom: 8px; font-weight: 500;">密码</label>
        <input type="password" name="password" class="form-control" style="width: 100%; padding: 12px; border-radius: 12px; border: 1px solid var(--border-color); background: var(--bg-primary);" placeholder="请输入密码" required>
    </div>
    <button type="submit" class="btn btn-primary" style="width: 100%; padding: 14px; border-radius: 12px; font-size: 16px; font-weight: 600;">密码登录</button>
</form>
            


            <div style="text-align: center; margin-top: 25px;">
                <p style="color: var(--text-secondary); font-size: 13px;">
                    还没有账号？<a href="/modules/home/register.php" style="color: var(--primary-color);">立即注册</a>
                </p>
            </div>
        </div>
    </div>
</div>

<style>
/* 基础变量 - 明暗主题兼容 */
:root,
[data-theme="light"] {
    --primary-color: #667eea;
    --primary-hover: #5a67d8;
    --danger-color: #ef4444;
    --success-color: #10b981;
    --warning-color: #f59e0b;
    --bg-primary: #ffffff;
    --bg-secondary: #f9fafb;
    --text-primary: #1f2937;
    --text-secondary: #6b7280;
    --text-muted: #9ca3af;
    --border-color: #e5e7eb;
    --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
    --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
    --radius-sm: 8px;
    --radius-md: 12px;
    --radius-lg: 20px;
}

/* 深色主题变量 */
[data-theme="dark"] {
    --primary-color: #7b8cf5;
    --primary-hover: #8f9ef7;
    --danger-color: #f87171;
    --success-color: #34d399;
    --warning-color: #fbbf24;
    --bg-primary: #1f2937;
    --bg-secondary: #374151;
    --text-primary: #f9fafb;
    --text-secondary: #d1d5db;
    --text-muted: #9ca3af;
    --border-color: #4b5563;
    --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.3);
    --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.4);
    --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.5);
}

.encrypt-container {
    max-width: 450px;
    margin: 0 auto;
    padding: 40px 20px;
}

.card {
    background: var(--bg-primary) !important;
    border-radius: 24px;
    padding: 40px;
    border: 1px solid var(--border-color);
    box-shadow: var(--shadow-md);
}

.card h2 {
    color: var(--text-primary) !important;
}

.card p {
    color: var(--text-secondary) !important;
}

/* 切换标签 */
.login-tabs {
    display: flex;
    margin-bottom: 30px;
    border-bottom: 1px solid var(--border-color);
}

.login-tab {
    flex: 1;
    text-align: center;
    padding: 12px;
    cursor: pointer;
    color: var(--text-secondary) !important;
    border-bottom: 2px solid transparent;
    transition: all 0.2s;
    font-weight: 500;
}

.login-tab.active {
    color: var(--primary-color) !important;
    border-bottom-color: var(--primary-color);
}

.login-tab:hover {
    color: var(--primary-color) !important;
}

/* 表单 */
.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: var(--text-primary) !important;
}

.form-control {
    width: 100%;
    padding: 12px 16px;
    border-radius: 12px;
    border: 1.5px solid var(--border-color);
    background: var(--bg-primary) !important;
    color: var(--text-primary) !important;
    font-size: 14px;
    transition: all 0.2s;
    box-sizing: border-box;
}

.form-control:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-control::placeholder {
    color: var(--text-muted);
}

.code-input-group {
    display: flex;
    gap: 10px;
}

.code-input-group .form-control {
    flex: 1;
}

/* 按钮 */
.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 12px 20px;
    border-radius: 12px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    border: none;
    font-size: 14px;
}

.btn-primary {
    width: 88px;
    padding: 14px;
    border-radius: 12px;
    font-size: 16px;
    font-weight: 600;
    background: linear-gradient(135deg, #667eea, #764ba2) !important;
    color: white !important;
    border: none;
    cursor: pointer;
    transition: all 0.2s;
    height: 45px;
}

.btn-primary:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.btn-secondary {
    white-space: nowrap;
    padding: 0 20px;
    border-radius: 12px;
    background: var(--bg-secondary) !important;
    border: 1.5px solid var(--border-color) !important;
    color: var(--text-primary) !important;
    cursor: pointer;
    transition: all 0.2s;
    font-weight: 500;
}

.btn-secondary:hover {
    background: var(--border-color) !important;
}

.btn-secondary:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

/* 提示消息 */
.alert {
    border-radius: 12px;
    padding: 12px 16px;
    margin-bottom: 20px;
    font-size: 13px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.alert-info {
    background: rgba(102, 126, 234, 0.1) !important;
    border: 1px solid var(--primary-color) !important;
    color: var(--text-primary) !important;
}

.alert-error {
    background: rgba(239, 68, 68, 0.1) !important;
    border: 1px solid #ef4444 !important;
    color: #ef4444 !important;
}

[data-theme="dark"] .alert-error {
    background: rgba(239, 68, 68, 0.15) !important;
    color: #f87171 !important;
}

/* 链接 */
.card a {
    color: var(--primary-color) !important;
    text-decoration: none;
    font-weight: 500;
}

.card a:hover {
    text-decoration: underline;
}

/* 响应式 */
@media (max-width: 480px) {
    .card {
        padding: 24px 20px;
    }
    
    .code-input-group {
        flex-direction: column;
    }
    
    .btn-secondary {
        padding: 12px 20px;
    }
}
</style>

<script>
let countdown = 0;
let timer = null;

// 切换登录方式
document.querySelectorAll('.login-tab').forEach(tab => {
    tab.addEventListener('click', function() {
        const method = this.dataset.method;
        window.history.pushState({}, '', '?method=' + method);
        document.querySelectorAll('.login-tab').forEach(t => {
            t.style.color = 'var(--text-secondary)';
            t.style.borderBottomColor = 'transparent';
        });
        this.style.color = 'var(--primary-color)';
        this.style.borderBottomColor = 'var(--primary-color)';
        document.getElementById('codeLoginForm').style.display = method === 'code' ? 'block' : 'none';
        document.getElementById('passwordLoginForm').style.display = method === 'password' ? 'block' : 'none';
    });
});

function showMessage(msg, isError) {
    const errorDiv = document.querySelector('.alert-error');
    if (errorDiv) {
        errorDiv.innerHTML = msg;
        errorDiv.style.display = 'block';
        setTimeout(() => {
            errorDiv.style.display = 'none';
        }, 3000);
    } else {
        alert(msg);
    }
}

function startCountdown(seconds) {
    const btn = document.getElementById('sendCodeBtn');
    countdown = seconds;
    btn.disabled = true;
    btn.innerHTML = `重新发送(${countdown}s)`;
    
    timer = setInterval(() => {
        countdown--;
        if (countdown <= 0) {
            clearInterval(timer);
            btn.disabled = false;
            btn.innerHTML = '发送验证码';
        } else {
            btn.innerHTML = `重新发送(${countdown}s)`;
        }
    }, 1000);
}

// 发送验证码
const sendCodeBtn = document.getElementById('sendCodeBtn');
if (sendCodeBtn) {
    sendCodeBtn.addEventListener('click', async function() {
        const email = document.getElementById('email').value;
        
        if (!email) {
            showMessage('请输入邮箱', true);
            return;
        }
        
        if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            showMessage('邮箱格式不正确', true);
            return;
        }
        
        this.disabled = true;
        this.innerHTML = '发送中...';
        
        try {
            const response = await fetch('/api/send_code.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `email=${encodeURIComponent(email)}&type=login`
            });
            const data = await response.json();
            
            if (data.success) {
                showMessage(data.message, false);
                startCountdown(60);
            } else {
                showMessage(data.message, true);
                this.disabled = false;
                this.innerHTML = '发送验证码';
            }
        } catch (error) {
            showMessage('网络错误，请重试', true);
            this.disabled = false;
            this.innerHTML = '发送验证码';
        }
    });
}
</script>
<?php include 'footer.php'; ?>