<?php
/**
 * 安装两个抽奖流程图外链菜单，并授权超级管理员
 * 用法（在 server 目录）: php db/run_dice_flowcharts_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__ . '/dice_flowcharts_menu.sql', '1. 外链菜单');

$menuIds = Db::name('sa_system_menu')
    ->where('type', 4)
    ->whereIn('link_url', [
        '/docs/flowcharts/dice-为何抽到该奖励.html',
        '/docs/flowcharts/dice-后台中奖逻辑配置.html',
    ])
    ->column('id');

if ($menuIds === [] || $menuIds === null) {
    echo "错误：未找到流程图菜单\n";
    exit(1);
}

$menuIds = array_map('intval', $menuIds);
echo "\n流程图菜单 ID: " . implode(', ', $menuIds) . "\n";

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');
}

foreach ($adminRoleIds as $roleId) {
    $roleId = (int) $roleId;
    foreach ($menuIds as $menuId) {
        $exists = Db::name('sa_system_role_menu')
            ->where('role_id', $roleId)
            ->where('menu_id', $menuId)
            ->count();
        if ($exists > 0) {
            continue;
        }
        Db::name('sa_system_role_menu')->insert([
            'role_id' => $roleId,
            'menu_id' => $menuId,
        ]);
    }
    echo "角色 {$roleId} 已关联流程图菜单\n";
}

UserMenuCache::clearMenuCache();
echo "\n已清理菜单缓存。请重新登录后台或刷新页面查看侧边栏。\n";
echo "点击菜单将在新窗口打开 /docs/flowcharts/*.html\n";
