<?php
session_start();
require_once('./config.php');

// 验证用户是否登录
if (!isset($_SESSION['user_id'])) {
    die("未授权访问！");
}

// 获取当前用户ID
$currentUserId = $_SESSION['user_id'];

// 查询当前用户等级
$stmt = $conn->prepare("SELECT level FROM users WHERE id = ?");
$stmt->bind_param("i", $currentUserId);
$stmt->execute();
$result = $stmt->get_result();
$userData = $result->fetch_assoc();
$stmt->close();

// 检查是否为管理员（等级4）
if ($userData['level'] != 4) {
    die("权限不足！");
}

// 处理删除玩家逻辑
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $playerId = $_POST['player_id'];
    
    // 查询玩家名称
    $stmt = $conn->prepare("SELECT player_name FROM players WHERE id = ?");
    $stmt->bind_param("i", $playerId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows == 1) {
        $playerData = $result->fetch_assoc();
        $playerName = $playerData['player_name'];
        $stmt->close();
        
        // 开始事务处理
        $conn->begin_transaction();
        
        try {
            $stmt = $conn->prepare("DELETE FROM players WHERE id = ?");
            $stmt->bind_param("i", $playerId);
            $stmt->execute();
            $stmt->close();
            
            
            if ($easyauthConn->connect_error) {
                throw new Exception("EasyAuth数据库连接失败: " . $easyauthConn->connect_error);
            }
            
            // 在easyauth数据库中删除对应记录
            $stmt = $easyauthConn->prepare("DELETE FROM easyauth WHERE username = ?");
            $stmt->bind_param("s", $playerName);
            $stmt->execute();
            
            if ($stmt->affected_rows == 0) {
                throw new Exception("EasyAuth中未找到对应记录或删除失败");
            }
            
            $stmt->close();
            $easyauthConn->close();
            
            // 提交事务
            $conn->commit();
            echo "玩家删除成功！";
            
        } catch (Exception $e) {
            // 回滚事务
            $conn->rollback();
            echo "操作失败：" . $e->getMessage();
        }
    } else {
        $stmt->close();
        echo "未找到该玩家！";
    }
}

$conn->close();
?>