<?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'];
    $password = $_POST['password'];
    $confirm = $_POST['confirm'];

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

    if ($confirm !== "确认注销") {
        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($password, $row['password'])) {
            // 密码验证通过，开始删除账户
            // 先删除关联的玩家数据
            $delete_players = $conn->prepare("DELETE FROM players WHERE user_id = ?");
            $delete_players->bind_param("i", $user_id);
            $delete_players->execute();
            $delete_players->close();
            
            // 再删除用户数据
            $delete_user = $conn->prepare("DELETE FROM users WHERE id = ?");
            $delete_user->bind_param("i", $user_id);
            
            if ($delete_user->execute()) {
                // 删除成功，销毁会话并重定向到登录页
                session_destroy();
                echo "账户已成功注销！";
                header("refresh:2;url=../auth/");
                exit();
            } else {
                echo "账户注销失败: " . $delete_user->error;
            }
            $delete_user->close();
        } else {
            echo "密码不正确，请重新输入。";
        }
    } else {
        echo "用户不存在，请重新登录。";
    }

    $stmt->close();
}

$conn->close();
?>