<?php
ob_start();
require_once '../config.php';
require_once '../includes/mail_helper.php';
require_once '../includes/verify_code_helper.php';

if (isLoggedIn()) {
    header('Location: index.php');
    exit;
}

$registerEnabled = getSiteConfig('register_enabled') == '1';
if (!$registerEnabled) {
    die('注册已关闭');
}

$error = '';
$invite_code = isset($_GET['code']) ? trim($_GET['code']) : '';

// 处理 AJAX 注册请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'register') {
    header('Content-Type: application/json');
    
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $email = trim($_POST['email'] ?? '');
    $code = trim($_POST['code'] ?? '');
    $invite_code = trim($_POST['invite_code'] ?? '');
    
    if (empty($username) || empty($password) || empty($email) || empty($code)) {
        echo json_encode(['success' => false, 'message' => '请填写完整信息']);
        exit;
    }
    
    if (strlen($username) < 3 || strlen($username) > 20) {
        echo json_encode(['success' => false, 'message' => '用户名3-20个字符']);
        exit;
    }
    
    if (strlen($password) < 6) {
        echo json_encode(['success' => false, 'message' => '密码至少6位']);
        exit;
    }
    
    if ($password !== $confirm_password) {
        echo json_encode(['success' => false, 'message' => '两次密码不一致']);
        exit;
    }
    
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['success' => false, 'message' => '邮箱格式不正确']);
        exit;
    }
    
    $result = completeRegisterWithCode($username, $password, $email, $code);
    
    if ($result['success'] && !empty($invite_code)) {
        $inviter = $db->fetchOne("SELECT id FROM users WHERE invite_code = '$invite_code'");
        if ($inviter && $inviter['id'] != $result['user_id']) {
            $db->query("INSERT INTO invite_records (inviter_id, invitee_id, invite_code) VALUES ({$inviter['id']}, {$result['user_id']}, '$invite_code')");
        }
    }
    
    echo json_encode($result);
    exit;
}

$site_name = getSiteConfig('site_name') ?? '麟泓授权';
$site_logo = getSiteConfig('site_logo') ?? '/assets/uploads/logo.png';

// 获取公告
$announcements = $db->fetchAll("
    SELECT * FROM announcements 
    WHERE type = 'user_register' AND status = 1 
    AND (start_time IS NULL OR start_time <= NOW()) 
    AND (end_time IS NULL OR end_time >= NOW())
    ORDER BY priority DESC, id DESC LIMIT 3
");

// 快捷登录方式
$enabled_logins = $db->fetchAll("SELECT type, name FROM quick_login_config WHERE enabled = 1 ORDER BY sort ASC");

$login_styles = [
    'qq' => ['bg' => '#12B7F5', 'icon' => 'qq.svg', 'url' => '/api/qq_login.php'],
    'wx' => ['bg' => '#07C160', 'icon' => 'wechat.svg', 'url' => '/api/wechat_login.php'],
    'alipay' => ['bg' => '#1677FF', 'icon' => 'alipay.svg', 'url' => '/api/union_login.php?type=alipay'],
    'gitee' => ['bg' => '#C71D23', 'icon' => 'gitee.svg', 'url' => '/api/gitee_login.php'],
    'github' => ['bg' => '#24292E', 'icon' => 'github.svg', 'url' => '/api/union_login.php?type=github'],
];
?>
<!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, viewport-fit=cover">
    <title>注册 - <?php echo htmlspecialchars($site_name); ?></title>
    <link rel="stylesheet" href="/assets/css/style.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #ffffff;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .register-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            padding: 24px 20px;
            max-width: 400px;
            margin: 0 auto;
            width: 100%;
        }
        
        .logo-section {
            text-align: center;
            margin-bottom: 32px;
            margin-top: 20px;
        }
        
        .logo-img {
            width: 64px;
            height: 64px;
            margin-bottom: 16px;
            border-radius: 16px;
            box-shadow: 0 8px 20px rgba(0,0,0,0.08);
        }
        
        .logo-section h1 {
            font-size: 28px;
            font-weight: 700;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: 6px;
        }
        
        .logo-section p {
            color: #94a3b8;
            font-size: 14px;
            letter-spacing: 0.5px;
        }
        
        .invite-tip {
            background: linear-gradient(135deg, #667eea15, #764ba215);
            border-radius: 16px;
            padding: 14px 18px;
            margin-bottom: 24px;
            font-size: 13px;
            color: #667eea;
            display: flex;
            align-items: center;
            gap: 10px;
            border: 1px solid #667eea20;
        }
        
        .announce-section {
            margin-bottom: 20px;
        }
        
        .announce-header {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 10px;
        }
        
        .announce-list {
            background: #f8fafc;
            border-radius: 16px;
            padding: 4px 0;
            border: 1px solid #f0f0f0;
        }
        
        .announce-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            cursor: pointer;
            transition: background 0.2s;
        }
        
        .announce-item:hover {
            background: white;
        }
        
        .announce-icon {
            width: 36px;
            height: 36px;
            border-radius: 10px;
            background: #fef3c7;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .announce-content {
            flex: 1;
        }
        
        .announce-title {
            font-size: 14px;
            font-weight: 500;
            color: #1e293b;
        }
        
        .announce-time {
            font-size: 11px;
            color: #94a3b8;
            display: flex;
            align-items: center;
            gap: 4px;
            margin-top: 4px;
        }
        
        .form-group {
            margin-bottom: 24px;
        }
        
        .form-label {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            font-weight: 500;
            color: #1e293b;
            margin-bottom: 10px;
        }
        
        .input-wrapper {
            position: relative;
        }
        
        .input-icon {
            position: absolute;
            left: 16px;
            top: 50%;
            transform: translateY(-50%);
            width: 20px;
            height: 20px;
            pointer-events: none;
            z-index: 1;
        }
        
        .form-input {
            width: 100%;
            padding: 16px 16px 16px 52px;
            border: 2px solid #f0f0f0;
            border-radius: 16px;
            font-size: 15px;
            outline: none;
            transition: all 0.2s;
            background: #fafbfc;
        }
        
        .form-input:focus {
            border-color: #667eea;
            background: white;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.1);
        }
        
        .form-input::placeholder {
            color: #cbd5e1;
        }
        
        .code-input-group {
            display: flex;
            gap: 12px;
        }
        
        .code-input-group .input-wrapper {
            flex: 1;
        }
        
        .code-btn {
            padding: 0 20px;
            white-space: nowrap;
            background: #f8fafc;
            border: 2px solid #f0f0f0;
            border-radius: 16px;
            color: #667eea;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .code-btn:hover {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }
        
        .code-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .btn-register {
            width: 100%;
            padding: 18px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 16px;
            font-size: 17px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
            margin-top: 8px;
        }
        
        .btn-register:hover {
            transform: translateY(-2px);
            box-shadow: 0 12px 28px rgba(102, 126, 234, 0.4);
        }
        
        .btn-register:disabled {
            opacity: 0.7;
            cursor: not-allowed;
            transform: none;
        }
        
        .toast-msg {
            position: fixed;
            top: 80px;
            left: 50%;
            transform: translateX(-50%);
            padding: 12px 28px;
            border-radius: 50px;
            font-size: 14px;
            font-weight: 500;
            z-index: 9999;
            animation: fadeInOut 3s ease;
            box-shadow: 0 8px 20px rgba(0,0,0,0.15);
        }
        
        .toast-success {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
        }
        
        .toast-error {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            color: white;
        }
        
        @keyframes fadeInOut {
            0%, 100% { opacity: 0; transform: translateX(-50%) translateY(-10px); }
            10%, 90% { opacity: 1; transform: translateX(-50%) translateY(0); }
        }
        
        .other-login {
            text-align: center;
            margin-top: 32px;
        }
        
        .other-title {
            display: flex;
            align-items: center;
            color: #94a3b8;
            font-size: 13px;
            margin-bottom: 24px;
        }
        
        .other-title::before,
        .other-title::after {
            content: '';
            flex: 1;
            height: 1px;
            background: linear-gradient(90deg, transparent, #e2e8f0, transparent);
        }
        
        .other-title span {
            padding: 0 20px;
        }
        
        .login-icons {
            display: flex;
            justify-content: center;
            gap: 24px;
        }
        
        .login-icon {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 56px;
            height: 56px;
            border-radius: 18px;
            transition: all 0.3s;
            text-decoration: none;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
        }
        
        .login-icon:hover {
            transform: translateY(-4px);
            box-shadow: 0 8px 20px rgba(0,0,0,0.12);
        }
        
        .login-icon img {
            width: 28px;
            height: 28px;
        }
        
        .auth-footer {
            text-align: center;
            margin-top: 32px;
        }
        
        .auth-footer p {
            color: #64748b;
            font-size: 15px;
        }
        
        .auth-footer a {
            color: #667eea;
            text-decoration: none;
            font-weight: 600;
            margin-left: 4px;
        }
        
        .copyright {
            text-align: center;
            color: #cbd5e1;
            font-size: 12px;
            padding: 24px 0 10px;
        }
        
        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid rgba(255,255,255,0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 0.6s linear infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            backdrop-filter: blur(4px);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 10000;
        }
        
        .modal-content {
            background: white;
            border-radius: 24px;
            width: 90%;
            max-width: 500px;
            max-height: 70vh;
            overflow: hidden;
            box-shadow: 0 20px 40px rgba(0,0,0,0.2);
        }
        
        .modal-header {
            padding: 20px 24px;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .modal-header h3 {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 18px;
            font-weight: 600;
            margin: 0;
        }
        
        .modal-close {
            background: none;
            border: none;
            cursor: pointer;
            padding: 4px;
            border-radius: 8px;
            display: flex;
        }
        
        .modal-body {
            padding: 24px;
            max-height: 50vh;
            overflow-y: auto;
            line-height: 1.7;
            color: #64748b;
        }
        
        .modal-footer {
            padding: 16px 24px;
            border-top: 1px solid #f0f0f0;
            display: flex;
            justify-content: flex-end;
        }
        
        .btn-modal {
            padding: 12px 28px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 30px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="register-container">
        <div class="logo-section">
            <h1><?php echo htmlspecialchars($site_name); ?></h1>
            <p>但行前路 · 不负韶华</p>
        </div>
        
        <?php if (!empty($announcements)): ?>
        <div class="announce-section">
            <div class="announce-header">
                <img src="https://api.iconify.design/mdi:bullhorn.svg?color=%23f59e0b" width="18" height="18" alt="">
                公告须知
            </div>
            <div class="announce-list">
                <?php foreach ($announcements as $announce): ?>
                <div class="announce-item" onclick="showAnnouncement(<?php echo htmlspecialchars(json_encode($announce)); ?>)">
                    <div class="announce-icon">
                        <img src="https://api.iconify.design/mdi:bullhorn.svg?color=%23f59e0b" width="18" height="18" alt="">
                    </div>
                    <div class="announce-content">
                        <div class="announce-title"><?php echo htmlspecialchars($announce['title']); ?></div>
                        <div class="announce-time">
                            <img src="https://api.iconify.design/mdi:clock-outline.svg?color=%2394a3b8" width="10" height="10" alt="">
                            <?php echo date('m-d H:i', strtotime($announce['created_at'])); ?>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
        
    
        
        <form id="registerForm">
            <input type="hidden" name="invite_code" id="invite_code" value="<?php echo htmlspecialchars($invite_code); ?>">
            
            <div class="form-group">
                <div class="form-label">
                    <img src="https://api.iconify.design/mdi:account-outline.svg?color=%23667eea" width="18" height="18" alt="">
                    用户名
                </div>
                <div class="input-wrapper">
                    <input type="text" id="username" name="username" class="form-input" placeholder="请输入用户名" required>
                </div>
            </div>
            
            <div class="form-group">
                <div class="form-label">
                    <img src="https://api.iconify.design/mdi:email-outline.svg?color=%23667eea" width="18" height="18" alt="">
                    邮箱
                </div>
                <div class="code-input-group">
                    <div class="input-wrapper">
                        <input type="email" id="email" name="email" class="form-input" placeholder="请输入邮箱" required>
                    </div>
                    <button type="button" id="sendCodeBtn" class="code-btn">发送验证码</button>
                </div>
            </div>
            
            <div class="form-group">
                <div class="form-label">
                    <img src="https://api.iconify.design/mdi:shield-key-outline.svg?color=%23667eea" width="18" height="18" alt="">
                    验证码
                </div>
                <div class="input-wrapper">
                    <input type="text" id="code" name="code" class="form-input" placeholder="请输入6位验证码" required>
                </div>
            </div>
            
            <div class="form-group">
                <div class="form-label">
                    <img src="https://api.iconify.design/mdi:lock-outline.svg?color=%23667eea" width="18" height="18" alt="">
                    密码
                </div>
                <div class="input-wrapper">
                    <input type="password" id="password" name="password" class="form-input" placeholder="至少6位密码" required>
                </div>
            </div>
            
            <div class="form-group">
                <div class="form-label">
                    <img src="https://api.iconify.design/mdi:lock-check-outline.svg?color=%23667eea" width="18" height="18" alt="">
                    确认密码
                </div>
                <div class="input-wrapper">
                    <input type="password" id="confirm_password" name="confirm_password" class="form-input" placeholder="再次输入密码" required>
                </div>
            </div>
            
            <button type="submit" class="btn-register" id="registerBtn">注 册</button>
        </form>
        
        <?php if (!empty($enabled_logins)): ?>
        <div class="other-login">
            <div class="other-title">
                <span>第三方注册</span>
            </div>
            <div class="login-icons">
                <?php foreach ($enabled_logins as $login): 
                    $type = $login['type'];
                    $style = $login_styles[$type] ?? ['bg' => '#667eea', 'icon' => 'default.svg', 'url' => '#'];
                ?>
                    <a href="<?php echo $style['url']; ?>" class="login-icon" style="background: <?php echo $style['bg']; ?>;">
                        <img src="/assets/svg/<?php echo $style['icon']; ?>" alt="<?php echo $login['name']; ?>">
                    </a>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
        
        <div class="auth-footer">
            <p>已有账号？<a href="login.php">立即登录</a></p>
        </div>
        
        <div class="copyright">
            Copyright © 2025 <?php echo htmlspecialchars($site_name); ?>. All Rights Reserved.
        </div>
    </div>
    
    <!-- 公告弹窗 -->
    <div id="announcementModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">
                    <img src="https://api.iconify.design/mdi:bullhorn.svg?color=%23667eea" width="20" height="20" alt="">
                    公告详情
                </h3>
                <button class="modal-close" onclick="closeModal()">
                    <img src="https://api.iconify.design/mdi:close.svg?color=%2394a3b8" width="22" height="22" alt="">
                </button>
            </div>
            <div class="modal-body">
                <div id="modalContent"></div>
            </div>
            <div class="modal-footer">
                <button class="btn-modal" onclick="closeModal()">关 闭</button>
            </div>
        </div>
    </div>
    
    <script>
        let countdown = 0;
        let timer = null;
        
        function showToast(msg, type) {
            const toast = document.createElement('div');
            toast.className = `toast-msg toast-${type}`;
            toast.innerHTML = msg;
            document.body.appendChild(toast);
            setTimeout(() => toast.remove(), 3000);
        }
        
        function startCountdown(seconds) {
            const btn = document.getElementById('sendCodeBtn');
            countdown = seconds;
            btn.disabled = true;
            btn.textContent = `重新发送(${countdown}s)`;
            
            timer = setInterval(() => {
                countdown--;
                if (countdown <= 0) {
                    clearInterval(timer);
                    btn.disabled = false;
                    btn.textContent = '发送验证码';
                } else {
                    btn.textContent = `重新发送(${countdown}s)`;
                }
            }, 1000);
        }
        
        function showAnnouncement(announce) {
            const modal = document.getElementById('announcementModal');
            document.getElementById('modalTitle').innerHTML = `
                <img src="https://api.iconify.design/mdi:bullhorn.svg?color=%23667eea" width="20" height="20" alt="">
                ${announce.title}
            `;
            document.getElementById('modalContent').innerHTML = announce.content;
            modal.style.display = 'flex';
            
            fetch('/api/mark_announcement_read.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `id=${announce.id}`
            });
        }
        
        function closeModal() {
            document.getElementById('announcementModal').style.display = 'none';
        }
        
        document.getElementById('announcementModal')?.addEventListener('click', function(e) {
            if (e.target === this) closeModal();
        });
        
        document.getElementById('sendCodeBtn').addEventListener('click', async function() {
            const email = document.getElementById('email').value;
            
            if (!email) {
                showToast('请输入邮箱', 'error');
                return;
            }
            
            if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
                showToast('邮箱格式不正确', 'error');
                return;
            }
            
            this.disabled = true;
            this.textContent = '发送中...';
            
            try {
                const response = await fetch('/api/send_code.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: `email=${encodeURIComponent(email)}&type=register`
                });
                const data = await response.json();
                
                if (data.success) {
                    showToast(data.message, 'success');
                    startCountdown(60);
                } else {
                    showToast(data.message, 'error');
                    this.disabled = false;
                    this.textContent = '发送验证码';
                }
            } catch (error) {
                showToast('网络错误，请重试', 'error');
                this.disabled = false;
                this.textContent = '发送验证码';
            }
        });
        
        document.getElementById('registerForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const username = document.getElementById('username').value;
            const email = document.getElementById('email').value;
            const code = document.getElementById('code').value;
            const password = document.getElementById('password').value;
            const confirm_password = document.getElementById('confirm_password').value;
            const invite_code = document.getElementById('invite_code').value;
            
            const registerBtn = document.getElementById('registerBtn');
            registerBtn.disabled = true;
            registerBtn.innerHTML = '<span class="loading-spinner"></span> 注册中...';
            
            try {
                let body = `username=${encodeURIComponent(username)}&email=${encodeURIComponent(email)}&code=${encodeURIComponent(code)}&password=${encodeURIComponent(password)}&confirm_password=${encodeURIComponent(confirm_password)}`;
                if (invite_code) body += `&invite_code=${encodeURIComponent(invite_code)}`;
                
                const response = await fetch('/m/register.php?action=register', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: body
                });
                const data = await response.json();
                
                if (data.success) {
                    showToast(data.message, 'success');
                    setTimeout(() => window.location.href = 'index.php', 1500);
                } else {
                    showToast(data.message, 'error');
                    registerBtn.disabled = false;
                    registerBtn.textContent = '注 册';
                }
            } catch (error) {
                showToast('网络错误，请重试', 'error');
                registerBtn.disabled = false;
                registerBtn.textContent = '注 册';
            }
        });
    </script>
</body>
</html>