<?php

use App\Http\Controllers\Admin\ConfigController;
use App\Http\Controllers\Admin\ViewController;
use App\Http\Controllers\Api\AppController;
use App\Http\Controllers\Api\AttachmentController;
use App\Http\Controllers\Api\AttachmentGroupController;
use App\Http\Controllers\Api\AuthController;
use App\Http\Controllers\Api\ConfigGroupController;
use App\Http\Controllers\Api\ConfigItemController;
use App\Http\Controllers\Api\ContentCategoryController;
use App\Http\Controllers\Api\ContentController;
use App\Http\Controllers\Api\ContentModelController;
use App\Http\Controllers\Api\ContentModelFieldController;
use App\Http\Controllers\Api\DashboardController;
use App\Http\Controllers\Api\DatabaseController;
use App\Http\Controllers\Api\ServerInfoController;
use App\Http\Controllers\Api\LogController;
use App\Http\Controllers\Api\MenuController;
use App\Http\Controllers\Api\OperationLogController;
use App\Http\Controllers\Api\RoleController;
use App\Http\Controllers\Api\UserController;
use App\Http\Controllers\Api\FrontUserController;
use App\Http\Controllers\Api\UserAuthController;
use App\Http\Controllers\Api\UserGroupController;
use App\Http\Controllers\Api\AdminUserExtFieldController;
use App\Http\Controllers\Api\UserExtFieldController;
use App\Http\Controllers\User\ConfigController as UserConfigController;
use App\Http\Controllers\User\ViewController as UserViewController;
use Illuminate\Support\Facades\Route;

// 应用未启用时的兜底路由排除模式（排除已启用应用的 appId，避免拦截已注册的应用路由）
// 支持 旧格式（如 onlinepay）和新格式（如 cmspro.blog）
$excludePattern = '[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)?';
try {
    $enabledAppIds = \App\Models\AppModel::enabled()
        ->pluck('app_id')
        ->map(fn ($id) => preg_quote($id, '/'))
        ->implode('|');
    if ($enabledAppIds) {
        $excludePattern = '^(?!(?:' . $enabledAppIds . ')$)[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)?$';
    }
} catch (\Throwable) {
}

// 官网前端兜底路由（应用禁用时显示）
Route::get('/', function () {
    $homeMenus = \App\Models\AdminMenu::where('status', 1)
        ->where('visible', 1)
        ->where('terminal_type', 'home')
        ->orderBy('sort', 'asc')
        ->get(['id', 'parent_id', 'name', 'path', 'icon', 'sort', 'app_id', 'terminal_type']);

    return response()->view('home-disabled', compact('homeMenus'), 503);
})->name('home.disabled');

// 应用图标（公开，无需认证）
Route::get('/api/app/{appId}/icon', [AppController::class, 'icon']);

// 登录相关（公开）
Route::get('/admin/login', [ViewController::class, 'login'])->name('admin.login');
Route::post('/admin/login', [ViewController::class, 'loginSubmit'])->name('admin.login.submit');
Route::post('/admin/logout', [ViewController::class, 'logout'])->name('admin.logout');

// 前台用户认证（公开）
Route::prefix('api/user')->group(function () {
    Route::post('register', [UserAuthController::class, 'register']);
    Route::post('login', [UserAuthController::class, 'login']);
    Route::post('password/email-code', [UserAuthController::class, 'sendResetEmailCode']);
    Route::post('password/reset-by-code', [UserAuthController::class, 'resetPasswordByCode']);
});

// 前台用户认证（需登录）
Route::prefix('api/user')->middleware(['auth:web'])->group(function () {
    Route::post('logout', [UserAuthController::class, 'logout']);
    Route::get('info', [UserAuthController::class, 'info']);
    Route::put('profile', [UserAuthController::class, 'updateProfile']);
    Route::put('password', [UserAuthController::class, 'changePassword']);
});

// 用户端登录（公开）
Route::get('/user/login', [UserViewController::class, 'login'])->name('user.login');
Route::post('/user/login', [UserViewController::class, 'loginSubmit'])->name('user.login.submit');

// 用户端注册（公开）
Route::get('/user/register', [UserViewController::class, 'register'])->name('user.register');

// 用户端找回密码（公开）
Route::get('/user/forgot-password', [UserViewController::class, 'forgotPassword'])->name('user.forgot-password');

// 用户端（需要前台用户认证）
Route::prefix('user')->middleware(['auth:web'])->group(function () use ($excludePattern) {
    Route::get('/', [UserViewController::class, 'index'])->name('user.index');
    Route::get('/dashboard', [UserViewController::class, 'dashboard'])->name('user.dashboard');
    Route::get('/account', [UserViewController::class, 'accountIndex'])->name('user.account');
    Route::get('/account/password', [UserViewController::class, 'accountPassword'])->name('user.account.password');

    Route::get('/{appId}', [UserViewController::class, 'disabledApp'])
        ->where('appId', $excludePattern)
        ->name('user.app.disabled');
});

// 用户端 API（需要前台用户认证）
Route::prefix('api/user')->middleware(['auth:web'])->group(function () {
    Route::get('config.json', [UserConfigController::class, 'index']);
    Route::get('menus.json', [UserConfigController::class, 'menus']);
    Route::get('cache/clear', [UserConfigController::class, 'clearCache']);
});

// 管理后台（需要认证）
Route::prefix('admin')->middleware(['auth:admin'])->group(function () use ($excludePattern) {
    // 视图路由
    Route::get('/', [ViewController::class, 'index'])->name('admin.index');
    Route::get('/dashboard', [ViewController::class, 'dashboard'])->name('admin.dashboard');

    // 用户管理
    Route::get('/user', [ViewController::class, 'userIndex'])->name('admin.user.index');
    Route::get('/user/form', [ViewController::class, 'userForm'])->name('admin.user.form');

    // 角色管理
    Route::get('/role', [ViewController::class, 'roleIndex'])->name('admin.role.index');
    Route::get('/role/form', [ViewController::class, 'roleForm'])->name('admin.role.form');
    Route::get('/role/permissions', [ViewController::class, 'rolePermissions'])->name('admin.role.permissions');
    Route::get('/role/menus', [ViewController::class, 'roleMenus'])->name('admin.role.menus');

    // 菜单管理
    Route::get('/menu', [ViewController::class, 'menuIndex'])->name('admin.menu.index');
    Route::get('/menu/form', [ViewController::class, 'menuForm'])->name('admin.menu.form');
    Route::get('/menu/terminal', [ViewController::class, 'menuTerminal'])->name('admin.menu.terminal');
    Route::get('/menu/terminal-form', [ViewController::class, 'menuTerminalForm'])->name('admin.menu.terminal-form');

    // 账号管理
    Route::get('/account', [ViewController::class, 'accountIndex'])->name('admin.account');
    Route::get('/account/password', [ViewController::class, 'accountPassword'])->name('admin.account.password');

    // 系统配置
    Route::get('/config', [ViewController::class, 'configIndex'])->name('admin.config.index');

    // 系统设置
    Route::get('/setting', [ViewController::class, 'settingIndex'])->name('admin.setting.index');

    // 附件管理
    Route::get('/attachment', [ViewController::class, 'attachmentIndex'])->name('admin.attachment.index');

    // 系统日志
    Route::get('/log', [ViewController::class, 'logIndex'])->name('admin.log.index');

    // 环境信息
    Route::get('/environment', [ViewController::class, 'environmentIndex'])->name('admin.environment.index');
    Route::get('/environment/phpinfo', [ViewController::class, 'environmentPhpinfo'])->name('admin.environment.phpinfo');

    // 操作日志
    Route::get('/operation-log', [ViewController::class, 'operationLogIndex'])->name('admin.operation-log.index');

    // 数据管理
    Route::get('/database', [ViewController::class, 'databaseWelcome'])->name('admin.database.index');
    Route::get('/database/advanced', [ViewController::class, 'databaseAdvanced'])->name('admin.database.advanced');
    Route::get('/database/check/{table}', [ViewController::class, 'databaseCheck'])->name('admin.database.check');
    Route::get('/database/recover/{table}', [ViewController::class, 'databaseRecover'])->name('admin.database.recover');
    Route::get('/database/add-fields/{table}', [ViewController::class, 'databaseAddFields'])->name('admin.database.add-fields');
    Route::get('/database/edit-field/{table}', [ViewController::class, 'databaseEditField'])->name('admin.database.edit-field');
    Route::get('/database/table-add/{table}', [ViewController::class, 'databaseTableAdd'])->name('admin.database.table-add');
    Route::get('/database/table-edit/{table}', [ViewController::class, 'databaseTableEdit'])->name('admin.database.table-edit');
    Route::get('/database/table-copy/{table}', [ViewController::class, 'databaseTableCopy'])->name('admin.database.table-copy');

    // 内容管理
    Route::get('/content-category', [ViewController::class, 'categoryIndex'])->name('admin.content-category.index');
    Route::get('/content-category/form', [ViewController::class, 'categoryForm'])->name('admin.content-category.form');
    Route::get('/content-model', [ViewController::class, 'modelIndex'])->name('admin.content-model.index');
    Route::get('/content-model/form', [ViewController::class, 'modelForm'])->name('admin.content-model.form');
    Route::get('/content-model/design/{id}', [ViewController::class, 'modelDesign'])->name('admin.content-model.design');
    Route::get('/content', [ViewController::class, 'contentIndex'])->name('admin.content.index');
    Route::get('/content/form', [ViewController::class, 'contentForm'])->name('admin.content.form');

    // 应用管理
    Route::get('/app', [ViewController::class, 'appIndex'])->name('admin.app.index');
    Route::get('/app/market', [ViewController::class, 'appMarket'])->name('admin.app.market');
    Route::get('/app/log', [ViewController::class, 'appLog'])->name('admin.app.log');

    // 前台用户管理
    Route::get('/front-user', [ViewController::class, 'frontUserIndex'])->name('admin.front-user.index');
    Route::get('/front-user/form', [ViewController::class, 'frontUserForm'])->name('admin.front-user.form');
    Route::get('/user-group', [ViewController::class, 'userGroupIndex'])->name('admin.user-group.index');

    // 应用未启用时的兜底路由（必须在最后，作为所有未匹配路由的fallback）
    Route::get('/{appId}', [ViewController::class, 'disabledApp'])
        ->where('appId', $excludePattern)
        ->name('admin.app.disabled');
});

// 管理后台 API 路由（Session 认证 + 权限校验 + 操作日志记录）
Route::prefix('api/admin')->middleware(['auth:admin', 'permission', 'operation_log'])->group(function () {
    // 系统配置
    Route::get('config.json', [ConfigController::class, 'index']);
    Route::get('menus.json', [ConfigController::class, 'menus']);

    // 认证相关
    Route::post('auth/logout', [AuthController::class, 'logout']);
    Route::get('auth/user', [AuthController::class, 'user']);
    Route::put('auth/password', [AuthController::class, 'changePassword']);

    // 仪表盘
    Route::get('dashboard/stats', [DashboardController::class, 'stats']);

    // 服务器信息
    Route::get('server-info', [ServerInfoController::class, 'index']);
    Route::get('server-communication/check', [ServerInfoController::class, 'checkCommunication']);

    // 缓存清除
    Route::get('cache/clear', [ConfigController::class, 'clearCache']);

    // 用户管理
    Route::prefix('users')->controller(UserController::class)->group(function () {
        Route::get('/', 'index');
        Route::post('/', 'store');
        Route::get('all', 'all');
        Route::get('{id}', 'show');
        Route::put('{id}', 'update');
        Route::delete('{id}', 'destroy');
        Route::put('{id}/status', 'updateStatus');
        Route::put('{id}/reset-password', 'resetPassword');
        Route::post('batch-delete', 'batchDelete');
    });

    // 后台用户扩展字段管理
    Route::prefix('admin-user-ext-fields')->controller(AdminUserExtFieldController::class)->group(function () {
        Route::get('/', 'index');
        Route::post('/', 'store');
        Route::put('{id}', 'update');
        Route::delete('{id}', 'destroy');
    });

    // 角色管理
    Route::prefix('roles')->controller(RoleController::class)->group(function () {
        Route::get('/', 'index');
        Route::get('tree', 'tree');
        Route::get('all', 'all');
        Route::post('/', 'store');
        Route::get('{id}', 'show');
        Route::put('{id}', 'update');
        Route::delete('{id}', 'destroy');
        Route::put('{id}/status', 'updateStatus');
        Route::get('{id}/permissions', 'getPermissions');
        Route::put('{id}/permissions', 'updatePermissions');
        Route::get('{id}/menus', 'getMenus');
        Route::put('{id}/menus', 'updateMenus');
    });

    // 菜单管理
    Route::prefix('menus')->controller(MenuController::class)->group(function () {
        Route::get('/', 'index');
        Route::get('tree', 'tree');
        Route::get('user', 'user');
        Route::post('/', 'store');
        Route::put('sort', 'saveSort');

        // 终端管理（固定路径必须在 {id} 路由之前）
        Route::get('terminals', 'terminals');
        Route::post('terminals', 'storeTerminal');
        Route::put('terminals/sort', 'saveTerminalSort');
        Route::put('terminals/{id}', 'updateTerminal');
        Route::delete('terminals/{id}', 'destroyTerminal');
        Route::post('terminals/{id}/status', 'updateTerminalStatus');

        // 单条操作（必须在最后，作为兜底）
        Route::get('{id}', 'show');
        Route::put('{id}', 'update');
        Route::delete('{id}', 'destroy');
        Route::put('{id}/visible', 'updateVisible');
        Route::put('{id}/status', 'updateStatus');
    });

    // 日志管理
    Route::prefix('logs')->controller(LogController::class)->group(function () {
        Route::get('/', 'index');
        Route::get('read', 'read');
        Route::get('stats', 'stats');
        Route::get('download', 'download');
        Route::delete('destroy', 'destroy');
        Route::post('clear', 'clear');
    });

    // 操作日志
    Route::prefix('operation-logs')->controller(OperationLogController::class)->group(function () {
        Route::get('/', 'index');
        Route::get('modules', 'modules');
        Route::get('{id}', 'show');
        Route::delete('destroy', 'destroy');
        Route::post('clear', 'clear');
    });

    // 附件管理
    Route::prefix('attachments')->controller(AttachmentController::class)->group(function () {
        Route::get('/', 'index');
        Route::get('upload-config', 'uploadConfig');
        Route::post('upload', 'upload');
        Route::get('{id}', 'show');
        Route::delete('destroy', 'destroy');
        Route::put('move-group', 'moveGroup');
    });

    // 附件分组
    Route::prefix('attachment-groups')->controller(AttachmentGroupController::class)->group(function () {
        Route::get('/', 'index');
        Route::post('/', 'store');
        Route::put('{id}', 'update');
        Route::delete('{id}', 'destroy');
    });

    // 配置分组
    Route::prefix('config-groups')->controller(ConfigGroupController::class)->group(function () {
        Route::get('/', 'index');
        Route::post('/', 'store');
        Route::put('{id}', 'update');
        Route::delete('{id}', 'destroy');
    });

    // 配置项
    Route::prefix('config-items')->controller(ConfigItemController::class)->group(function () {
        Route::get('/', 'index');
        Route::post('/', 'store');
        Route::put('{id}', 'update');
        Route::delete('{id}', 'destroy');
        Route::post('batch', 'batch');
    });

    // 数据管理
    Route::prefix('database')->controller(DatabaseController::class)->group(function () {
        Route::get('list', 'list');
        Route::post('add-table', 'addTable');
        Route::post('edit-table', 'editTable');
        Route::post('copy-table', 'copyTable');
        Route::post('delete-table', 'deleteTable');
        Route::post('optimize', 'optimize');
        Route::post('repair', 'repair');
        Route::post('backup', 'backup');
        Route::post('recover-backup', 'recoverBackup');
        Route::post('delete-backup', 'deleteBackup');
        Route::get('{table}/structure', 'structure');
        Route::get('{table}/check', 'check');
        Route::post('{table}/table-add', 'tableAdd');
        Route::post('{table}/table-edit', 'tableEdit');
        Route::post('{table}/table-delete', 'tableDelete');
        Route::post('{table}/add-fields', 'addFields');
        Route::post('{table}/edit-field', 'editField');
        Route::post('{table}/delete-field', 'deleteField');
        Route::post('{table}/delete-fields', 'deleteFields');
        Route::post('{table}/field-index', 'fieldIndex');
        Route::get('{table}/backup-list', 'backupList');
    });

    // 内容分类
    Route::prefix('content-categories')->controller(ContentCategoryController::class)->group(function () {
        Route::get('/', 'index');
        Route::get('tree', 'tree');
        Route::post('/', 'store');
        Route::put('sort', 'saveSort');
        Route::get('{id}', 'show');
        Route::put('{id}', 'update');
        Route::delete('{id}', 'destroy');
        Route::put('{id}/status', 'updateStatus');
    });

    // 内容模型
    Route::prefix('content-models')->controller(ContentModelController::class)->group(function () {
        Route::get('/', 'index');
        Route::post('/', 'store');
        Route::put('sort', 'saveSort');
        Route::get('{id}', 'show');
        Route::put('{id}', 'update');
        Route::delete('{id}', 'destroy');
        Route::put('{id}/status', 'updateStatus');
    });

    // 模型字段（嵌套在模型下）
    Route::prefix('content-models')->controller(ContentModelFieldController::class)->group(function () {
        Route::get('{modelId}/fields', 'index');
        Route::post('{modelId}/fields', 'store');
    });

    // 模型字段（独立操作）
    Route::prefix('content-model-fields')->controller(ContentModelFieldController::class)->group(function () {
        Route::put('sort', 'saveSort');
        Route::put('{id}', 'update');
        Route::delete('{id}', 'destroy');
    });

    // 内容管理
    Route::prefix('contents')->controller(ContentController::class)->group(function () {
        Route::get('/', 'index');
        Route::get('form-config', 'formConfig');
        Route::post('/', 'store');
        Route::delete('batch', 'batchDelete');
        Route::get('{id}', 'show');
        Route::put('{id}', 'update');
        Route::delete('{id}', 'destroy');
        Route::put('{id}/status', 'updateStatus');
    });

    // 应用管理
    Route::prefix('apps')->controller(AppController::class)->group(function () {
        Route::get('/', 'index');
        Route::get('available', 'available');
        Route::post('upload', 'upload');
        Route::post('check-updates', 'checkUpdates');
        Route::post('{appId}/local-install', 'localInstall');
        Route::get('{appId}', 'show');
        Route::get('{appId}/export', 'export');
        Route::post('{appId}/install', 'install');
        Route::post('{appId}/uninstall', 'uninstall');
        Route::post('{appId}/delete', 'delete');
        Route::post('{appId}/enable', 'enable');
        Route::post('{appId}/disable', 'disable');
        Route::post('{appId}/upgrade', 'upgrade');
        Route::get('{appId}/config', 'getConfig');
        Route::put('{appId}/config', 'saveConfig');
        Route::get('{appId}/backups', 'backupList');
        Route::post('{appId}/backups/prepare', 'backupPrepare');
        Route::post('{appId}/backups/table', 'backupTable');
        Route::post('{appId}/backups/finish', 'backupFinish');
        Route::post('{appId}/backups', 'backupCreate');
        Route::get('backups/{backupId}/download', 'backupDownload');
        Route::post('backups/{backupId}/restore', 'backupRestore');
        Route::delete('backups/{backupId}', 'backupDelete');
        Route::post('{appId}/backups/import', 'backupImport');
        Route::post('{appId}/backups/upload-file', 'backupUploadFile');
        Route::get('{appId}/backups/local-files', 'backupLocalFiles');
        Route::post('{appId}/backups/import-local', 'backupImportLocal');
        Route::post('{appId}/backups/restore-prepare', 'restorePrepare');
        Route::post('{appId}/backups/restore-table', 'restoreTableStep');
        Route::post('{appId}/backups/restore-finish', 'restoreFinish');
    });

    // 应用市场
    Route::prefix('market')->controller(AppController::class)->group(function () {
        Route::get('apps', 'marketApps');
        Route::get('apps/{appId}', 'marketAppDetail');
        Route::post('install/{appId}', 'marketInstall');
        Route::get('categories', 'marketCategories');
        // 购买相关（系统级 API，远程调用 v5.cmspro.cn）
        Route::post('purchase/create', 'marketPurchaseCreate');
        Route::get('purchase/status', 'marketPurchaseStatus');
        Route::get('purchase/list', 'marketPurchaseList');
        // 站点注册
        Route::get('site/status', 'marketSiteStatus');
        Route::post('site/register', 'marketSiteRegister');
        Route::post('site/sync', 'marketSiteSync');
        // 站点身份验证（供 v5.cmspro.cn 反向调用，确认域名所有权）
        Route::get('site/verify-identity', 'marketSiteVerifyIdentity');
    });

    // 应用操作日志
    Route::prefix('app-logs')->controller(AppController::class)->group(function () {
        Route::get('/', 'logs');
    });

    // 前台用户管理
    Route::prefix('front-users')->controller(FrontUserController::class)->group(function () {
        Route::get('/', 'index');
        Route::post('/', 'store');
        Route::get('{id}', 'show');
        Route::put('{id}', 'update');
        Route::delete('{id}', 'destroy');
        Route::put('{id}/status', 'updateStatus');
        Route::put('{id}/reset-password', 'resetPassword');
        Route::post('batch-delete', 'batchDelete');
    });

    // 前台用户扩展字段管理
    Route::prefix('user-ext-fields')->controller(UserExtFieldController::class)->group(function () {
        Route::get('/', 'index');
        Route::post('/', 'store');
        Route::put('{id}', 'update');
        Route::delete('{id}', 'destroy');
    });

    // 用户组管理
    Route::prefix('user-groups')->controller(UserGroupController::class)->group(function () {
        Route::get('/', 'index');
        Route::post('/', 'store');
        Route::get('all', 'all');
        Route::get('{id}', 'show');
        Route::put('{id}', 'update');
        Route::delete('{id}', 'destroy');
    });
});
