<?php
/**
 * 更新管理员角色
 * 将 admin 用户设置为超级管理员 (role = 2)
 */
require_once __DIR__ . '/includes/functions.php';

echo "<h1>更新管理员角色</h1>";

// 检查是否有 role 字段
try {
    $checkColumn = db()->queryOne("SHOW COLUMNS FROM users LIKE 'role'");
    if (!$checkColumn) {
        echo "<p style='color: red;'>错误：users 表中没有 role 字段</p>";
        exit;
    }
    echo "<p>✓ role 字段存在</p>";
    
    // 查找 admin 用户
    $admin = db()->queryOne("SELECT id, username, role FROM users WHERE username = 'admin' OR username = 'administrator' LIMIT 1");
    
    if ($admin) {
        echo "<p>找到用户: " . htmlspecialchars($admin['username']) . " (当前角色: " . $admin['role'] . ")</p>";
        
        // 更新为超级管理员
        db()->execute("UPDATE users SET role = 2 WHERE id = ?", [$admin['id']]);
        echo "<p style='color: green;'>✓ 已将 " . htmlspecialchars($admin['username']) . " 设置为超级管理员 (role = 2)</p>";
    } else {
        // 查找第一个管理员
        $firstAdmin = db()->queryOne("SELECT id, username, role FROM users WHERE role = 1 ORDER BY id ASC LIMIT 1");
        
        if ($firstAdmin) {
            echo "<p>未找到 admin 用户，找到第一个管理员: " . htmlspecialchars($firstAdmin['username']) . "</p>";
            db()->execute("UPDATE users SET role = 2 WHERE id = ?", [$firstAdmin['id']]);
            echo "<p style='color: green;'>✓ 已将 " . htmlspecialchars($firstAdmin['username']) . " 设置为超级管理员 (role = 2)</p>";
        } else {
            echo "<p style='color: orange;'>警告：未找到任何管理员用户</p>";
            echo "<p>请先在数据库中创建一个管理员用户，然后运行此脚本</p>";
        }
    }
    
    echo "<hr>";
    echo "<h2>当前管理员列表</h2>";
    echo "<table border='1' cellpadding='10' style='border-collapse: collapse;'>";
    echo "<tr style='background: #f0f0f0;'><th>ID</th><th>用户名</th><th>角色</th><th>角色名称</th></tr>";
    
    $admins = db()->query("SELECT id, username, role FROM users WHERE role >= 1 ORDER BY role DESC, id ASC");
    foreach ($admins as $admin) {
        $roleName = $admin['role'] == 2 ? '超级管理员' : '管理员';
        $color = $admin['role'] == 2 ? '#e74c3c' : '#3498db';
        echo "<tr>";
        echo "<td>" . $admin['id'] . "</td>";
        echo "<td>" . htmlspecialchars($admin['username']) . "</td>";
        echo "<td>" . $admin['role'] . "</td>";
        echo "<td style='color: " . $color . "; font-weight: bold;'>" . $roleName . "</td>";
        echo "</tr>";
    }
    echo "</table>";
    
} catch (Exception $e) {
    echo "<p style='color: red;'>错误: " . $e->getMessage() . "</p>";
}

echo "<hr>";
echo "<p><a href='index.php'>返回首页</a></p>";
