<?php
// 开启错误显示以便调试
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 启动会话
session_start();

// 修复跳转逻辑：仅当用户已登录时才跳转到首页
// 已登录用户不需要注册，直接跳转
if (isset($_SESSION['user_logged_in']) && $_SESSION['user_logged_in'] === true) {
    header('Location: index.php');
    exit;
}

// 数据库连接配置 - 与登录页面保持一致
$servername = "localhost";
$dbusername = "a1sax1m9i";  // 与登录页面相同的数据库用户名
$dbpassword = "a1sax1m9i";     // 与登录页面相同的数据库密码
$dbname = "a1sax1m9i";   // 与登录页面相同的数据库名

// 初始化消息变量
$error = "";
$success = false;

// 处理表单提交
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // 获取表单数据并过滤
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $nickname = trim($_POST['nickname'] ?? $username); // 昵称默认为用户名

    // 表单验证
    if (empty($username)) {
        $error = "用户名不能为空";
    } elseif (strlen($username) < 3 || strlen($username) > 20) {
        $error = "用户名长度必须在3-20个字符之间";
    } elseif (empty($email)) {
        $error = "邮箱不能为空";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "请输入有效的邮箱地址";
    } elseif (empty($password)) {
        $error = "密码不能为空";
    } elseif (strlen($password) < 6) {
        $error = "密码长度不能少于6个字符";
    } elseif ($password !== $confirm_password) {
        $error = "两次输入的密码不一致";
    } else {
        // 连接数据库
        $conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);
        
        // 检查数据库连接
        if ($conn->connect_error) {
            $error = "数据库连接失败: " . $conn->connect_error . 
                    "<br>使用的连接信息:<br>" .
                    "服务器: " . htmlspecialchars($servername) . "<br>" .
                    "用户名: " . htmlspecialchars($dbusername) . "<br>" .
                    "数据库名: " . htmlspecialchars($dbname);
        } else {
            // 检查用户名或邮箱是否已存在
            $sql = "SELECT id FROM users WHERE username = ? OR email = ?";
            $stmt = $conn->prepare($sql);
            
            if (!$stmt) {
                $error = "准备查询语句失败: " . $conn->error;
            } else {
                $stmt->bind_param("ss", $username, $email);
                $stmt->execute();
                $stmt->store_result();
                
                if ($stmt->num_rows > 0) {
                    $error = "用户名或邮箱已被注册";
                    $stmt->close();
                } else {
                    $stmt->close();
                    
                    // 密码加密
                    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                    
                    // 插入新用户
                    $sql = "INSERT INTO users (username, email, password_hash, nickname, created_at) 
                            VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)";
                    $stmt = $conn->prepare($sql);
                    
                    if (!$stmt) {
                        $error = "准备插入语句失败: " . $conn->error;
                    } else {
                        $stmt->bind_param("ssss", $username, $email, $hashed_password, $nickname);
                        
                        if ($stmt->execute()) {
                            $success = true;
                            
                            // 注册成功后自动登录（可选）
                            $_SESSION['user_logged_in'] = true;
                            $_SESSION['user_id'] = $conn->insert_id;
                            $_SESSION['user_info'] = [
                                'username' => $username,
                                'email' => $email,
                                'nickname' => $nickname
                            ];
                            
                            // 延迟跳转，让用户看到成功信息
                            if ($_POST['auto_login'] ?? true) {
                                header('Refresh: 2; URL=index.php');
                            }
                        } else {
                            $error = "注册失败: " . $stmt->error;
                        }
                        
                        $stmt->close();
                    }
                }
            }
            
            $conn->close();
        }
    }
}
?>

<!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="icon" href="./static/icon/icon.png" type="image/png">
    <link rel="alternate icon" href="./static/icon/icon.ico" type="image/x-icon">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @font-face {
            font-family: "MyCustomFont";
            src: url("./static/font/bbc.ttf") format("truetype");
            font-weight: normal;
            font-style: normal;
        }
        :root{
            --main-font: "MyCustomFont", sans-serif; /* 自定义字体变量 */
        }
        /* 基础样式 */
        body {
            font-family: var(--main-font); /* 应用自定义字体 */
            max-width: 500px;
            margin: 2rem auto;
            padding: 0 1rem;
            background-color: #f5f5f7;
        }
        .container {
            background-color: white;
            padding: 2rem;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            text-align: center;
            color: #2c3e50;
        }
        .form-group {
            margin-bottom: 1.5rem;
        }
        label {
            display: block;
            margin-bottom: 0.5rem;
            color: #333;
        }
        input {
            width: 100%;
            padding: 0.8rem;
            border: 1px solid #ddd;
            border-radius: 5px;
            box-sizing: border-box;
            font-size: 1rem;
        }
        button {
            width: 100%;
            padding: 0.8rem;
            background-color: #2c3e50;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 1rem;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #34495e;
        }
        .error-message {
            background-color: #f8d7da;
            color: #721c24;
            padding: 1rem;
            border-radius: 5px;
            margin-bottom: 1.5rem;
            text-align: left;
        }
        .success-message {
            background-color: #d4edda;
            color: #155724;
            padding: 1rem;
            border-radius: 5px;
            margin-bottom: 1.5rem;
            text-align: center;
        }
        .login-link {
            text-align: center;
            margin-top: 1.5rem;
        }
        .login-link a {
            color: #2c3e50;
            text-decoration: none;
        }
        .login-link a:hover {
            text-decoration: underline;
        }
        .form-hint {
            font-size: 0.85rem;
            color: #666;
            margin-top: 0.3rem;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1><i class="fas fa-user-plus"></i> 用户注册</h1>
        
        <?php if (!empty($error)): ?>
            <div class="error-message">
                <i class="fas fa-exclamation-circle"></i> <?php echo nl2br(htmlspecialchars($error)); ?>
            </div>
        <?php endif; ?>
        
        <?php if ($success): ?>
            <div class="success-message">
                <i class="fas fa-check-circle"></i> 注册成功！感谢您的加入<br>
                2秒后将自动跳转到首页...
            </div>
        <?php else: ?>
            <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" name="username" 
                           value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>" required>
                    <div class="form-hint">3-20个字符，可包含字母、数字和下划线</div>
                </div>
                
                <div class="form-group">
                    <label for="nickname">昵称（可选）</label>
                    <input type="text" id="nickname" name="nickname" 
                           value="<?php echo htmlspecialchars($_POST['nickname'] ?? ''); ?>">
                    <div class="form-hint">显示给其他用户的名称，不填则默认与用户名相同</div>
                </div>
                
                <div class="form-group">
                    <label for="email">邮箱</label>
                    <input type="email" id="email" name="email" 
                           value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>" required>
                    <div class="form-hint">用于登录和密码找回</div>
                </div>
                
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" name="password" required>
                    <div class="form-hint">至少6个字符，建议包含字母和数字</div>
                </div>
                
                <div class="form-group">
                    <label for="confirm_password">确认密码</label>
                    <input type="password" id="confirm_password" name="confirm_password" required>
                </div>
                
                <input type="hidden" name="auto_login" value="1">
                <button type="submit"><i class="fas fa-register"></i> 注册账号</button>
            </form>
        <?php endif; ?>
        
        <div class="login-link">
            已有账号？<a href="login.php">立即登录</a>
        </div>
    </div>
</body>
</html>
