<?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>
.btn-secondary {
    background: var(--bg-secondary);
    border: 1px solid var(--border-color);
    color: var(--text-primary);
    cursor: pointer;
    transition: all 0.2s;
}
.btn-secondary:hover {
    background: var(--border-color);
}
.btn-secondary:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}
.login-tab {
    transition: all 0.2s;
}
.login-tab:hover {
    color: var(--primary-color);
}
</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'; ?>