<?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";
$username = "a1sax1m9i";  // 与其他页面相同
$password = "a1sax1m9i";     // 与其他页面相同
$dbname = "a1sax1m9i";   // 与其他页面相同

// 初始化消息变量
$message = "";
$messageType = ""; // success 或 error
$tokenValid = false;
$userId = null;

// 确保密码重置表存在
function ensurePasswordResetTableExists($conn) {
    $sql = "CREATE TABLE IF NOT EXISTS password_reset_tokens (
        user_id INT NOT NULL,
        token VARCHAR(255) NOT NULL,
        expiry DATETIME NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (user_id),
        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
    
    if (!$conn->query($sql)) {
        return "创建密码重置表失败: " . $conn->error;
    }
    return true;
}

// 检查令牌是否存在
if (!isset($_GET['token']) || empty($_GET['token'])) {
    $message = "无效的重置链接";
    $messageType = "error";
} else {
    $token = $_GET['token'];
    
    // 连接数据库
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    // 检查数据库连接
    if ($conn->connect_error) {
        $message = "数据库连接失败: " . $conn->connect_error;
        $messageType = "error";
    } else {
        // 确保密码重置表存在
        $tableCheck = ensurePasswordResetTableExists($conn);
        if ($tableCheck !== true) {
            $message = $tableCheck;
            $messageType = "error";
        } else {
            // 检查令牌是否有效且未过期
            $sql = "SELECT user_id FROM password_reset_tokens WHERE token = ? AND expiry > NOW()";
            $stmt = $conn->prepare($sql);
            
            if (!$stmt) {
                $message = "准备查询语句失败: " . $conn->error;
                $messageType = "error";
            } else {
                $stmt->bind_param("s", $token);
                $stmt->execute();
                $stmt->store_result();
                
                if ($stmt->num_rows == 1) {
                    // 令牌有效
                    $stmt->bind_result($userId);
                    $stmt->fetch();
                    $tokenValid = true;
                } else {
                    $message = "重置链接无效或已过期";
                    $messageType = "error";
                }
                
                $stmt->close();
            }
        }
        
        $conn->close();
    }
}

// 处理表单提交
if ($_SERVER["REQUEST_METHOD"] == "POST" && $tokenValid && $userId !== null) {
    // 获取表单数据并过滤
    $newPassword = $_POST['new_password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';
    
    // 表单验证
    if (empty($newPassword)) {
        $message = "新密码不能为空";
        $messageType = "error";
    } elseif (strlen($newPassword) < 6) {
        $message = "密码长度不能少于6个字符";
        $messageType = "error";
    } elseif ($newPassword !== $confirmPassword) {
        $message = "两次输入的密码不一致";
        $messageType = "error";
    } else {
        // 连接数据库
        $conn = new mysqli($servername, $username, $password, $dbname);
        
        // 检查数据库连接
        if ($conn->connect_error) {
            $message = "数据库连接失败: " . $conn->connect_error;
            $messageType = "error";
        } else {
            // 哈希密码
            $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
            
            // 更新用户密码
            $sql = "UPDATE users SET password_hash = ? WHERE id = ?";
            $stmt = $conn->prepare($sql);
            
            if (!$stmt) {
                $message = "准备更新语句失败: " . $conn->error;
                $messageType = "error";
            } else {
                $stmt->bind_param("si", $hashedPassword, $userId);
                
                if ($stmt->execute()) {
                    // 密码更新成功，删除令牌
                    $deleteStmt = $conn->prepare("DELETE FROM password_reset_tokens WHERE user_id = ?");
                    $deleteStmt->bind_param("i", $userId);
                    $deleteStmt->execute();
                    $deleteStmt->close();
                    
                    $message = "密码已成功重置，请使用新密码登录";
                    $messageType = "success";
                    $tokenValid = false; // 防止再次提交
                } else {
                    $message = "密码更新失败，请稍后再试";
                    $messageType = "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>
        /* 基础样式 */
        body {
            font-family: 'Arial', sans-serif;
            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;
        }
        .message {
            padding: 1rem;
            border-radius: 5px;
            margin-bottom: 1.5rem;
            text-align: left;
        }
        .error-message {
            background-color: #f8d7da;
            color: #721c24;
        }
        .success-message {
            background-color: #d4edda;
            color: #155724;
        }
        .login-link {
            text-align: center;
            margin-top: 1.5rem;
        }
        .login-link a {
            color: #2c3e50;
            text-decoration: none;
        }
        .login-link a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1><i class="fas fa-redo"></i> 重置密码</h1>
        
        <?php if (!empty($message)): ?>
            <div class="message <?php echo $messageType === 'error' ? 'error-message' : 'success-message'; ?>">
                <i class="fas <?php echo $messageType === 'error' ? 'fa-exclamation-circle' : 'fa-check-circle'; ?>"></i> 
                <?php echo nl2br(htmlspecialchars($message)); ?>
            </div>
        <?php endif; ?>
        
        <?php if ($tokenValid): ?>
            <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) . '?token=' . htmlspecialchars($_GET['token']); ?>">
                <div class="form-group">
                    <label for="new_password">新密码</label>
                    <input type="password" id="new_password" name="new_password" minlength="6" required>
                </div>
                
                <div class="form-group">
                    <label for="confirm_password">确认新密码</label>
                    <input type="password" id="confirm_password" name="confirm_password" minlength="6" required>
                </div>
                
                <button type="submit">重置密码</button>
            </form>
        <?php endif; ?>
        
        <div class="login-link">
            <a href="login.php"><i class="fas fa-sign-in-alt"></i> 返回登录</a>
        </div>
    </div>
</body>
</html>
