<?php
session_start();
require '../auth/config.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: ../auth/");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $user_id = $_SESSION['user_id'];
    $current_password = $_POST['current_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];

    // 输入验证
    if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
        echo "所有字段都是必需的。";
        exit();
    }

    if ($new_password !== $confirm_password) {
        echo "新密码和确认密码不一致，请重新输入。";
        exit();
    }

    // 密码必须包含大小写字母
    if (!preg_match('/[a-z]/', $new_password) || !preg_match('/[A-Z]/', $new_password)) {
        echo "新密码必须包含大小写字母。";
        exit();
    }

    // 验证当前密码
    $stmt = $conn->prepare("SELECT password FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 1) {
        $row = $result->fetch_assoc();
        if (password_verify($current_password, $row['password'])) {
            // 密码验证通过，更新新密码
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            $update_stmt = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
            $update_stmt->bind_param("si", $hashed_password, $user_id);
            
            if ($update_stmt->execute()) {
                echo "密码更新成功！";
            } else {
                echo "密码更新失败: " . $update_stmt->error;
            }
            $update_stmt->close();
        } else {
            echo "当前密码不正确，请重新输入。";
        }
    } else {
        echo "用户不存在，请重新登录。";
    }

    $stmt->close();
}

$conn->close();
?>