<?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;
}

// 数据库连接配置 - 请与register.php使用相同的配置
$servername = "localhost";
// 虚拟主机数据库用户名格式通常为 "用户名_前缀"
$username = "a1sax1m9i";  // 必须与注册页面使用的用户名一致
$password = "a1sax1m9i";     // 必须与注册页面使用的密码一致
$dbname = "a1sax1m9i";   // 必须与注册页面使用的数据库名一致

// 初始化错误信息
$error = "";

// 处理表单提交
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // 获取表单数据并过滤
    $email = trim($_POST['email'] ?? '');
    $userPassword = $_POST['password'] ?? '';

    // 表单验证
    if (empty($email)) {
        $error = "邮箱不能为空";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "请输入有效的邮箱地址";
    } elseif (empty($userPassword)) {
        $error = "密码不能为空";
    } else {
        // 连接数据库 - 添加详细的连接信息输出用于调试
        $conn = new mysqli($servername, $username, $password, $dbname);
        
        // 检查数据库连接
        if ($conn->connect_error) {
            // 显示当前使用的连接参数，帮助调试
            $error = "数据库连接失败: " . $conn->connect_error . 
                    "<br>使用的连接信息:<br>" .
                    "服务器: " . htmlspecialchars($servername) . "<br>" .
                    "用户名: " . htmlspecialchars($username) . "<br>" .
                    "数据库名: " . htmlspecialchars($dbname);
        } else {
            // 准备查询语句 - 根据实际表结构调整字段名
            // 确保password_hash与你的数据库字段名一致
            $sql = "SELECT id, username, email, password_hash FROM users WHERE email = ?";
            $stmt = $conn->prepare($sql);
            
            if (!$stmt) {
                $error = "准备查询语句失败: " . $conn->error;
            } else {
                $stmt->bind_param("s", $email);
                $stmt->execute();
                $stmt->store_result();
                
                // 检查用户是否存在
                if ($stmt->num_rows == 1) {
                    // 绑定结果到变量 - 确保与查询的字段顺序一致
                    $stmt->bind_result($userId, $username, $userEmail, $passwordHash);
                    $stmt->fetch();
                    
                    // 验证密码
                    if (password_verify($userPassword, $passwordHash)) {
                        // 密码正确，设置会话变量
                        $_SESSION['user_logged_in'] = true;
                        $_SESSION['user_id'] = $userId;
                        $_SESSION['user_info'] = [
                            'username' => $username,
                            'email' => $userEmail
                        ];
                        
                        // 更新最后登录时间
                        $updateStmt = $conn->prepare("UPDATE users SET last_login_at = CURRENT_TIMESTAMP WHERE id = ?");
                        if ($updateStmt) {
                            $updateStmt->bind_param("i", $userId);
                            $updateStmt->execute();
                            $updateStmt->close();
                        }
                        
                        // 重定向到首页
                        header('Location: index.php');
                        exit;
                    } else {
                        $error = "密码不正确";
                    }
                } else {
                    $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="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;
        }
        .register-link {
            text-align: center;
            margin-top: 1.5rem;
        }
        .register-link a {
            color: #2c3e50;
            text-decoration: none;
        }
        .register-link a:hover {
            text-decoration: underline;
        }
        .forgot-password {
            text-align: right;
            margin-bottom: 1rem;
        }
        .forgot-password a {
            color: #2c3e50;
            text-decoration: none;
            font-size: 0.9rem;
        }
        .forgot-password a:hover {
            text-decoration: underline;
        }
        .db-hint {
            font-size: 0.9rem;
            color: #666;
            margin-top: 1rem;
            padding: 1rem;
            background-color: #f8f9fa;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1><i class="fas fa-sign-in-alt"></i> 用户登录</h1>
        
        <?php if (!empty($error)): ?>
            <div class="error-message">
                <i class="fas fa-exclamation-circle"></i> <?php echo nl2br(htmlspecialchars($error)); ?>
            </div>
            
            <?php if (strpos($error, '数据库连接失败') !== false): ?>
                <div class="db-hint">
                    <strong>检查步骤：</strong><br>
                    1. 确认数据库用户名、密码和数据库名与虚拟主机面板一致<br>
                    2. 确保与register.php使用完全相同的数据库配置<br>
                    3. 检查该用户是否有权限访问指定数据库
                </div>
            <?php endif; ?>
        <?php endif; ?>
        
        <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
            <div class="form-group">
                <label for="email">邮箱</label>
                <input type="email" id="email" name="email" 
                       value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>" required>
            </div>
            
            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" id="password" name="password" required>
            </div>
            
            <div class="forgot-password">
                <a href="forgot_password.php">忘记密码？</a>
            </div>
            
            <button type="submit">登录</button>
        </form>
        
        <div class="register-link">
            还没有账号？<a href="register.php">立即注册</a>
        </div>
    </div>
</body>
</html>
