<?php
/** 唯一参数为站点根目录；创建待审批表并登记独立功能菜单，不保留调整/审批历史。 */
if(PHP_SAPI!=='cli')exit;
$root=$argv[1]??'D:/phpstudy_pro/WWW/cqoms.com';require rtrim($root,'/\\').'/vendor/autoload.php';$app=new \think\App(rtrim($root,'/\\').'/');$app->initialize();
use think\facade\Db;
$p=Db::connect()->getConfig('prefix');if(!preg_match('/^[A-Za-z0-9_]*$/D',$p))throw new RuntimeException('Invalid prefix');
Db::execute("CREATE TABLE IF NOT EXISTS `{$p}member_position_request` (
 id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, mid INT NOT NULL, tid INT NOT NULL, plan_id INT NOT NULL,
 from_poid INT NOT NULL, to_poid INT NOT NULL, fingerprint CHAR(64) NOT NULL, created_at INT NOT NULL,
 UNIQUE KEY idx_member(mid), KEY idx_team(tid,id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
// 兼容尚未升级菜单可见部门的旧库，先补字段再让 ORM 读取结构。
$columns=array_column(Db::query("SHOW COLUMNS FROM `{$p}admin_menus_wx`"),'Field');
if(!in_array('department_ids',$columns,true)){
    Db::execute("ALTER TABLE `{$p}admin_menus_wx` ADD COLUMN department_ids VARCHAR(500) NOT NULL DEFAULT '' COMMENT '可见部门ID，空为全部部门' AFTER user_types");
    echo "Added admin_menus_wx.department_ids.\n";
}
// 即使字段已存在，也可能残留添加字段之前的缓存；只清理这张表的结构缓存。
$c=Db::connect();$database=$c->getConfig('database');
if(!preg_match('/^[A-Za-z0-9_]+$/D',$database))throw new RuntimeException('Invalid database name');
$schemaFile=$c->getConfig('schema_cache_path').$database.'.'.$p.'admin_menus_wx.php';
if(is_file($schemaFile) && !unlink($schemaFile))throw new RuntimeException('Cannot clear menu schema cache: '.$schemaFile);
// 功能页读取数据库菜单；从独立入口进入时先识别管理权限，无权限则显示本人申请。
$action='memberPositions';
$route='/pages/tools-check/member-positions?mode=leader';
$menu=Db::name('admin_menus_wx')->where('action',$action)->find();
if($menu){
    // 已有菜单的可见范围、启停和排序交给管理端维护。
    Db::name('admin_menus_wx')->where('id',$menu['id'])->update(['title'=>'组员岗位设置','route'=>$route]);
}else{
    $sort=(int)Db::name('admin_menus_wx')->where('action','toolsCheck')->value('sort');
    Db::name('admin_menus_wx')->insert(['action'=>$action,'title'=>'组员岗位设置','route'=>$route,'icon'=>'user-group','icon_color'=>'#137E78','sort'=>$sort+1,'status'=>1,'user_types'=>'1,2,3','department_ids'=>'']);
}
echo "Pending position-request table and memberPositions menu ready; no employee positions changed.\n";
