<?php
/**
 * 安装「后台操作指南」菜单与权限，并授权给超级管理员角色
 * 用法（在 server 目录）: php db/run_system_admin_guide_menu.php
 */
declare(strict_types=1);

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../support/bootstrap.php';

use plugin\saiadmin\app\cache\UserMenuCache;
use support\think\Db;

function runSqlFile(PDO $pdo, string $path, string $label): void
{
    echo "\n=== {$label} ===\n";
    if (! is_file($path)) {
        echo "跳过：文件不存在 {$path}\n";
        return;
    }
    $sql = file_get_contents($path);
    $sql = preg_replace('/--.*$/m', '', $sql);
    $parts = array_filter(array_map('trim', explode(';', $sql)));
    $ok = 0;
    foreach ($parts as $statement) {
        if ($statement === '') {
            continue;
        }
        $pdo->exec($statement);
        $ok++;
    }
    echo "完成：执行 {$ok} 条语句\n";
}

function cliPdo(): PDO
{
    $host = getenv('DB_HOST') ?: '127.0.0.1';
    $port = getenv('DB_PORT') ?: '3306';
    $db = getenv('DB_NAME') ?: '';
    $user = getenv('DB_USER') ?: '';
    $pass = getenv('DB_PASSWORD') ?: '';
    $dsn = "mysql:host={$host};port={$port};dbname={$db};charset=utf8mb4";
    return new PDO($dsn, $user, $pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ]);
}

echo "========== 后台操作指南菜单安装 ==========\n";
echo '数据库: ' . (getenv('DB_NAME') ?: '') . '@' . (getenv('DB_HOST') ?: '') . "\n";

$pdo = cliPdo();
runSqlFile($pdo, __DIR__ . '/system_admin_guide_menu.sql', '1. 菜单与按钮权限');

$menuId = (int) Db::name('sa_system_menu')
    ->where('path', 'admin_guide')
    ->where('component', '/system/admin_guide/index')
    ->where('type', 2)
    ->value('id');

if ($menuId <= 0) {
    echo "错误：未找到后台操作指南菜单\n";
    exit(1);
}

$buttonIds = Db::name('sa_system_menu')
    ->where('parent_id', $menuId)
    ->where('type', 3)
    ->column('id');

$allMenuIds = array_values(array_unique(array_merge([$menuId], array_map('intval', $buttonIds ?: []))));

echo "\n=== 2. 授权超级管理员角色 ===\n";
$adminRoleIds = Db::name('sa_system_role')
    ->where('code', 'super_admin')
    ->column('id');

if ($adminRoleIds === [] || $adminRoleIds === null) {
    $adminRoleIds = Db::name('sa_system_role')->where('id', 1)->column('id');
}

$inserted = 0;
foreach ($adminRoleIds as $roleId) {
    $roleId = (int) $roleId;
    foreach ($allMenuIds as $mid) {
        $exists = Db::name('sa_system_role_menu')
            ->where('role_id', $roleId)
            ->where('menu_id', $mid)
            ->count();
        if ($exists > 0) {
            continue;
        }
        Db::name('sa_system_role_menu')->insert([
            'role_id' => $roleId,
            'menu_id' => $mid,
        ]);
        $inserted++;
    }
    echo "  角色 {$roleId}：新增授权 {$inserted} 条\n";
}

UserMenuCache::clearMenuCache();
\plugin\saiadmin\app\cache\UserAuthCache::clear();

echo "\n菜单 ID: {$menuId}\n";
echo "按钮权限: " . implode(',', $allMenuIds) . "\n";
echo "已清除菜单缓存，请重新登录后台查看。\n";
echo "========== 安装完成 ==========\n";
