<?php
/**
 * 执行档位结算推荐配置菜单权限 SQL
 * 用法：在 server 目录执行 php db/run_dice_reward_config_tier_recommend_menu.php
 */
declare(strict_types=1);

define('BASE_PATH', dirname(__DIR__));

require_once BASE_PATH . '/vendor/autoload.php';

if (class_exists(\Dotenv\Dotenv::class) && is_file(BASE_PATH . '/.env')) {
    if (method_exists(\Dotenv\Dotenv::class, 'createUnsafeMutable')) {
        \Dotenv\Dotenv::createUnsafeMutable(BASE_PATH)->load();
    } else {
        \Dotenv\Dotenv::createMutable(BASE_PATH)->load();
    }
}

$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";
$pdo = new PDO($dsn, $user, $pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

$sqlFile = __DIR__ . '/dice_reward_config_tier_recommend_menu.sql';
$sql = file_get_contents($sqlFile);
$sql = preg_replace('/--.*$/m', '', $sql);
$parts = array_filter(array_map('trim', explode(';', $sql)));

echo "执行: dice_reward_config_tier_recommend_menu.sql\n";
echo "数据库: {$db} @ {$host}\n\n";

foreach ($parts as $statement) {
    if ($statement === '') {
        continue;
    }
    $pdo->exec($statement);
}

$row = $pdo->query(
    "SELECT id, parent_id, name, slug FROM sa_system_menu WHERE slug = 'dice:reward_config:index:tierRecommend' AND type = 3 LIMIT 1"
)->fetch(PDO::FETCH_ASSOC);

if ($row) {
    echo "成功：已写入菜单权限\n";
    echo "  id={$row['id']} parent_id={$row['parent_id']} name={$row['name']} slug={$row['slug']}\n";
} else {
    $parent = $pdo->query(
        "SELECT id, name, path FROM sa_system_menu WHERE type = 2 AND (path = 'reward_config' OR component LIKE '%reward_config%') ORDER BY id ASC LIMIT 1"
    )->fetch(PDO::FETCH_ASSOC);
    if ($parent === false) {
        echo "失败：未找到「奖励配置」父菜单 (type=2)，请先创建 reward_config 菜单\n";
        exit(1);
    }
    echo "警告：权限 slug 未查到（可能已存在但未插入）。父菜单: id={$parent['id']} path={$parent['path']}\n";
    exit(1);
}
