<?php
/**
 * BuildAdmin Webman 路由
 * 根据 ThinkPHP pathinfo 规则（应用/控制器/方法）生成
 * GET=只读 POST=写入 ANY=兼容多种请求
 */

use Webman\Route;
use support\Response;

// ==================== 未安装时根路径重定向（迁移自 public/index.php） ====================
// 当 install.lock 不存在或未完成安装时，访问 / 或 /index.html 重定向到安装页
$installLockFile = public_path('install.lock');
$installCompleteMark = 'install-end';
$installPageFile = public_path('install/index.html');
Route::get('/', function () use ($installLockFile, $installCompleteMark, $installPageFile) {
    $needRedirect = is_file($installPageFile)
        && (!is_file($installLockFile) || @file_get_contents($installLockFile) !== $installCompleteMark);
    if ($needRedirect) {
        return new Response(302, ['Location' => '/install/']);
    }
    if (is_file(public_path('index.html'))) {
        return new Response(302, ['Location' => '/index.html']);
    }
    return new Response(404, [], 'Not Found');
});
Route::get('/index.html', function () use ($installLockFile, $installCompleteMark, $installPageFile) {
    $needRedirect = is_file($installPageFile)
        && (!is_file($installLockFile) || @file_get_contents($installLockFile) !== $installCompleteMark);
    if ($needRedirect) {
        return new Response(302, ['Location' => '/install/']);
    }
    $file = public_path('index.html');
    return is_file($file) ? (new Response())->file($file) : new Response(404, [], 'Not Found');
});

// ==================== 安装向导（静态页） ====================
// 已安装时访问 /install 重定向到应用，访问提示仅在终端显示
$installLockFileForInstall = public_path('install.lock');
$installCompleteMarkForInstall = 'install-end';
Route::get('/install', function () use ($installLockFileForInstall, $installCompleteMarkForInstall) {
    $installed = is_file($installLockFileForInstall) && @file_get_contents($installLockFileForInstall) === $installCompleteMarkForInstall;
    if ($installed && is_file(public_path('index.html'))) {
        return new Response(302, ['Location' => '/index.html']);
    }
    $file = public_path('install/index.html');
    return is_file($file) ? (new Response())->file($file) : new Response(404, [], 'Install page not found');
});
Route::get('/install/', function () use ($installLockFileForInstall, $installCompleteMarkForInstall) {
    $installed = is_file($installLockFileForInstall) && @file_get_contents($installLockFileForInstall) === $installCompleteMarkForInstall;
    if ($installed && is_file(public_path('index.html'))) {
        return new Response(302, ['Location' => '/index.html']);
    }
    $file = public_path('install/index.html');
    return is_file($file) ? (new Response())->file($file) : new Response(404, [], 'Install page not found');
});
Route::get('/install/index', function () use ($installLockFileForInstall, $installCompleteMarkForInstall) {
    $installed = is_file($installLockFileForInstall) && @file_get_contents($installLockFileForInstall) === $installCompleteMarkForInstall;
    if ($installed && is_file(public_path('index.html'))) {
        return new Response(302, ['Location' => '/index.html']);
    }
    $file = public_path('install/index.html');
    return is_file($file) ? (new Response())->file($file) : new Response(404, [], 'Install page not found');
});

// ==================== API 路由 ====================

// api/index
Route::get('/api/index/index', [\app\api\controller\Index::class, 'index']);

// api/v1
Route::get('/api/v1/authToken', [\app\api\controller\V1::class, 'authToken']);

// api/user（GET 获取配置，POST 登录/注册）
Route::add(['GET', 'POST'], '/api/user/checkIn', [\app\api\controller\User::class, 'checkIn']);
Route::post('/api/user/logout', [\app\api\controller\User::class, 'logout']);

// api/install（安装流程多为 POST）
Route::add(['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD'], '/api/install/terminal', [\app\api\controller\Install::class, 'terminal']);
Route::post('/api/install/changePackageManager', [\app\api\controller\Install::class, 'changePackageManager']);
Route::get('/api/install/envBaseCheck', [\app\api\controller\Install::class, 'envBaseCheck']);
Route::add(['GET', 'POST'], '/api/install/envNpmCheck', [\app\api\controller\Install::class, 'envNpmCheck']);
Route::post('/api/install/testDatabase', [\app\api\controller\Install::class, 'testDatabase']);
Route::add(['GET', 'POST'], '/api/install/baseConfig', [\app\api\controller\Install::class, 'baseConfig']);
Route::get('/api/install/accessUrls', [\app\api\controller\Install::class, 'accessUrls']);
Route::post('/api/install/commandExecComplete', [\app\api\controller\Install::class, 'commandExecComplete']);
Route::post('/api/install/manualInstall', [\app\api\controller\Install::class, 'manualInstall']);
Route::post('/api/install/mvDist', [\app\api\controller\Install::class, 'mvDist']);

// api/common
Route::get('/api/common/captcha', [\app\api\controller\Common::class, 'captcha']);
Route::get('/api/common/clickCaptcha', [\app\api\controller\Common::class, 'clickCaptcha']);
Route::post('/api/common/checkClickCaptcha', [\app\api\controller\Common::class, 'checkClickCaptcha']);
Route::post('/api/common/refreshToken', [\app\api\controller\Common::class, 'refreshToken']);

// api/ajax
Route::post('/api/ajax/upload', [\app\api\controller\Ajax::class, 'upload']);
Route::get('/api/ajax/area', [\app\api\controller\Ajax::class, 'area']);
Route::get('/api/ajax/buildSuffixSvg', [\app\api\controller\Ajax::class, 'buildSuffixSvg']);

// api/account
Route::get('/api/account/overview', [\app\api\controller\Account::class, 'overview']);
Route::add(['GET', 'POST'], '/api/account/profile', [\app\api\controller\Account::class, 'profile']);
Route::get('/api/account/verification', [\app\api\controller\Account::class, 'verification']);
Route::post('/api/account/changeBind', [\app\api\controller\Account::class, 'changeBind']);
Route::add(['GET', 'POST'], '/api/account/changePassword', [\app\api\controller\Account::class, 'changePassword']);
Route::get('/api/account/integral', [\app\api\controller\Account::class, 'integral']);
Route::get('/api/account/balance', [\app\api\controller\Account::class, 'balance']);
Route::post('/api/account/retrievePassword', [\app\api\controller\Account::class, 'retrievePassword']);

// api/ems
Route::post('/api/ems/send', [\app\api\controller\Ems::class, 'send']);

// ==================== 移动端用户接口（统一收口到 /api/user/*） ====================
// 约定：移动端所有业务接口一律使用 POST 调用；查询类同时兼容 GET 便于浏览器调试。
Route::post('/api/user/register', [\app\api\controller\Auth::class, 'userRegister']);
Route::post('/api/user/login', [\app\api\controller\Auth::class, 'userLogin']);
Route::post('/api/user/refreshToken', [\app\api\controller\Auth::class, 'tokenRefresh']);
Route::add(['GET', 'POST'], '/api/user/profile', [\app\api\controller\Account::class, 'userProfile']);
Route::post('/api/user/retrievePassword', [\app\api\controller\Account::class, 'retrievePassword']);

// 兼容旧移动端路径，后续客户端切换完成后可移除
Route::post('/api/auth/userRegister', [\app\api\controller\Auth::class, 'userRegister']);
Route::post('/api/auth/userLogin', [\app\api\controller\Auth::class, 'userLogin']);
Route::post('/api/auth/tokenRefresh', [\app\api\controller\Auth::class, 'tokenRefresh']);
Route::add(['GET', 'POST'], '/api/account/userProfile', [\app\api\controller\Account::class, 'userProfile']);

Route::add(['GET', 'POST'], '/api/game/lobbyInit', [\app\api\controller\Game::class, 'lobbyInit']);
Route::add(['GET', 'POST'], '/api/game/dictionaryList', [\app\api\controller\Game::class, 'dictionaryList']);
Route::add(['GET', 'POST'], '/api/game/periodCurrent', [\app\api\controller\Game::class, 'periodCurrent']);
Route::post('/api/game/betPlace', [\app\api\controller\Game::class, 'betPlace']);
Route::add(['GET', 'POST'], '/api/game/betMyOrders', [\app\api\controller\Game::class, 'betMyOrders']);
Route::post('/api/game/placeBet', [\app\api\controller\Game::class, 'placeBet']);
Route::post('/api/game/autoSpin', [\app\api\controller\Game::class, 'autoSpin']);

Route::add(['GET', 'POST'], '/api/wallet/recordList', [\app\api\controller\Wallet::class, 'recordList']);

Route::add(['GET', 'POST'], '/api/finance/depositTierList', [\app\api\controller\Finance::class, 'depositTierList']);
Route::post('/api/finance/depositCreate', [\app\api\controller\Finance::class, 'depositCreate']);
Route::add(['GET', 'POST'], '/api/finance/mockDepositPage', [\app\api\controller\Finance::class, 'mockDepositPage']);
Route::add(['GET', 'POST'], '/api/finance/mockDepositStatus', [\app\api\controller\Finance::class, 'mockDepositStatus']);
Route::add(['GET', 'POST'], '/api/finance/mockDepositConfirm', [\app\api\controller\Finance::class, 'mockDepositConfirm']);
Route::add(['GET', 'POST'], '/api/finance/mockDepositPay', [\app\api\controller\Finance::class, 'mockDepositPay']);
Route::post('/api/finance/ddpayDepositNotify', [\app\api\controller\Finance::class, 'ddpayDepositNotify']);
Route::add(['GET', 'POST'], '/api/finance/ddpayDepositRedirect', [\app\api\controller\Finance::class, 'ddpayDepositRedirect']);
Route::post('/api/finance/ddpayPayoutNotify', [\app\api\controller\Finance::class, 'ddpayPayoutNotify']);
Route::add(['GET', 'POST'], '/api/finance/depositDetail', [\app\api\controller\Finance::class, 'depositDetail']);
Route::add(['GET', 'POST'], '/api/finance/depositList', [\app\api\controller\Finance::class, 'depositList']);
Route::add(['GET', 'POST'], '/api/finance/cashierConfig', [\app\api\controller\Finance::class, 'cashierConfig']);
Route::add(['GET', 'POST'], '/api/finance/depositWithdrawConfig', [\app\api\controller\Finance::class, 'depositWithdrawConfig']);
Route::post('/api/finance/withdrawCreate', [\app\api\controller\Finance::class, 'withdrawCreate']);
Route::add(['GET', 'POST'], '/api/finance/withdrawDetail', [\app\api\controller\Finance::class, 'withdrawDetail']);
Route::add(['GET', 'POST'], '/api/finance/withdrawList', [\app\api\controller\Finance::class, 'withdrawList']);

Route::get('/api/notice/noticeList', [\app\api\controller\Notice::class, 'noticeList']);
Route::get('/api/notice/noticeConfirm', [\app\api\controller\Notice::class, 'noticeConfirm']);

// ==================== Admin 路由 ====================
// Admin 多为 JSON API，前端可能用 GET 传参查列表、POST 提交表单，使用 any 确保兼容

// admin/index（小写）
Route::get('/admin/index/index', [\app\admin\controller\Index::class, 'index']);
Route::get('/admin/index/login', [\app\admin\controller\Index::class, 'login']);
Route::post('/admin/index/login', [\app\admin\controller\Index::class, 'login']);
Route::post('/admin/index/logout', [\app\admin\controller\Index::class, 'logout']);

// 兼容前端请求 /admin/Index/*（首字母大写）
Route::get('/admin/Index/index', [\app\admin\controller\Index::class, 'index']);
Route::get('/admin/Index/login', [\app\admin\controller\Index::class, 'login']);
Route::post('/admin/Index/login', [\app\admin\controller\Index::class, 'login']);
Route::post('/admin/Index/logout', [\app\admin\controller\Index::class, 'logout']);

// admin/dashboard
Route::get('/admin/dashboard/index', [\app\admin\controller\Dashboard::class, 'index']);
// 兼容前端请求 /admin/Dashboard/*
Route::get('/admin/Dashboard/index', [\app\admin\controller\Dashboard::class, 'index']);

// admin/module
Route::get('/admin/module/index', [\app\admin\controller\Module::class, 'index']);
Route::get('/admin/module/state', [\app\admin\controller\Module::class, 'state']);
Route::post('/admin/module/install', [\app\admin\controller\Module::class, 'install']);
Route::post('/admin/module/dependentInstallComplete', [\app\admin\controller\Module::class, 'dependentInstallComplete']);
Route::post('/admin/module/changeState', [\app\admin\controller\Module::class, 'changeState']);
Route::post('/admin/module/uninstall', [\app\admin\controller\Module::class, 'uninstall']);
Route::post('/admin/module/upload', [\app\admin\controller\Module::class, 'upload']);

// admin/ajax
Route::post('/admin/ajax/upload', [\app\admin\controller\Ajax::class, 'upload']);
Route::get('/admin/ajax/area', [\app\admin\controller\Ajax::class, 'area']);
Route::get('/admin/ajax/buildSuffixSvg', [\app\admin\controller\Ajax::class, 'buildSuffixSvg']);
Route::get('/admin/ajax/getDatabaseConnectionList', [\app\admin\controller\Ajax::class, 'getDatabaseConnectionList']);
Route::get('/admin/ajax/getTablePk', [\app\admin\controller\Ajax::class, 'getTablePk']);
Route::get('/admin/ajax/getTableList', [\app\admin\controller\Ajax::class, 'getTableList']);
Route::get('/admin/ajax/getTableFieldList', [\app\admin\controller\Ajax::class, 'getTableFieldList']);
Route::post('/admin/ajax/changeTerminalConfig', [\app\admin\controller\Ajax::class, 'changeTerminalConfig']);
Route::post('/admin/ajax/clearCache', [\app\admin\controller\Ajax::class, 'clearCache']);
Route::add(['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD'], '/admin/ajax/terminal', [\app\admin\controller\Ajax::class, 'terminal']);

// admin/auth/admin
Route::get('/admin/auth/admin/index', [\app\admin\controller\auth\Admin::class, 'index']);
Route::post('/admin/auth/admin/add', [\app\admin\controller\auth\Admin::class, 'add']);
Route::post('/admin/auth/admin/edit', [\app\admin\controller\auth\Admin::class, 'edit']);
Route::post('/admin/auth/admin/del', [\app\admin\controller\auth\Admin::class, 'del']);

// admin/auth/group
Route::get('/admin/auth/group/index', [\app\admin\controller\auth\Group::class, 'index']);
Route::post('/admin/auth/group/add', [\app\admin\controller\auth\Group::class, 'add']);
Route::post('/admin/auth/group/edit', [\app\admin\controller\auth\Group::class, 'edit']);
Route::post('/admin/auth/group/del', [\app\admin\controller\auth\Group::class, 'del']);
Route::get('/admin/auth/group/select', [\app\admin\controller\auth\Group::class, 'select']);

// admin/auth/rule
Route::get('/admin/auth/rule/index', [\app\admin\controller\auth\Rule::class, 'index']);
Route::post('/admin/auth/rule/add', [\app\admin\controller\auth\Rule::class, 'add']);
Route::post('/admin/auth/rule/edit', [\app\admin\controller\auth\Rule::class, 'edit']);
Route::post('/admin/auth/rule/del', [\app\admin\controller\auth\Rule::class, 'del']);
Route::get('/admin/auth/rule/select', [\app\admin\controller\auth\Rule::class, 'select']);

// admin/auth/adminLog
Route::get('/admin/auth/adminLog/index', [\app\admin\controller\auth\AdminLog::class, 'index']);

// admin/routine/config
Route::get('/admin/routine/config/index', [\app\admin\controller\routine\Config::class, 'index']);
Route::post('/admin/routine/config/edit', [\app\admin\controller\routine\Config::class, 'edit']);
Route::post('/admin/routine/config/add', [\app\admin\controller\routine\Config::class, 'add']);
Route::post('/admin/routine/config/sendTestMail', [\app\admin\controller\routine\Config::class, 'sendTestMail']);

// admin/routine/adminInfo
Route::get('/admin/routine/adminInfo/index', [\app\admin\controller\routine\AdminInfo::class, 'index']);
Route::post('/admin/routine/adminInfo/edit', [\app\admin\controller\routine\AdminInfo::class, 'edit']);

// admin/routine/attachment
Route::post('/admin/routine/attachment/del', [\app\admin\controller\routine\Attachment::class, 'del']);

// admin/crud/crud
Route::post('/admin/crud/crud/generate', [\app\admin\controller\crud\Crud::class, 'generate']);
Route::post('/admin/crud/crud/logStart', [\app\admin\controller\crud\Crud::class, 'logStart']);
Route::post('/admin/crud/crud/delete', [\app\admin\controller\crud\Crud::class, 'delete']);
Route::get('/admin/crud/crud/getFileData', [\app\admin\controller\crud\Crud::class, 'getFileData']);
// 兼容 ThinkPHP 风格 URL：/admin/crud.Crud/getFileData
Route::get('/admin/crud.Crud/getFileData', [\app\admin\controller\crud\Crud::class, 'getFileData']);
Route::get('/admin/crud/crud/checkCrudLog', [\app\admin\controller\crud\Crud::class, 'checkCrudLog']);
Route::post('/admin/crud/crud/parseFieldData', [\app\admin\controller\crud\Crud::class, 'parseFieldData']);
Route::post('/admin/crud/crud/generateCheck', [\app\admin\controller\crud\Crud::class, 'generateCheck']);
Route::post('/admin/crud/crud/uploadCompleted', [\app\admin\controller\crud\Crud::class, 'uploadCompleted']);

// admin/crud/log
Route::get('/admin/crud/log/index', [\app\admin\controller\crud\Log::class, 'index']);

// admin/security/sensitiveData
Route::get('/admin/security/sensitiveData/index', [\app\admin\controller\security\SensitiveData::class, 'index']);
Route::add(['GET', 'POST'], '/admin/security/sensitiveData/add', [\app\admin\controller\security\SensitiveData::class, 'add']);
Route::add(['GET', 'POST'], '/admin/security/sensitiveData/edit', [\app\admin\controller\security\SensitiveData::class, 'edit']);
Route::post('/admin/security/sensitiveData/del', [\app\admin\controller\security\SensitiveData::class, 'del']);

// admin/security/sensitiveDataLog
Route::get('/admin/security/sensitiveDataLog/index', [\app\admin\controller\security\SensitiveDataLog::class, 'index']);
Route::get('/admin/security/sensitiveDataLog/info', [\app\admin\controller\security\SensitiveDataLog::class, 'info']);
Route::post('/admin/security/sensitiveDataLog/rollback', [\app\admin\controller\security\SensitiveDataLog::class, 'rollback']);

// admin/security/dataRecycle
Route::get('/admin/security/dataRecycle/index', [\app\admin\controller\security\DataRecycle::class, 'index']);
Route::add(['GET', 'POST'], '/admin/security/dataRecycle/add', [\app\admin\controller\security\DataRecycle::class, 'add']);
Route::add(['GET', 'POST'], '/admin/security/dataRecycle/edit', [\app\admin\controller\security\DataRecycle::class, 'edit']);
Route::post('/admin/security/dataRecycle/del', [\app\admin\controller\security\DataRecycle::class, 'del']);

// admin/security/dataRecycleLog
Route::get('/admin/security/dataRecycleLog/index', [\app\admin\controller\security\DataRecycleLog::class, 'index']);
Route::post('/admin/security/dataRecycleLog/restore', [\app\admin\controller\security\DataRecycleLog::class, 'restore']);
Route::get('/admin/security/dataRecycleLog/info', [\app\admin\controller\security\DataRecycleLog::class, 'info']);

// admin/config/depositTier
Route::get('/admin/config/depositTier/currencyOptions', [\app\admin\controller\config\DepositTier::class, 'currencyOptions']);

// ==================== CRUD 生成的根级控制器（/admin/item/index 或 /admin/Item/index，无子目录、无点号） ====================
// 显式路由在上，此处作为兜底；与 /admin/module.controller/action 互补
Route::add(
    ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD'],
    '/admin/{controller:[a-zA-Z][a-zA-Z0-9]*}/{action}',
    function (\Webman\Http\Request $request, string $controller, string $action) {
        $class = '\\app\\admin\\controller\\' . ucfirst(strtolower($controller));
        if (!class_exists($class)) {
            return new Response(404, ['Content-Type' => 'application/json'], json_encode(['code' => 404, 'msg' => '404 Not Found', 'data' => []], JSON_UNESCAPED_UNICODE));
        }
        if (!method_exists($class, $action)) {
            return new Response(404, ['Content-Type' => 'application/json'], json_encode(['code' => 404, 'msg' => '404 Not Found', 'data' => []], JSON_UNESCAPED_UNICODE));
        }
        $request->controller = $class;
        try {
            $instance = new $class();
            return $instance->$action($request);
        } catch (\Throwable $e) {
            return new Response(500, ['Content-Type' => 'application/json'], json_encode([
                'code' => 0,
                'msg'  => $e->getMessage(),
                'time' => time(),
                'data' => null,
            ], JSON_UNESCAPED_UNICODE));
        }
    }
);

// ==================== 兼容 ThinkPHP 风格 URL（module.Controller/action） ====================
// 前端使用 /admin/user.Rule/index 格式，需转换为控制器调用
Route::add(
    ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD'],
    '/admin/{controllerPart:[a-zA-Z]+\\.[a-zA-Z0-9]+}/{action}',
    function (\Webman\Http\Request $request, string $controllerPart, string $action) {
        $pos = strpos($controllerPart, '.');
        if ($pos === false) {
            return new Response(404, ['Content-Type' => 'application/json'], json_encode(['code' => 404, 'msg' => '404 Not Found', 'data' => []], JSON_UNESCAPED_UNICODE));
        }
        $module = substr($controllerPart, 0, $pos);
        $controller = substr($controllerPart, $pos + 1);
        $class = '\\app\\admin\\controller\\' . strtolower($module) . '\\' . $controller;
        if (!class_exists($class)) {
            return new Response(404, ['Content-Type' => 'application/json'], json_encode(['code' => 404, 'msg' => '404 Not Found', 'data' => []], JSON_UNESCAPED_UNICODE));
        }
        if (!method_exists($class, $action)) {
            return new Response(404, ['Content-Type' => 'application/json'], json_encode(['code' => 404, 'msg' => '404 Not Found', 'data' => []], JSON_UNESCAPED_UNICODE));
        }
        // 设置 controller 供 get_controller_path、权限校验等使用
        $request->controller = $class;
        try {
            $instance = new $class();
            return $instance->$action($request);
        } catch (\Throwable $e) {
            return new Response(500, ['Content-Type' => 'application/json'], json_encode([
                'code' => 0,
                'msg'  => $e->getMessage(),
                'time' => time(),
                'data' => null,
            ], JSON_UNESCAPED_UNICODE));
        }
    }
);

// ==================== CORS 预检（OPTIONS） ====================
// 放在最后注册；显式加上前端会请求的路径，再加固通配
Route::add('OPTIONS', '/api/index/index', [\app\common\middleware\AllowCrossDomain::class, 'optionsResponse']);
Route::add('OPTIONS', '/api/{path:.+}', [\app\common\middleware\AllowCrossDomain::class, 'optionsResponse']);
Route::add('OPTIONS', '/admin/{path:.+}', [\app\common\middleware\AllowCrossDomain::class, 'optionsResponse']);