<?php
require_once dirname(__DIR__) . '/config.php';

header('Content-Type: application/json');

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

$user = currentUser();
if ($user['role'] !== 'admin') {
    echo json_encode(['success' => false, 'message' => '权限不足']);
    exit;
}

$id = intval($_POST['id'] ?? 0);

if ($id <= 0) {
    echo json_encode(['success' => false, 'message' => '参数错误']);
    exit;
}

// 检查用户是否存在且不是代理商
$target = $db->fetchOne("SELECT id, role FROM users WHERE id = $id");
if (!$target) {
    echo json_encode(['success' => false, 'message' => '用户不存在']);
    exit;
}

if ($target['role'] == 'admin') {
    echo json_encode(['success' => false, 'message' => '管理员不能设为代理商']);
    exit;
}

$db->query("UPDATE users SET is_agent = 1, agent_level = 1 WHERE id = $id");
echo json_encode(['success' => true]);
exit;
?>