<?php
/**
 * 用户注册页面
 * 物业工单管理系统
 */

require_once '../includes/functions.php';

// 如果用户已登录，重定向到仪表盘
if (isLoggedIn()) {
    redirect('../dashboard.php');
}

$errors = [];
$success = false;

// 处理注册表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = sanitizeInput(isset($_POST['username']) ? $_POST['username'] : '');
    $email = sanitizeInput(isset($_POST['email']) ? $_POST['email'] : '');
    $password = isset($_POST['password']) ? $_POST['password'] : '';
    $confirm_password = isset($_POST['confirm_password']) ? $_POST['confirm_password'] : '';
    
    // 验证输入
    if (empty($username)) {
        $errors[] = '用户名不能为空';
    } elseif (strlen($username) < 3) {
        $errors[] = '用户名至少需要3个字符';
    } elseif (strlen($username) > 50) {
        $errors[] = '用户名不能超过50个字符';
    }
    
    if (empty($email)) {
        $errors[] = '邮箱不能为空';
    } elseif (!validateEmail($email)) {
        $errors[] = '请输入有效的邮箱地址';
    }
    
    if (empty($password)) {
        $errors[] = '密码不能为空';
    } elseif (!validatePassword($password)) {
        $errors[] = '密码至少需要8位，包含字母和数字';
    }
    
    if ($password !== $confirm_password) {
        $errors[] = '两次输入的密码不一致';
    }
    
    // 如果没有错误，尝试注册用户
    if (empty($errors)) {
        try {
            $pdo = getDBConnection();
            
            // 检查用户名是否已存在
            $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
            $stmt->execute([$username]);
            if ($stmt->fetch()) {
                $errors[] = '用户名已存在';
            }
            
            // 检查邮箱是否已存在
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$email]);
            if ($stmt->fetch()) {
                $errors[] = '邮箱已被注册';
            }
            
            // 如果用户名和邮箱都可用，创建新用户
            if (empty($errors)) {
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                
                $stmt = $pdo->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");
                if ($stmt->execute([$username, $email, $hashed_password])) {
                    $success = true;
                    showSuccess('注册成功！请登录您的账户。');
                    redirect('login.php');
                } else {
                    $errors[] = '注册失败，请稍后重试';
                }
            }
            
        } catch (PDOException $e) {
            $errors[] = '数据库错误，请稍后重试';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户注册 - 物业工单管理系统</title>
    <link rel="stylesheet" href="../assets/css/style.css">
</head>
<body>
    <div class="header">
        <div class="container">
            <h1>物业工单管理系统</h1>
            <p>用户注册</p>
        </div>
    </div>

    <div class="container">
        <div class="card">
            <h2>创建新账户</h2>
            
            <?php if (!empty($errors)): ?>
                <?php foreach ($errors as $error): ?>
                    <div class="alert alert-error"><?php echo $error; ?></div>
                <?php endforeach; ?>
            <?php endif; ?>
            
            <form method="POST" action="">
                <div class="form-group">
                    <label for="username">用户名 *</label>
                    <input type="text" id="username" name="username" class="form-control" 
                           value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>" 
                           required>
                    <small>用户名至少3个字符，最多50个字符</small>
                </div>
                
                <div class="form-group">
                    <label for="email">邮箱地址 *</label>
                    <input type="email" id="email" name="email" class="form-control" 
                           value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>" 
                           required>
                </div>
                
                <div class="form-group">
                    <label for="password">密码 *</label>
                    <input type="password" id="password" name="password" class="form-control" required>
                    <small>密码至少8位，必须包含字母和数字</small>
                </div>
                
                <div class="form-group">
                    <label for="confirm_password">确认密码 *</label>
                    <input type="password" id="confirm_password" name="confirm_password" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <button type="submit" class="btn btn-primary">注册</button>
                    <a href="login.php" class="btn btn-secondary">已有账户？去登录</a>
                </div>
            </form>
        </div>
    </div>

    <div class="footer">
        <div class="container">
            <p>&copy; 2024 物业工单管理系统. 保留所有权利.</p>
        </div>
    </div>

    <script>
        // 简单的密码强度检查
        document.getElementById('password').addEventListener('input', function() {
            const password = this.value;
            const hasLetter = /[A-Za-z]/.test(password);
            const hasNumber = /[0-9]/.test(password);
            const isLongEnough = password.length >= 8;
            
            if (isLongEnough && hasLetter && hasNumber) {
                this.style.borderColor = '#28a745';
            } else {
                this.style.borderColor = '#dc3545';
            }
        });
        
        // 确认密码检查
        document.getElementById('confirm_password').addEventListener('input', function() {
            const password = document.getElementById('password').value;
            const confirmPassword = this.value;
            
            if (password === confirmPassword && confirmPassword !== '') {
                this.style.borderColor = '#28a745';
            } else if (confirmPassword !== '') {
                this.style.borderColor = '#dc3545';
            } else {
                this.style.borderColor = '#ddd';
            }
        });
    </script>
</body>
</html>
