<?php
header('Content-Type: application/json; charset=utf-8');

// 允许跨域请求
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");

// 数据库连接配置
$servername = "localhost";
$username = "a1sax1m9i";
$password = "a1sax1m9i";
$dbname = "a1sax1m9i";

// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接
if ($conn->connect_error) {
    die(json_encode(array(
        "success" => false, 
        "message" => "数据库连接失败: " . $conn->connect_error
    )));
}

// 设置数据库连接字符集
$conn->set_charset("utf8mb4");

/**
 * 根据用户ID获取用户信息
 */
function getUserById($conn) {
    $userId = $_GET['id'] ?? '';
    
    if (empty($userId) || !is_numeric($userId)) {
        return array(
            "success" => false,
            "message" => "请提供有效的用户ID"
        );
    }
    
    // 修复：移除last_login_at字段引用
    $sql = "SELECT id, username, email, created_at FROM users WHERE id = ?";
    $stmt = $conn->prepare($sql);
    
    if (!$stmt) {
        return array(
            "success" => false,
            "message" => "查询准备失败: " . $conn->error
        );
    }
    
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        $stmt->close();
        
        return array(
            "success" => true,
            "data" => $user
        );
    } else {
        $stmt->close();
        return array(
            "success" => false,
            "message" => "未找到ID为 {$userId} 的用户"
        );
    }
}

/**
 * 获取所有用户信息
 */
function getAllUsers($conn) {
    // 修复：移除last_login_at字段引用
    $sql = "SELECT id, username, email, created_at FROM users ORDER BY id ASC";
    $result = $conn->query($sql);
    
    $users = array();
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $users[] = $row;
        }
        
        return array(
            "success" => true,
            "count" => count($users),
            "data" => $users
        );
    } else {
        return array(
            "success" => false,
            "message" => "没有找到任何用户信息",
            "data" => array()
        );
    }
}

// 处理请求
$action = $_GET['action'] ?? '';

switch ($action) {
    case 'getUser':
        $response = getUserById($conn);
        break;
    case 'getAllUsers':
        $response = getAllUsers($conn);
        break;
    default:
        $response = array(
            "success" => false, 
            "message" => "请指定正确的操作: action=getUser (需要id参数) 或 action=getAllUsers"
        );
}

// 输出JSON响应
echo json_encode($response, JSON_UNESCAPED_UNICODE);

// 关闭数据库连接
$conn->close();
?>
