<?php

use App\Http\Controllers\Admin\AccountController as AdminAccountController;
use App\Http\Controllers\Admin\AiSettingsController;
use App\Http\Controllers\Admin\AnnouncementController as AdminAnnouncementController;
use App\Http\Controllers\Admin\ApacheConfigController as AdminApacheConfigController;
use App\Http\Controllers\Admin\ApiDocsController as AdminApiDocsController;
use App\Http\Controllers\Admin\ApiTesterController;
use App\Http\Controllers\Admin\ApiTokenController as AdminApiTokenController;
use App\Http\Controllers\Admin\AuditController as AdminAuditController;
use App\Http\Controllers\Admin\BackupConfigController as AdminBackupConfigController;
use App\Http\Controllers\Admin\BackupController as AdminBackupController;
use App\Http\Controllers\Admin\BandwidthController as AdminBandwidthController;
use App\Http\Controllers\Admin\BrandingController as AdminBrandingController;
use App\Http\Controllers\Admin\BulkAccountController as AdminBulkAccountController;
use App\Http\Controllers\Admin\ClusterController as AdminClusterController;
use App\Http\Controllers\Admin\CpanelMigrationController as AdminCpanelMigrationController;
use App\Http\Controllers\Admin\DashboardController as AdminDashboardController;
use App\Http\Controllers\Admin\DkimManagerController as AdminDkimManagerController;
use App\Http\Controllers\Admin\DovecotConfigController as AdminDovecotConfigController;
use App\Http\Controllers\Admin\EmailTemplateController as AdminEmailTemplateController;
use App\Http\Controllers\Admin\Fail2banController as AdminFail2banController;
use App\Http\Controllers\Admin\FirewallController as AdminFirewallController;
use App\Http\Controllers\Admin\HealthController as AdminHealthController;
use App\Http\Controllers\Admin\ImpersonateController as AdminImpersonateController;
// use App\Http\Controllers\Admin\KbController as AdminKbController; // Kaldırıldı (WHM-style değil — eklenti entegrasyonu için)
use App\Http\Controllers\Admin\LicenseController;
use App\Http\Controllers\Admin\LogsController as AdminLogsController;
use App\Http\Controllers\Admin\MailQueueController as AdminMailQueueController;
use App\Http\Controllers\Admin\MailReportsController as AdminMailReportsController;
use App\Http\Controllers\Admin\MaintenanceModeController as AdminMaintenanceModeController;
use App\Http\Controllers\Admin\ModSecurityController as AdminModSecurityController;
use App\Http\Controllers\Admin\MonitoringController as AdminMonitoringController;
use App\Http\Controllers\Admin\CronAuditController as AdminCronAuditController;
use App\Http\Controllers\Admin\EmailDeliverabilityController as AdminEmailDeliverabilityController;
use App\Http\Controllers\Admin\FpmPoolController as AdminFpmPoolController;
use App\Http\Controllers\Admin\MultiPhpController as AdminMultiPhpController;
use App\Http\Controllers\Admin\MysqlAdminController as AdminMysqlAdminController;
use App\Http\Controllers\Admin\MysqlServerConfigController as AdminMysqlServerConfigController;
use App\Http\Controllers\Admin\NetworkController as AdminNetworkController;
use App\Http\Controllers\Admin\OutboundWebhookController as AdminOutboundWebhookController;
use App\Http\Controllers\Admin\PackageController as AdminPackageController;
use App\Http\Controllers\Admin\DbVersionController as AdminDbVersionController;
use App\Http\Controllers\Admin\PhpExtensionController as AdminPhpExtensionController;
use App\Http\Controllers\Admin\PhpSystemController as AdminPhpSystemController;
use App\Http\Controllers\Admin\PluginController;
use App\Http\Controllers\Admin\PostfixConfigController as AdminPostfixConfigController;
use App\Http\Controllers\Admin\ProcessController as AdminProcessController;
use App\Http\Controllers\Admin\ReplicationController as AdminReplicationController;
use App\Http\Controllers\Admin\ResellerController as AdminResellerController;
use App\Http\Controllers\Admin\ResourceUsageController as AdminResourceUsageController;
use App\Http\Controllers\Admin\RspamdConfigController as AdminRspamdConfigController;
use App\Http\Controllers\Admin\ServiceController as AdminServiceController;
use App\Http\Controllers\Admin\DnsNameserversController as AdminDnsNameserversController;
use App\Http\Controllers\Admin\SettingsController as AdminSettingsController;
use App\Http\Controllers\Admin\WebServerController as AdminWebServerController;
use App\Http\Controllers\Admin\MailServerController as AdminMailServerController;
use App\Http\Controllers\Admin\MailMigrationController as AdminMailMigrationController;
use App\Http\Controllers\Admin\MailStackController as AdminMailStackController;
use App\Http\Controllers\Admin\MailStorageController as AdminMailStorageController;
use App\Http\Controllers\Admin\MailingListController as AdminMailingListController;
use App\Http\Controllers\Admin\IntegrationsController as AdminIntegrationsController;
use App\Http\Controllers\Admin\SetupWizardController as AdminSetupWizardController;
use App\Http\Controllers\Admin\SnapshotController as AdminSnapshotController;
use App\Http\Controllers\Admin\SslManagerController as AdminSslManagerController;
use App\Http\Controllers\Admin\StatusManagerController as AdminStatusManagerController;
// use App\Http\Controllers\Admin\TicketController as AdminTicketController; // Kaldırıldı
use App\Http\Controllers\Admin\UpdateManagerController as AdminUpdateManagerController;
use App\Http\Controllers\Admin\WebhookPlaygroundController;
use App\Http\Controllers\Api\MetricsController;
use App\Http\Controllers\Auth\SsoController;
use App\Http\Controllers\Customer\AccountController as CustomerAccountController;
use App\Http\Controllers\Customer\AiAssistantController;
use App\Http\Controllers\Customer\ApiTokenController as CustomerApiTokenController;
use App\Http\Controllers\Customer\AppInstallerController as CustomerAppInstallerController;
use App\Http\Controllers\Customer\BackupController as CustomerBackupController;
use App\Http\Controllers\Customer\BandwidthController as CustomerBandwidthController;
use App\Http\Controllers\Customer\BoxTrapperController as CustomerBoxTrapperController;
use App\Http\Controllers\Customer\CronController as CustomerCronController;
use App\Http\Controllers\Customer\DashboardController as CustomerDashboardController;
use App\Http\Controllers\Customer\DatabaseController as CustomerDatabaseController;
use App\Http\Controllers\Customer\DiskUsageController as CustomerDiskUsageController;
use App\Http\Controllers\Customer\ResourceUsageController as CustomerResourceUsageController;
use App\Http\Controllers\Customer\DnsController as CustomerDnsController;
use App\Http\Controllers\Customer\DomainAliasController as CustomerDomainAliasController;
use App\Http\Controllers\Customer\DomainController as CustomerDomainController;
use App\Http\Controllers\Customer\PhpErrorLogController as CustomerPhpErrorLogController;
use App\Http\Controllers\Customer\EmailController as CustomerEmailController;
use App\Http\Controllers\Customer\EmailDefaultAddressController as CustomerEmailDefaultAddressController;
use App\Http\Controllers\Customer\EmailDeliverabilityController as CustomerEmailDeliverabilityController;
use App\Http\Controllers\Customer\EmailDiskUsageController as CustomerEmailDiskUsageController;
use App\Http\Controllers\Customer\EmailImporterController as CustomerEmailImporterController;
use App\Http\Controllers\Customer\EmailRoutingController as CustomerEmailRoutingController;
use App\Http\Controllers\Customer\EmailTrackingController as CustomerEmailTrackingController;
use App\Http\Controllers\Customer\FileController as CustomerFileController;
use App\Http\Controllers\Customer\FtpController as CustomerFtpController;
use App\Http\Controllers\Customer\GitController as CustomerGitController;
use App\Http\Controllers\Customer\GpgKeyController as CustomerGpgKeyController;
use App\Http\Controllers\Customer\ImageController as CustomerImageController;
use App\Http\Controllers\Customer\IndexManagerController as CustomerIndexManagerController;
use App\Http\Controllers\Customer\LeechProtectionController as CustomerLeechProtectionController;
use App\Http\Controllers\Customer\MailingListController as CustomerMailingListController;
use App\Http\Controllers\Customer\MailSetupController as CustomerMailSetupController;
use App\Http\Controllers\Customer\MimeTypesController as CustomerMimeTypesController;
use App\Http\Controllers\Customer\ModSecurityController as CustomerModSecurityController;
use App\Http\Controllers\Customer\OptimizeWebsiteController as CustomerOptimizeWebsiteController;
use App\Http\Controllers\Customer\PhpController as CustomerPhpController;
use App\Http\Controllers\Customer\PushSubscriptionController;
use App\Http\Controllers\Customer\RedirectController as CustomerRedirectController;
use App\Http\Controllers\Customer\SecurityController as CustomerSecurityController;
use App\Http\Controllers\Customer\SnapshotController as CustomerSnapshotController;
use App\Http\Controllers\Customer\SpamFilterController as CustomerSpamFilterController;
use App\Http\Controllers\Customer\SslController as CustomerSslController;
use App\Http\Controllers\Customer\StatsController as CustomerStatsController;
use App\Http\Controllers\Customer\SubdomainController as CustomerSubdomainController;
// use App\Http\Controllers\Customer\TicketController as CustomerTicketController; // Kaldırıldı
use App\Http\Controllers\Customer\TwoFactorController as CustomerTwoFactorController;
use App\Http\Controllers\Customer\WebdiskController as CustomerWebdiskController;
use App\Http\Controllers\Customer\WebmailController as CustomerWebmailController;
use App\Http\Controllers\Customer\WordPressToolkitController as CustomerWordPressToolkitController;
// use App\Http\Controllers\HelpCenterController; // Kaldırıldı
use App\Http\Controllers\LocaleController;
use App\Http\Controllers\NotificationController;
use App\Http\Controllers\OnboardingController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\Public\AutoconfigController as PublicAutoconfigController;
use App\Http\Controllers\Public\StatusPageController as PublicStatusPageController;
use App\Http\Controllers\Reseller\AccountsController as ResellerAccountsController;
use App\Http\Controllers\Reseller\BrandingController as ResellerBrandingController;
use App\Http\Controllers\Reseller\DashboardController as ResellerDashboardController;
use App\Http\Controllers\Reseller\RevenueController as ResellerRevenueController;
use App\Http\Controllers\Reseller\SubPackagesController as ResellerSubPackagesController;
use App\Http\Controllers\WebhookInboxController;
use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;

// ── i18n locale switcher ──────────────────────────────────────────────────────────────
Route::post('/api/locale', [LocaleController::class, 'update'])->name('locale.update');

// ── Public Status Page — no auth required ────────────────────────────────────────────
Route::get('/status', [PublicStatusPageController::class, 'index'])->name('status.index');
Route::get('/status.json', [PublicStatusPageController::class, 'jsonApi'])->name('status.api');
Route::get('/status.rss', [PublicStatusPageController::class, 'rss'])->name('status.rss');

// ── WHMCS SSO receiver — unauthenticated, token-verified internally ──────────────────
Route::get('/auth/sso', [SsoController::class, 'show'])->name('auth.sso');

// ── Mail auto-configuration endpoints (unauthenticated — must be before auth groups) ──
// Thunderbird / Mozilla autoconfig
Route::get('/mail/config-v1.1.xml', [PublicAutoconfigController::class, 'thunderbird'])->name('autoconfig.thunderbird');
// Microsoft Autodiscover — multiple case variants required by spec
Route::match(['get', 'post'], '/autodiscover/autodiscover.xml', [PublicAutoconfigController::class, 'autodiscover'])->name('autoconfig.autodiscover');
Route::match(['get', 'post'], '/Autodiscover/Autodiscover.xml', [PublicAutoconfigController::class, 'autodiscover']);
Route::match(['get', 'post'], '/AutoDiscover/AutoDiscover.xml', [PublicAutoconfigController::class, 'autodiscover']);
// Apple Mail .mobileconfig profile
Route::get('/mail/apple.mobileconfig', [PublicAutoconfigController::class, 'applemail'])->name('autoconfig.apple');

Route::get('/', function () {
    $user = auth()->user();
    if ($user) {
        if ($user->hasRole('admin')) {
            return redirect()->route('admin.dashboard');
        }
        if ($user->hasRole('reseller')) {
            return redirect()->route('reseller.dashboard');
        }
        if ($user->hasRole('user')) {
            return redirect()->route('customer.dashboard');
        }
    }

    return Inertia::render('Welcome', [
        'canLogin' => Route::has('login'),
        // Public registration is disabled — hesaplar install.sh kurulum sihirbazından
        // veya admin paneli "Kullanıcı Yönetimi" sayfasından oluşturulur.
        'canRegister' => false,
        'laravelVersion' => Application::VERSION,
        'phpVersion' => PHP_VERSION,
    ]);
});

// ════════════════════════════════════════════════════════════════════════════
// Onoxsoft License — KillSwitch'te bile erişilebilir (EnforceLicense allows)
// ════════════════════════════════════════════════════════════════════════════
Route::get('/lisans/satin-al', [\App\Http\Controllers\License\BuyController::class, 'show'])->name('license.buy');
Route::post('/lisans/intent-baslat', [\App\Http\Controllers\License\BuyController::class, 'generateIntent'])->name('license.intent');
Route::get('/lisans/poll', [\App\Http\Controllers\License\BuyController::class, 'poll'])->name('license.poll');

// ════════════════════════════════════════════════════════════════════════════
// Help Center (public — no auth required)
// ════════════════════════════════════════════════════════════════════════════
// Help Center routes kaldırıldı — destek harici sistem (WHMCS/WiseCP) ile entegre edilir
// Route::get('/help', [HelpCenterController::class, 'index'])->name('help.index');
// Route::get('/help/search', [HelpCenterController::class, 'search'])->name('help.search');
// Route::get('/help/c/{slug}', [HelpCenterController::class, 'category'])->name('help.category');
// Help routes kaldırıldı — eklenti/entegrasyon ile dış sistem (WHMCS/WiseCP)
// Route::get('/help/api/contextual', ...
// Route::post('/help/{slug}/feedback', ...
// Route::get('/help/{slug}', ...

Route::get('/dashboard', function () {
    $user = auth()->user();
    if ($user->hasRole('admin')) {
        return redirect()->route('admin.dashboard');
    }
    if ($user->hasRole('reseller')) {
        return redirect()->route('reseller.dashboard');
    }
    if ($user->hasRole('user')) {
        return redirect()->route('customer.dashboard');
    }

    return Inertia::render('Dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');

Route::middleware('auth')->group(function () {
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');

    // Onoxsoft License — IP transfer (admin panel'den cloud migration sonrası)
    Route::post('/lisans/ip-transfer', [\App\Http\Controllers\License\ActivateController::class, 'transferIp'])
        ->name('license.ip-transfer');

    // Notifications (both admin + customer)
    Route::get('/notifications', [NotificationController::class, 'index'])->name('notifications.index');
    Route::get('/notifications/recent', [NotificationController::class, 'recent'])->name('notifications.recent');
    Route::post('/notifications/{notification}/read', [NotificationController::class, 'markRead'])->name('notifications.read');
    Route::post('/notifications/read-all', [NotificationController::class, 'markAllRead'])->name('notifications.read-all');
    Route::delete('/notifications/{notification}', [NotificationController::class, 'destroy'])->name('notifications.destroy');
    Route::delete('/notifications', [NotificationController::class, 'destroyAll'])->name('notifications.destroy-all');

    // Web Push subscriptions (admin + customer ortak)
    Route::post('/api/push-subscriptions', [PushSubscriptionController::class, 'store'])->name('push.subscribe');
    Route::delete('/api/push-subscriptions', [PushSubscriptionController::class, 'destroy'])->name('push.unsubscribe');
});

// Admin route group — opt-in IP whitelist middleware aktif edilebilir
// (server_settings.admin_ip_whitelist_enabled=1 ile). Default kapalı.
Route::middleware(['auth', 'admin', 'admin.ip'])
    ->prefix('admin')
    ->name('admin.')
    ->group(function () {
        Route::get('/', [AdminDashboardController::class, 'index'])->name('dashboard');
        Route::get('/dashboard', [AdminDashboardController::class, 'index']);

        // Lightweight system info JSON — topbar live polling için (5sn TTL cache)
        Route::get('/system-info.json', [\App\Http\Controllers\Api\V1\SystemInfoController::class, 'index'])
            ->name('system-info.json');

        Route::post('accounts/bulk', [AdminAccountController::class, 'bulkAction'])->name('accounts.bulk');
        // Phase 2 — multi-select bulk actions (Accounts/Index.vue toolbar)
        Route::post('accounts/bulk-suspend',        [AdminAccountController::class, 'bulkSuspend'])->name('accounts.bulk-suspend');
        Route::post('accounts/bulk-unsuspend',      [AdminAccountController::class, 'bulkUnsuspend'])->name('accounts.bulk-unsuspend');
        Route::post('accounts/bulk-password-reset', [AdminAccountController::class, 'bulkPasswordReset'])->name('accounts.bulk-password-reset');
        Route::post('accounts/bulk-change-package', [AdminAccountController::class, 'bulkChangePackage'])->name('accounts.bulk-change-package');
        Route::post('accounts/bulk-terminate',      [AdminAccountController::class, 'bulkTerminate'])->name('accounts.bulk-terminate');

        Route::prefix('accounts/bulk-modifier')->name('accounts.bulk-modifier.')->group(function () {
            Route::get('/', [AdminBulkAccountController::class, 'index'])->name('index');
            Route::post('/apply', [AdminBulkAccountController::class, 'apply'])->name('apply');
            Route::get('/export', [AdminBulkAccountController::class, 'export'])->name('export');
        });

        Route::resource('accounts', AdminAccountController::class);
        Route::post('accounts/{account}/suspend', [AdminAccountController::class, 'suspend'])->name('accounts.suspend');
        Route::post('accounts/{account}/unsuspend', [AdminAccountController::class, 'unsuspend'])->name('accounts.unsuspend');
        Route::post('accounts/{account}/terminate', [AdminAccountController::class, 'terminate'])->name('accounts.terminate');
        Route::post('accounts/{account}/provision', [AdminAccountController::class, 'provision'])->name('accounts.provision');
        Route::post('accounts/{account}/resource-override', [AdminAccountController::class, 'setResourceOverride'])->name('accounts.resource-override.set');
        Route::delete('accounts/{account}/resource-override', [AdminAccountController::class, 'clearResourceOverride'])->name('accounts.resource-override.clear');

        // Faz P — WHM Account Functions muadili admin action'ları
        Route::post('accounts/{account}/activate', [AdminAccountController::class, 'activate'])->name('accounts.activate');
        Route::post('accounts/{account}/reset-password', [AdminAccountController::class, 'resetPassword'])->name('accounts.reset-password');
        Route::patch('accounts/{account}/package', [AdminAccountController::class, 'changePackage'])->name('accounts.change-package');
        Route::patch('accounts/{account}/owner', [AdminAccountController::class, 'changeOwner'])->name('accounts.change-owner');
        Route::post('accounts/{account}/backup', [AdminAccountController::class, 'triggerBackup'])->name('accounts.backup');

        Route::resource('packages', AdminPackageController::class)->except(['show']);
        // Audit Log (Phase 2 — filter + CSV/JSON export + detail + stats)
        Route::prefix('audit')->name('audit.')->group(function () {
            Route::get('/', [AdminAuditController::class, 'index'])->name('index');
            Route::get('/stats', [AdminAuditController::class, 'stats'])->name('stats');
            Route::get('/export.csv', [AdminAuditController::class, 'exportCsv'])->name('export.csv');
            Route::get('/export.json', [AdminAuditController::class, 'exportJson'])->name('export.json');
            Route::get('/{id}', [AdminAuditController::class, 'show'])->whereNumber('id')->name('show');
        });
        // BC: eski export endpoint
        Route::get('/audit/export', [AdminAuditController::class, 'exportCsv'])->name('audit.export.legacy');

        // Server Health
        Route::get('/health', [AdminHealthController::class, 'index'])->name('health.index');
        Route::post('/test-webpush', [AdminHealthController::class, 'testWebPush'])->name('test-webpush');

        // Mobile Push (APNs + FCM) — Faz F native push admin paneli
        Route::prefix('notifications/mobile')->name('notifications.mobile.')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\MobilePushController::class, 'index'])->name('index');
            Route::post('/test-push', [\App\Http\Controllers\Admin\MobilePushController::class, 'testPush'])->name('test-push');
        });

        // Service Status (systemctl wrapper)
        Route::get('/services', [AdminServiceController::class, 'index'])->name('services.index');
        Route::post('/services/restart-all', [AdminServiceController::class, 'restartAll'])->name('services.restart-all');
        Route::post('/services/enable-all', [AdminServiceController::class, 'enableAll'])->name('services.enable-all');
        Route::post('/services/{unit}/restart', [AdminServiceController::class, 'restart'])->name('services.restart');
        Route::post('/services/{unit}/reload', [AdminServiceController::class, 'reload'])->name('services.reload');
        Route::post('/services/{unit}/start', [AdminServiceController::class, 'start'])->name('services.start');
        Route::post('/services/{unit}/stop', [AdminServiceController::class, 'stop'])->name('services.stop');
        Route::get('/services/{unit}/logs', [AdminServiceController::class, 'logs'])->name('services.logs');
        // Phase 2 — live tail AJAX (5sn polling)
        Route::get('/services/{unit}/logs/live', [AdminServiceController::class, 'liveLogs'])->name('services.logs.live');

        // Resellers
        Route::get('/resellers', [AdminResellerController::class, 'index'])->name('resellers.index');
        Route::post('/resellers', [AdminResellerController::class, 'store'])->name('resellers.store');
        Route::post('/resellers/promote', [AdminResellerController::class, 'promote'])->name('resellers.promote');
        Route::get('/resellers/{user}', [AdminResellerController::class, 'show'])->name('resellers.show');
        Route::patch('/resellers/{user}/limits', [AdminResellerController::class, 'updateLimits'])->name('resellers.limits.update');
        Route::post('/resellers/{user}/suspend', [AdminResellerController::class, 'suspend'])->name('resellers.suspend');
        Route::post('/resellers/{user}/unsuspend', [AdminResellerController::class, 'unsuspend'])->name('resellers.unsuspend');
        Route::post('/resellers/{user}/transfer-account', [AdminResellerController::class, 'transferAccount'])->name('resellers.transfer-account');
        Route::delete('/resellers/{user}', [AdminResellerController::class, 'demote'])->name('resellers.demote');

        // Reseller Phase 2 — Branding
        Route::get('/resellers/{user}/branding', [AdminResellerController::class, 'branding'])->name('resellers.branding.index');
        Route::patch('/resellers/{user}/branding', [AdminResellerController::class, 'updateBranding'])->name('resellers.branding.update');
        Route::post('/resellers/{user}/branding/logo', [AdminResellerController::class, 'uploadBrandingLogo'])->middleware('throttle:uploads')->name('resellers.branding.logo');
        // Reseller Phase 3 — White-label vhost+SSL+DNS uygulama
        Route::post('/resellers/{user}/branding/apply', [AdminResellerController::class, 'applyWhiteLabel'])->name('resellers.branding.apply');
        Route::delete('/resellers/{user}/branding/whitelabel', [AdminResellerController::class, 'destroyWhiteLabel'])->name('resellers.branding.whitelabel.destroy');

        // Reseller Phase 2 — Sub-packages
        Route::get('/resellers/{user}/sub-packages', [AdminResellerController::class, 'subPackages'])->name('resellers.sub-packages.index');
        Route::post('/resellers/{user}/sub-packages', [AdminResellerController::class, 'storeSubPackage'])->name('resellers.sub-packages.store');
        Route::patch('/resellers/{user}/sub-packages/{subPackage}', [AdminResellerController::class, 'updateSubPackage'])->name('resellers.sub-packages.update');
        Route::delete('/resellers/{user}/sub-packages/{subPackage}', [AdminResellerController::class, 'destroySubPackage'])->name('resellers.sub-packages.destroy');

        // Reseller Phase 2 — Revenue
        Route::get('/resellers/{user}/revenue', [AdminResellerController::class, 'revenue'])->name('resellers.revenue.index');
        Route::post('/resellers/{user}/revenue/{revenueId}/mark-paid', [AdminResellerController::class, 'markRevenuePaid'])->name('resellers.revenue.mark-paid');

        // API Docs (OpenAPI spec viewer)
        Route::get('/api-docs', [AdminApiDocsController::class, 'index'])->name('api-docs.index');

        // Setup Wizard
        Route::get('/setup', [AdminSetupWizardController::class, 'index'])->name('setup.index');
        Route::post('/setup', [AdminSetupWizardController::class, 'save'])->name('setup.save');
        Route::post('/setup/skip', [AdminSetupWizardController::class, 'skip'])->name('setup.skip');

        // Cluster / Multi-Server
        Route::get('/cluster', [AdminClusterController::class, 'index'])->name('cluster.index');
        Route::get('/cluster/summary', [AdminClusterController::class, 'summary'])->name('cluster.summary');
        Route::get('/cluster/health', [AdminClusterController::class, 'health'])->name('cluster.health');
        Route::get('/cluster/sync', [AdminClusterController::class, 'syncWizard'])->name('cluster.sync.wizard');
        Route::post('/cluster', [AdminClusterController::class, 'store'])->name('cluster.store');
        // Specific job routes BEFORE {node} wildcard to avoid conflict
        Route::post('/cluster/jobs/{job}/cancel', [AdminClusterController::class, 'cancelJob'])->name('cluster.jobs.cancel');
        Route::post('/cluster/jobs/{job}/retry', [AdminClusterController::class, 'retryJob'])->name('cluster.jobs.retry');
        Route::get('/cluster/{node}', [AdminClusterController::class, 'show'])->name('cluster.show');
        Route::get('/cluster/{node}/jobs', [AdminClusterController::class, 'jobs'])->name('cluster.jobs');
        Route::post('/cluster/{node}/toggle', [AdminClusterController::class, 'toggleAccept'])->name('cluster.toggle');
        Route::post('/cluster/{node}/regenerate-secret', [AdminClusterController::class, 'regenerateSecret'])->name('cluster.regenerate-secret');
        Route::get('/cluster/{node}/install-script', [AdminClusterController::class, 'installScript'])->name('cluster.install-script');
        // Manager ops — ping/sync/exec/promote/slave-status
        Route::post('/cluster/{node}/ping', [AdminClusterController::class, 'ping'])->name('cluster.ping');
        Route::post('/cluster/{node}/sync', [AdminClusterController::class, 'sync'])->name('cluster.sync');
        Route::post('/cluster/{node}/exec', [AdminClusterController::class, 'exec'])->name('cluster.exec');
        Route::post('/cluster/{node}/promote', [AdminClusterController::class, 'promoteSlave'])->name('cluster.promote');
        Route::get('/cluster/{node}/slave-status', [AdminClusterController::class, 'slaveStatus'])->name('cluster.slave-status');
        // Phase N enterprise: token rotation + cross-node account migration
        Route::post('/cluster/{node}/rotate-token', [AdminClusterController::class, 'rotateToken'])->name('cluster.rotate-token');
        Route::post('/cluster/{node}/migrate-preflight', [AdminClusterController::class, 'migratePreflight'])->name('cluster.migrate-preflight');
        Route::post('/cluster/{node}/migrate-account/{account}', [AdminClusterController::class, 'migrateAccount'])->name('cluster.migrate-account');
        Route::delete('/cluster/{node}', [AdminClusterController::class, 'destroy'])->name('cluster.destroy');

        // Replication / HA (Multi-Server)
        Route::prefix('replication')->name('replication.')->group(function () {
            Route::get('/', [AdminReplicationController::class, 'index'])->name('index');
            Route::get('/create', [AdminReplicationController::class, 'create'])->name('create');
            Route::post('/', [AdminReplicationController::class, 'store'])->name('store');
            Route::get('/{setup}', [AdminReplicationController::class, 'show'])->name('show');
            Route::post('/{setup}/pause', [AdminReplicationController::class, 'pause'])->name('pause');
            Route::post('/{setup}/resume', [AdminReplicationController::class, 'resume'])->name('resume');
            Route::post('/{setup}/promote/{slave}', [AdminReplicationController::class, 'promoteSlave'])->name('promote');
            Route::post('/{setup}/health-check', [AdminReplicationController::class, 'healthCheck'])->name('health-check');
            Route::delete('/{setup}', [AdminReplicationController::class, 'delete'])->name('delete');
        });

        // API Tokens
        Route::get('/api-tokens', [AdminApiTokenController::class, 'index'])->name('api-tokens.index');
        Route::post('/api-tokens', [AdminApiTokenController::class, 'store'])->name('api-tokens.store');
        Route::delete('/api-tokens/{id}', [AdminApiTokenController::class, 'destroy'])->name('api-tokens.destroy');

        // Email Deliverability — WHM "Email Deliverability" admin muadili (Phase 2)
        // Tüm domain'lerin SPF/DKIM/DMARC/MX/PTR/RBL durumu + auto-fix
        Route::prefix('mail/deliverability')->name('mail.deliverability.')->group(function () {
            Route::get('/', [AdminEmailDeliverabilityController::class, 'index'])->name('index');
            Route::get('/{domain}', [AdminEmailDeliverabilityController::class, 'show'])->name('show');
            Route::post('/refresh', [AdminEmailDeliverabilityController::class, 'refresh'])->name('refresh');
            Route::post('/{domain}/auto-fix', [AdminEmailDeliverabilityController::class, 'autoFix'])->name('auto-fix');
            Route::post('/bulk-auto-fix', [AdminEmailDeliverabilityController::class, 'bulkAutoFix'])->name('bulk-auto-fix');
        });

        // Cron Audit — WHM "Cron Jobs" cross-account muadili (Phase 2)
        Route::prefix('cron-audit')->name('cron-audit.')->group(function () {
            Route::get('/', [AdminCronAuditController::class, 'index'])->name('index');
            Route::post('/{id}/disable', [AdminCronAuditController::class, 'disable'])->name('disable');
            Route::post('/{id}/enable', [AdminCronAuditController::class, 'enable'])->name('enable');
            Route::post('/bulk-disable-broken', [AdminCronAuditController::class, 'bulkDisableBroken'])->name('bulk-disable-broken');
        });

        // Server-Wide Settings (Tweak Settings)
        Route::get('/settings', [AdminSettingsController::class, 'index'])->name('settings.index');
        Route::patch('/settings', [AdminSettingsController::class, 'update'])->name('settings.update');

        // DNS Nameserver Yönetimi (Phase 2) — cPanel "Basic WebHost Manager Setup → Nameservers" muadili
        // Dedicated NS page: drift analizi, "Tüm zone'lara uygula" bulk action, per-zone resync.
        Route::prefix('dns')->name('dns.')->group(function () {
            Route::get('/nameservers', [AdminDnsNameserversController::class, 'index'])->name('nameservers.index');
            Route::patch('/nameservers', [AdminDnsNameserversController::class, 'update'])->name('nameservers.update');
            Route::post('/nameservers/apply-all', [AdminDnsNameserversController::class, 'applyToAllZones'])->name('nameservers.apply-all');
            Route::post('/nameservers/dry-run', [AdminDnsNameserversController::class, 'dryRun'])->name('nameservers.dry-run');
            Route::post('/nameservers/zones/{zone}/resync', [AdminDnsNameserversController::class, 'resyncZone'])->name('nameservers.zone.resync');

            // Phase 2 — DNS Templates (WHM "DNS Zone Template" muadili)
            // DB-driven templates auto-apply on zone creation; falls back to hardcoded DnsRecordTemplate.
            Route::prefix('templates')->name('templates.')->group(function () {
                Route::get('/', [\App\Http\Controllers\Admin\DnsTemplateController::class, 'index'])->name('index');
                Route::post('/', [\App\Http\Controllers\Admin\DnsTemplateController::class, 'store'])->name('store');
                Route::get('/{id}', [\App\Http\Controllers\Admin\DnsTemplateController::class, 'show'])->whereNumber('id')->name('show');
                Route::patch('/{id}', [\App\Http\Controllers\Admin\DnsTemplateController::class, 'update'])->whereNumber('id')->name('update');
                Route::delete('/{id}', [\App\Http\Controllers\Admin\DnsTemplateController::class, 'destroy'])->whereNumber('id')->name('destroy');
                Route::post('/{id}/default', [\App\Http\Controllers\Admin\DnsTemplateController::class, 'setDefault'])->whereNumber('id')->name('set-default');
                Route::post('/{id}/preview', [\App\Http\Controllers\Admin\DnsTemplateController::class, 'preview'])->whereNumber('id')->name('preview');
                Route::post('/{template}/records', [\App\Http\Controllers\Admin\DnsTemplateController::class, 'storeRecord'])->whereNumber('template')->name('records.store');
                Route::patch('/{template}/records/{record}', [\App\Http\Controllers\Admin\DnsTemplateController::class, 'updateRecord'])->whereNumber('template')->whereNumber('record')->name('records.update');
                Route::delete('/{template}/records/{record}', [\App\Http\Controllers\Admin\DnsTemplateController::class, 'destroyRecord'])->whereNumber('template')->whereNumber('record')->name('records.destroy');
            });
        });


        // Web Server Management (WHM-style: install/switch/reload)
        Route::prefix('webserver')->name('webserver.')->group(function () {
            Route::get('/', [AdminWebServerController::class, 'index'])->name('index');
            Route::post('/install', [AdminWebServerController::class, 'install'])->name('install');
            Route::post('/uninstall', [AdminWebServerController::class, 'uninstall'])->name('uninstall');
            Route::post('/switch', [AdminWebServerController::class, 'switch'])->name('switch');
            Route::post('/config-test', [AdminWebServerController::class, 'configTest'])->name('config-test');
            Route::post('/action/{action}', [AdminWebServerController::class, 'action'])->name('action');
        });

        // Mail Stack — birleşik dashboard + alt sayfalar (Webmail / IMAP / Spam)
        Route::prefix('mail')->name('mail.')->group(function () {
            Route::get('/', [AdminMailStackController::class, 'dashboard'])->name('dashboard');

            // Webmail (Roundcube/SnappyMail/Rainloop)
            Route::prefix('webmail')->name('webmail.')->group(function () {
                Route::get('/', [AdminMailStackController::class, 'webmailIndex'])->name('index');
                Route::post('/install', [AdminMailStackController::class, 'webmailInstall'])->name('install');
                Route::post('/uninstall', [AdminMailStackController::class, 'webmailUninstall'])->name('uninstall');
                Route::post('/switch', [AdminMailStackController::class, 'webmailSwitch'])->name('switch');
            });

            // IMAP/POP3 (Dovecot)
            Route::prefix('imap')->name('imap.')->group(function () {
                Route::get('/', [AdminMailStackController::class, 'imapIndex'])->name('index');
                Route::post('/install', [AdminMailStackController::class, 'imapInstall'])->name('install');
                Route::post('/action/{action}', [AdminMailStackController::class, 'imapAction'])->name('action');
            });

            // Spam Filter (Rspamd)
            Route::prefix('spam')->name('spam.')->group(function () {
                Route::get('/', [AdminMailStackController::class, 'spamIndex'])->name('index');
                Route::post('/install', [AdminMailStackController::class, 'spamInstall'])->name('install');
                Route::post('/action/{action}', [AdminMailStackController::class, 'spamAction'])->name('action');
            });

            // Health Check (5-grup tam diagnostic)
            Route::get('/health', [AdminMailStackController::class, 'healthIndex'])->name('health.index');
            Route::post('/health/refresh', [AdminMailStackController::class, 'healthRefresh'])->name('health.refresh');
            Route::post('/health/test-mail', [AdminMailStackController::class, 'healthTestMail'])->name('health.test-mail');
            Route::post('/health/auto-fix', [AdminMailStackController::class, 'healthAutoFix'])->name('health.auto-fix');

            // Mail Logs Viewer (Postfix/Dovecot/Rspamd tail)
            Route::get('/logs', [AdminMailStackController::class, 'logsIndex'])->name('logs.index');

            // Mail Backup Schedule (admin operational)
            Route::prefix('backup')->name('backup.')->group(function () {
                Route::get('/', [AdminMailStackController::class, 'backupIndex'])->name('index');
                Route::post('/all', [AdminMailStackController::class, 'backupAll'])->name('all');
                Route::post('/single', [AdminMailStackController::class, 'backupSingle'])->name('single');
                // Faz L: per-mailbox restore
                Route::get('/snapshots', [AdminMailStackController::class, 'backupSnapshots'])->name('snapshots');
                Route::post('/restore-mailbox', [AdminMailStackController::class, 'backupRestoreMailbox'])->name('restoreMailbox');
            });

            // Mailbox Storage Report (admin operational)
            Route::prefix('storage')->name('storage.')->group(function () {
                Route::get('/', [AdminMailStorageController::class, 'index'])->name('index');
                Route::get('/{id}', [AdminMailStorageController::class, 'show'])->name('show');
                Route::get('/{id}/activity', [AdminMailStorageController::class, 'activity'])->name('activity');
                Route::patch('/{id}/quota', [AdminMailStorageController::class, 'updateQuota'])->name('quota');
                Route::post('/{id}/toggle', [AdminMailStorageController::class, 'toggleStatus'])->name('toggle');
                Route::post('/{id}/reset-password', [AdminMailStorageController::class, 'resetPassword'])->name('reset-password');
            });

            // cPanel Mail Migration (pkgacct tarball import)
            Route::prefix('migration')->name('migration.')->group(function () {
                Route::get('/', [AdminMailMigrationController::class, 'index'])->name('index');
                Route::post('/parse', [AdminMailMigrationController::class, 'uploadAndParse'])->name('parse');
                Route::post('/confirm', [AdminMailMigrationController::class, 'confirmImport'])->name('confirm');
                Route::post('/cancel', [AdminMailMigrationController::class, 'cancelPreview'])->name('cancel');
            });

            // Mailing Lists (sentinel pattern over EmailForwarder)
            Route::prefix('mailing-lists')->name('mailing-lists.')->group(function () {
                Route::get('/', [AdminMailingListController::class, 'index'])->name('index');
                Route::post('/', [AdminMailingListController::class, 'store'])->name('store');
                Route::get('/{id}', [AdminMailingListController::class, 'show'])->name('show');
                Route::patch('/{id}/members', [AdminMailingListController::class, 'updateMembers'])->name('members.update');
                Route::post('/{id}/members', [AdminMailingListController::class, 'addMember'])->name('members.add');
                Route::delete('/{id}/members', [AdminMailingListController::class, 'removeMember'])->name('members.remove');
                Route::delete('/{id}', [AdminMailingListController::class, 'destroy'])->name('destroy');
            });
        });

        // Mail Server Management (WHM-style: install/switch/test/queue) — eski MTA endpoint'leri
        Route::prefix('mailserver')->name('mailserver.')->group(function () {
            Route::get('/', [AdminMailServerController::class, 'index'])->name('index');
            Route::post('/install', [AdminMailServerController::class, 'install'])->name('install');
            Route::post('/uninstall', [AdminMailServerController::class, 'uninstall'])->name('uninstall');
            Route::post('/switch', [AdminMailServerController::class, 'switch'])->name('switch');
            Route::post('/action/{action}', [AdminMailServerController::class, 'action'])->name('action');
            Route::post('/test-mail', [AdminMailServerController::class, 'testMail'])->name('test-mail');
            Route::post('/flush-queue', [AdminMailServerController::class, 'flushQueue'])->name('flush-queue');
        });

        // Eklentiler & Entegrasyonlar (WHMCS, WiseCP, REST, Webhooks dashboard)
        Route::get('/integrations', [AdminIntegrationsController::class, 'index'])->name('integrations.index');

        // MultiPHP Manager
        Route::get('/multiphp', [AdminMultiPhpController::class, 'index'])->name('multiphp.index');
        Route::post('/multiphp/bulk-update', [AdminMultiPhpController::class, 'bulkUpdate'])->name('multiphp.bulk-update');
        Route::post('/multiphp/set-default', [AdminMultiPhpController::class, 'setSystemDefault'])->name('multiphp.set-default');
        // Faz R — EasyApache 4 muadili: install/uninstall PHP versions
        Route::post('/multiphp/install', [AdminMultiPhpController::class, 'install'])->name('multiphp.install');
        Route::post('/multiphp/uninstall', [AdminMultiPhpController::class, 'uninstall'])->name('multiphp.uninstall');

        // Phase 2 — FPM Pool Tuning (per-account)
        // cPanel "MultiPHP INI Editor → FPM Pool" + Plesk "PHP-FPM Pool Settings" muadili.
        Route::prefix('fpm-pools')->name('fpm-pools.')->group(function () {
            Route::get('/', [AdminFpmPoolController::class, 'index'])->name('index');
            Route::patch('/{account}/{phpVersion}', [AdminFpmPoolController::class, 'update'])
                ->where('phpVersion', '[0-9]+\.[0-9]+')
                ->name('update');
            Route::delete('/{account}/{phpVersion}', [AdminFpmPoolController::class, 'reset'])
                ->where('phpVersion', '[0-9]+\.[0-9]+')
                ->name('reset');
            Route::get('/{account}/{phpVersion}/status', [AdminFpmPoolController::class, 'status'])
                ->where('phpVersion', '[0-9]+\.[0-9]+')
                ->name('status');
            Route::post('/reload/{phpVersion}', [AdminFpmPoolController::class, 'reload'])
                ->where('phpVersion', '[0-9]+\.[0-9]+')
                ->name('reload');
        });

        // PHP Extension Manager (per-version pecl/dnf module manager)
        Route::prefix('php-extensions')->name('php-extensions.')->group(function () {
            Route::get('/', [AdminPhpExtensionController::class, 'index'])->name('index');
            Route::post('/install', [AdminPhpExtensionController::class, 'install'])->name('install');
            Route::post('/uninstall', [AdminPhpExtensionController::class, 'uninstall'])->name('uninstall');
        });

        // DB Version Switcher (MySQL/MariaDB upgrade)
        Route::prefix('db-version')->name('db-version.')->group(function () {
            Route::get('/', [AdminDbVersionController::class, 'index'])->name('index');
            Route::post('/refresh-versions', [AdminDbVersionController::class, 'refreshVersions'])->name('refresh-versions');
            Route::post('/prepare', [AdminDbVersionController::class, 'prepare'])->name('prepare');
            Route::post('/apply-auto-fixes', [AdminDbVersionController::class, 'applyAutoFixes'])->name('apply-auto-fixes');
            Route::post('/dry-run', [AdminDbVersionController::class, 'dryRun'])->name('dry-run');
            Route::post('/switch', [AdminDbVersionController::class, 'switch'])->name('switch');
            // Phase 2 — rollback: önceki sürüme dön (backup'tan import)
            Route::post('/rollback', [AdminDbVersionController::class, 'rollback'])->name('rollback');
        });

        // Process Manager (WHM "Process Manager" muadili) — Phase 2 live + audit
        Route::get('/processes', [AdminProcessController::class, 'index'])->name('processes.index');
        Route::get('/processes/live', [AdminProcessController::class, 'liveList'])->name('processes.live');
        Route::get('/processes/refresh', [AdminProcessController::class, 'refresh'])->name('processes.refresh'); // legacy alias
        Route::post('/processes/{pid}/kill', [AdminProcessController::class, 'kill'])->whereNumber('pid')->name('processes.kill');

        // Network Tools
        Route::get('/network', [AdminNetworkController::class, 'index'])->name('network.index');
        Route::post('/network/dig', [AdminNetworkController::class, 'dig'])->name('network.dig');
        Route::post('/network/ping', [AdminNetworkController::class, 'ping'])->name('network.ping');
        Route::post('/network/reverse-dns', [AdminNetworkController::class, 'reverseDns'])->name('network.reverse-dns');

        // Mail Queue Manager (Postfix postqueue/postsuper bridge)
        Route::get('/mail-queue', [AdminMailQueueController::class, 'index'])->name('mail-queue.index');
        Route::post('/mail-queue/flush', [AdminMailQueueController::class, 'flush'])->name('mail-queue.flush');
        Route::post('/mail-queue/hold/{id}', [AdminMailQueueController::class, 'hold'])->name('mail-queue.hold');
        Route::post('/mail-queue/requeue/{id}', [AdminMailQueueController::class, 'requeue'])->name('mail-queue.requeue');
        Route::delete('/mail-queue/{id}', [AdminMailQueueController::class, 'deleteMail'])->name('mail-queue.delete');

        // DKIM Keys Manager (Phase 2 mail server)
        Route::prefix('mail/dkim')->name('mail.dkim.')->group(function () {
            Route::get('/', [AdminDkimManagerController::class, 'index'])->name('index');
            Route::get('/{id}/dns', [AdminDkimManagerController::class, 'showDns'])->name('dns');
            Route::post('/', [AdminDkimManagerController::class, 'generate'])->name('generate');
            Route::post('/bulk-generate', [AdminDkimManagerController::class, 'bulkGenerate'])->name('bulk-generate');
            // Phase 2 — AJAX polling endpoint for bulk-generate progress (every 2s)
            Route::get('/bulk-progress', [AdminDkimManagerController::class, 'bulkProgress'])->name('bulk-progress');
            Route::post('/{id}/rotate', [AdminDkimManagerController::class, 'rotate'])->name('rotate');
            Route::post('/{id}/toggle', [AdminDkimManagerController::class, 'toggle'])->name('toggle');
            Route::post('/{id}/verify', [AdminDkimManagerController::class, 'verifyDns'])->name('verify');
            Route::delete('/{id}', [AdminDkimManagerController::class, 'destroy'])->name('destroy');
        });

        // Account Snapshots (cPanel migration tool)
        Route::prefix('snapshots')->name('snapshots.')->group(function () {
            Route::get('/', [AdminSnapshotController::class, 'index'])->name('index');
            Route::get('/create', [AdminSnapshotController::class, 'create'])->name('create');
            Route::post('/', [AdminSnapshotController::class, 'store'])->name('store');
            Route::get('/import', [AdminSnapshotController::class, 'importForm'])->name('import.form');
            Route::post('/import', [AdminSnapshotController::class, 'import'])->name('import');
            Route::get('/{snapshot}', [AdminSnapshotController::class, 'show'])->name('show');
            Route::post('/{snapshot}/restore', [AdminSnapshotController::class, 'restore'])->name('restore');
            Route::get('/{snapshot}/download', [AdminSnapshotController::class, 'download'])->name('download');
            // Phase N: cluster-wide replication
            Route::post('/{snapshot}/replicate', [AdminSnapshotController::class, 'replicate'])->name('replicate');
            Route::get('/{snapshot}/replication-status', [AdminSnapshotController::class, 'replicationStatus'])->name('replication-status');
            Route::delete('/{snapshot}', [AdminSnapshotController::class, 'destroy'])->name('destroy');
        });

        // cPanel Migration Tool (pkgacct restore engine)
        Route::prefix('migration')->name('migration.')->group(function () {
            Route::get('/', [AdminCpanelMigrationController::class, 'index'])->name('index');
            Route::post('/upload', [AdminCpanelMigrationController::class, 'upload'])->middleware('throttle:uploads')->name('upload');
            // Phase 2 polish: uzak cPanel sunucudan SSH ile pkgacct çek (tek hesap)
            Route::post('/pull-remote', [AdminCpanelMigrationController::class, 'pullRemote'])->name('pull-remote');

            // WHM Transfer Tool muadili — multi-step wizard (Phase 2)
            Route::prefix('transfer')->name('transfer.')->group(function () {
                Route::get('/', [AdminCpanelMigrationController::class, 'transferTool'])->name('index');
                Route::post('/test', [AdminCpanelMigrationController::class, 'testConnection'])->name('test');
                Route::post('/discover', [AdminCpanelMigrationController::class, 'discoverRemote'])->name('discover');
                Route::post('/bulk-pull', [AdminCpanelMigrationController::class, 'bulkPullRemote'])->name('bulk-pull');
            });

            Route::post('/{job}/inspect', [AdminCpanelMigrationController::class, 'inspect'])->name('inspect');
            Route::get('/{job}/plan', [AdminCpanelMigrationController::class, 'plan'])->name('plan');
            // Phase 2 polish: execute öncesi blocker kontrolü (AJAX)
            Route::post('/{job}/preflight', [AdminCpanelMigrationController::class, 'preflight'])->name('preflight');
            Route::post('/{job}/execute', [AdminCpanelMigrationController::class, 'execute'])->name('execute');
            Route::get('/{job}/progress', [AdminCpanelMigrationController::class, 'progress'])->name('progress');
            Route::get('/{job}', [AdminCpanelMigrationController::class, 'show'])->name('show');
            Route::post('/{job}/cancel', [AdminCpanelMigrationController::class, 'cancel'])->name('cancel');
            Route::delete('/{job}', [AdminCpanelMigrationController::class, 'destroy'])->name('destroy');
        });

        // Backup Manager
        Route::prefix('backups')->name('backups.')->group(function () {
            Route::get('/', [AdminBackupController::class, 'dashboard'])->name('dashboard');
            Route::get('/schedules', [AdminBackupController::class, 'schedules'])->name('schedules');
            Route::post('/schedules', [AdminBackupController::class, 'storeSchedule'])->name('schedules.store');
            Route::patch('/schedules/{schedule}', [AdminBackupController::class, 'updateSchedule'])->name('schedules.update');
            Route::delete('/schedules/{schedule}', [AdminBackupController::class, 'destroySchedule'])->name('schedules.destroy');
            Route::post('/schedules/{schedule}/run', [AdminBackupController::class, 'runScheduleNow'])->name('schedules.run');

            Route::get('/destinations', [AdminBackupController::class, 'destinations'])->name('destinations');
            Route::post('/destinations', [AdminBackupController::class, 'storeDestination'])->name('destinations.store');
            Route::post('/destinations/{destination}/test', [AdminBackupController::class, 'testDestination'])->name('destinations.test');
            // Phase 2 — JSON variant for AJAX inline modal (step-by-step + throughput)
            Route::post('/destinations/{destination}/test-json', [AdminBackupController::class, 'testDestinationJson'])->name('destinations.test-json');
            Route::delete('/destinations/{destination}', [AdminBackupController::class, 'destroyDestination'])->name('destinations.destroy');

            Route::get('/history', [AdminBackupController::class, 'history'])->name('history');
            Route::post('/history/{backup}/restore', [AdminBackupController::class, 'restoreNow'])->name('history.restore');

            // Server-wide Backup Configuration (WHM Backup Configuration)
            Route::get('/config', [AdminBackupConfigController::class, 'index'])->name('config.index');
            Route::patch('/config', [AdminBackupConfigController::class, 'update'])->name('config.update');
            Route::post('/config/apply-all', [AdminBackupConfigController::class, 'applyToAllAccounts'])->name('config.apply-all');
            Route::post('/config/reset', [AdminBackupConfigController::class, 'resetToDefaults'])->name('config.reset');
            Route::get('/config/export', [AdminBackupConfigController::class, 'exportConfig'])->name('config.export');
            Route::post('/config/run-now', [AdminBackupConfigController::class, 'runNow'])->name('config.run-now');
        });

        // Impersonate (login as customer) — WHM-style "view-as-account"
        Route::post('/impersonate/{user}', [AdminImpersonateController::class, 'start'])->name('impersonate.start');
        // Yeni API: doğrudan account ID ile hızlı geçiş (banner switcher dropdown)
        Route::post('/view-account/{account}', [AdminImpersonateController::class, 'viewAccount'])->name('view-account');

        // System Logs Viewer (apache_error, php_fpm, mariadb, secure, fail2ban, panel_laravel, vd.)
        Route::get('/logs', [AdminLogsController::class, 'index'])->name('logs.index');
        Route::get('/logs/refresh', [AdminLogsController::class, 'refresh'])->name('logs.refresh');
        Route::get('/logs/{source}/download', [AdminLogsController::class, 'download'])->name('logs.download');

        // ModSecurity / WAF Management
        Route::prefix('modsecurity')->name('modsecurity.')->group(function () {
            Route::get('/', [AdminModSecurityController::class, 'index'])->name('index');

            // Settings
            Route::patch('/settings', [AdminModSecurityController::class, 'updateSettings'])->name('settings.update');

            // Rule exclusions
            Route::post('/exclusions', [AdminModSecurityController::class, 'storeExclusion'])->name('exclusions.store');
            Route::delete('/exclusions/{id}', [AdminModSecurityController::class, 'destroyExclusion'])->name('exclusions.destroy');
            Route::post('/exclusions/from-audit/{auditEventId}', [AdminModSecurityController::class, 'quickExcludeFromAudit'])->name('exclusions.from_audit');

            // IP Whitelist
            Route::post('/whitelist', [AdminModSecurityController::class, 'storeWhitelist'])->name('whitelist.store');
            Route::delete('/whitelist/{id}', [AdminModSecurityController::class, 'destroyWhitelist'])->name('whitelist.destroy');

            // Custom rules
            Route::post('/custom-rules', [AdminModSecurityController::class, 'storeCustomRule'])->name('custom_rules.store');
            Route::post('/custom-rules/{id}/toggle', [AdminModSecurityController::class, 'toggleCustomRule'])->name('custom_rules.toggle');
            Route::delete('/custom-rules/{id}', [AdminModSecurityController::class, 'destroyCustomRule'])->name('custom_rules.destroy');

            // Audit log
            Route::post('/audit/search', [AdminModSecurityController::class, 'searchAuditLog'])->name('audit.search');
            Route::post('/audit/refresh', [AdminModSecurityController::class, 'refreshAuditLog'])->name('audit.refresh');

            // Test request
            Route::post('/test-request', [AdminModSecurityController::class, 'testRequest'])->name('test_request');

            // CRS update
            Route::post('/crs-update', [AdminModSecurityController::class, 'updateCrs'])->name('crs.update');

            // Rule detail + per-rule toggle (Faz Ü+)
            Route::get('/rules/{ruleId}/detail', [AdminModSecurityController::class, 'ruleDetail'])->name('rules.detail');
            Route::post('/rules/{ruleId}/toggle', [AdminModSecurityController::class, 'toggleRule'])->name('rules.toggle');

            // Audit event detail modal
            Route::get('/audit/{eventId}/detail', [AdminModSecurityController::class, 'auditEventDetail'])->name('audit.detail');

            // Reports tab
            Route::get('/reports', [AdminModSecurityController::class, 'reports'])->name('reports');

            // Vendors
            Route::get('/vendors', [AdminModSecurityController::class, 'vendors'])->name('vendors.list');
            Route::post('/vendors/install', [AdminModSecurityController::class, 'installVendor'])->name('vendors.install');
            Route::delete('/vendors/{slug}', [AdminModSecurityController::class, 'removeVendor'])->name('vendors.remove');
        });

        // Firewall / cPHulk (Brute Force Protection) — Faz Ü genişletildi
        Route::prefix('firewall')->name('firewall.')->group(function () {
            Route::get('/', [AdminFirewallController::class, 'index'])->name('index');

            // Temel kurallar
            Route::post('/rules', [AdminFirewallController::class, 'storeRule'])->name('rules.store');
            Route::delete('/rules/{id}', [AdminFirewallController::class, 'destroyRule'])->name('rules.destroy');
            Route::post('/reload', [AdminFirewallController::class, 'reload'])->name('reload');

            // Ülke blokları
            Route::post('/countries/toggle', [AdminFirewallController::class, 'toggleCountry'])->name('countries.toggle');
            Route::post('/countries/bulk', [AdminFirewallController::class, 'bulkToggleCountries'])->name('countries.bulk');
            Route::post('/geoip/update', [AdminFirewallController::class, 'updateGeoipDatabase'])->name('geoip.update');

            // cPHulk
            Route::patch('/cphulk', [AdminFirewallController::class, 'updateCphulk'])->name('cphulk.update');

            // Tehdit listeleri (Spamhaus DROP/EDROP, DShield, ET, Tor)
            Route::post('/threats/{id}/sync', [AdminFirewallController::class, 'syncThreatList'])->name('threats.sync');
            Route::post('/threats/{id}/toggle', [AdminFirewallController::class, 'toggleThreatList'])->name('threats.toggle');
            Route::post('/threats/sync-all', [AdminFirewallController::class, 'syncAllThreatLists'])->name('threats.sync_all');

            // Güvenilir IP'ler (master allowlist)
            Route::post('/trusted', [AdminFirewallController::class, 'storeTrustedIp'])->name('trusted.store');
            Route::delete('/trusted/{id}', [AdminFirewallController::class, 'destroyTrustedIp'])->name('trusted.destroy');

            // Bağlantı limitleri (DDoS / SYN flood / rate limit)
            Route::patch('/conn-limits', [AdminFirewallController::class, 'updateConnectionLimits'])->name('conn_limits.update');

            // Son aktivite + IP lookup
            Route::post('/recent/refresh', [AdminFirewallController::class, 'refreshRecentBlocks'])->name('recent.refresh');
            Route::post('/lookup', [AdminFirewallController::class, 'lookupIp'])->name('lookup');
        });

        // fail2ban (admin only) — Faz Ü gelişmiş sürüm
        Route::prefix('security/fail2ban')->name('fail2ban.')->group(function () {
            Route::get('/', [AdminFail2banController::class, 'index'])->name('index');

            // Jail CRUD
            Route::post('/jails', [AdminFail2banController::class, 'storeJail'])->name('jails.store');
            Route::delete('/jails/{jail}', [AdminFail2banController::class, 'deleteJail'])->name('jails.delete');
            Route::post('/jails/{jail}/toggle', [AdminFail2banController::class, 'toggleJail'])->name('jails.toggle');

            // Ban / Unban
            Route::post('/ban', [AdminFail2banController::class, 'ban'])->name('ban');
            Route::post('/unban', [AdminFail2banController::class, 'unban'])->name('unban');
            Route::post('/bulk-ban', [AdminFail2banController::class, 'bulkBan'])->name('bulk_ban');
            Route::post('/jails/{jail}/unban-all', [AdminFail2banController::class, 'unbanAll'])->name('unban_all');

            // Whitelist
            Route::post('/whitelist', [AdminFail2banController::class, 'addWhitelist'])->name('whitelist.add');
            Route::delete('/whitelist/{id}', [AdminFail2banController::class, 'removeWhitelist'])->name('whitelist.remove');

            // Global settings + presets
            Route::patch('/settings', [AdminFail2banController::class, 'updateSettings'])->name('settings.update');
            Route::post('/preset', [AdminFail2banController::class, 'applyPreset'])->name('preset.apply');

            // Filter test + service control
            Route::post('/filter-test', [AdminFail2banController::class, 'testFilter'])->name('filter.test');
            Route::post('/restart', [AdminFail2banController::class, 'restart'])->name('restart');
            Route::post('/reload', [AdminFail2banController::class, 'reload'])->name('reload');

            Route::get('/status/{jail}', [AdminFail2banController::class, 'status'])->name('status');
        });

        // Branding / White-Label
        Route::prefix('branding')->name('branding.')->group(function () {
            Route::get('/', [AdminBrandingController::class, 'index'])->name('index');
            Route::patch('/', [AdminBrandingController::class, 'update'])->name('update');
            Route::post('/logo', [AdminBrandingController::class, 'uploadLogo'])->middleware('throttle:uploads')->name('logo.upload');
            Route::post('/favicon', [AdminBrandingController::class, 'uploadFavicon'])->middleware('throttle:uploads')->name('favicon.upload');
            Route::post('/login-bg', [AdminBrandingController::class, 'uploadLoginBg'])->middleware('throttle:uploads')->name('login-bg.upload');
            Route::delete('/asset/{key}', [AdminBrandingController::class, 'removeAsset'])->name('asset.remove');
            Route::post('/reset', [AdminBrandingController::class, 'reset'])->name('reset');
        });

        // MySQL Global Database Manager (WHM SQL Services)
        Route::prefix('mysql')->name('mysql.')->group(function () {
            Route::get('/', [AdminMysqlAdminController::class, 'index'])->name('index');
            Route::delete('/processlist/{processId}', [AdminMysqlAdminController::class, 'killProcess'])->name('process.kill');
            Route::post('/optimize', [AdminMysqlAdminController::class, 'optimizeTable'])->name('optimize');
            Route::post('/repair', [AdminMysqlAdminController::class, 'repairTable'])->name('repair');
            Route::post('/flush-hosts', [AdminMysqlAdminController::class, 'flushHostsCache'])->name('flush-hosts');
            Route::post('/flush-query-cache', [AdminMysqlAdminController::class, 'flushQueryCache'])->name('flush-query-cache');
            Route::post('/restart', [AdminMysqlAdminController::class, 'restart'])->name('restart');
            Route::get('/databases/{databaseId}/phpmyadmin', [AdminMysqlAdminController::class, 'phpmyadminSso'])->name('phpmyadmin.sso');
            // Faz I: admin root-level SSO POST endpoint (returns JSON {redirect_url})
            Route::post('/pma-sso', [AdminMysqlAdminController::class, 'pmaSsoIssue'])->name('pma-sso');

            // Slow Query Analyzer (Phase 2) — slow.log parse + EXPLAIN + suggestions + processlist kill
            Route::prefix('slow-queries')->name('slow-queries.')->group(function () {
                Route::get('/',            [\App\Http\Controllers\Admin\MysqlSlowQueryController::class, 'index'])->name('index');
                Route::get('/running',     [\App\Http\Controllers\Admin\MysqlSlowQueryController::class, 'running'])->name('running');
                Route::post('/explain',    [\App\Http\Controllers\Admin\MysqlSlowQueryController::class, 'explain'])->name('explain');
                Route::post('/kill/{pid}', [\App\Http\Controllers\Admin\MysqlSlowQueryController::class, 'kill'])->whereNumber('pid')->name('kill');
                Route::post('/clear-log',  [\App\Http\Controllers\Admin\MysqlSlowQueryController::class, 'clearLog'])->name('clear-log');
                Route::patch('/settings',  [\App\Http\Controllers\Admin\MysqlSlowQueryController::class, 'settings'])->name('settings.update');
                Route::get('/{hash}',      [\App\Http\Controllers\Admin\MysqlSlowQueryController::class, 'show'])->where('hash', '[a-z0-9]+')->name('show');
            });
        });

        // MySQL Server Configuration (my.cnf editor)
        Route::prefix('mysql-config')->name('mysql.config.')->group(function () {
            Route::get('/', [AdminMysqlServerConfigController::class, 'index'])->name('index');
            Route::patch('/', [AdminMysqlServerConfigController::class, 'update'])->name('update');
            Route::post('/reset', [AdminMysqlServerConfigController::class, 'resetToDefaults'])->name('reset');
            Route::get('/export', [AdminMysqlServerConfigController::class, 'exportCnf'])->name('export');
            Route::post('/restart', [AdminMysqlServerConfigController::class, 'restart'])->name('restart');
        });

        // Apache Global Configuration (WHM EasyApache)
        Route::prefix('apache')->name('apache.')->group(function () {
            Route::get('/', [AdminApacheConfigController::class, 'index'])->name('index');
            Route::patch('/', [AdminApacheConfigController::class, 'update'])->name('update');
            Route::post('/modules/toggle', [AdminApacheConfigController::class, 'toggleModule'])->name('modules.toggle');
            // Phase 2 — vendor modül install (mod_pagespeed, mod_evasive vb.)
            Route::post('/modules/install', [AdminApacheConfigController::class, 'installModule'])->name('modules.install');
            Route::post('/reset', [AdminApacheConfigController::class, 'resetToDefaults'])->name('reset');
            Route::get('/export', [AdminApacheConfigController::class, 'exportConf'])->name('export');
            Route::post('/reload', [AdminApacheConfigController::class, 'reload'])->name('reload');
            Route::post('/test', [AdminApacheConfigController::class, 'testConfig'])->name('test');
        });

        // PHP System Defaults (WHM MultiPHP System Default + INI Editor)
        Route::prefix('php-system')->name('php-system.')->group(function () {
            Route::get('/', [AdminPhpSystemController::class, 'index'])->name('index');
            Route::patch('/', [AdminPhpSystemController::class, 'update'])->name('update');
            Route::post('/extensions/toggle', [AdminPhpSystemController::class, 'toggleExtension'])->name('extensions.toggle');
            Route::post('/default-version', [AdminPhpSystemController::class, 'setDefaultVersion'])->name('set-default');
            Route::post('/reset', [AdminPhpSystemController::class, 'resetToDefaults'])->name('reset');
            Route::get('/export', [AdminPhpSystemController::class, 'exportIni'])->name('export');
        });

        // Mail Delivery Reports (WHM mail trafiği)
        Route::prefix('mail-reports')->name('mail-reports.')->group(function () {
            Route::get('/', [AdminMailReportsController::class, 'index'])->name('index');
            Route::get('/export', [AdminMailReportsController::class, 'export'])->name('export');
            // Postfix queue ID alfanumerik (örn: ABCDEF123) — pattern ile sanitize
            Route::post('/{queueId}/requeue', [AdminMailReportsController::class, 'requeue'])
                ->where('queueId', '[A-F0-9]{6,16}')
                ->name('requeue');
            Route::delete('/{queueId}', [AdminMailReportsController::class, 'delete'])
                ->where('queueId', '[A-F0-9]{6,16}')
                ->name('delete');
        });

        // SSL/AutoSSL Manager (WHM SSL Status + AutoSSL)
        Route::prefix('ssl')->name('ssl.')->group(function () {
            Route::get('/', [AdminSslManagerController::class, 'index'])->name('index');
            Route::patch('/settings', [AdminSslManagerController::class, 'update'])->name('settings.update');
            Route::post('/renew-all', [AdminSslManagerController::class, 'renewAll'])->name('renew-all');
            Route::post('/run-autossl', [AdminSslManagerController::class, 'runAutoSslNow'])->name('run-autossl');
            Route::post('/{certificateId}/renew', [AdminSslManagerController::class, 'renew'])->name('renew');
            Route::delete('/{certificateId}', [AdminSslManagerController::class, 'revoke'])->name('revoke');
            Route::post('/settings/reset', [AdminSslManagerController::class, 'resetSettings'])->name('settings.reset');

            // AutoSSL Manager (cPanel "Manage AutoSSL" muadili) — Phase 2
            // LE rate limit tracking, force renewal with bypass, RBL/blocklist check.
            Route::prefix('autossl')->name('autossl.')->group(function () {
                Route::get('/', [AdminSslManagerController::class, 'autoSslIndex'])->name('index');
                Route::get('/{id}', [AdminSslManagerController::class, 'autoSslShow'])->whereNumber('id')->name('show');
                Route::post('/{id}/force-renew', [AdminSslManagerController::class, 'forceRenew'])->whereNumber('id')->name('force-renew');
                Route::post('/{id}/toggle-auto-renew', [AdminSslManagerController::class, 'toggleAutoRenew'])->whereNumber('id')->name('toggle-auto-renew');
                Route::post('/{id}/check-rbl', [AdminSslManagerController::class, 'checkRbl'])->whereNumber('id')->name('check-rbl');
                Route::post('/bulk-renew', [AdminSslManagerController::class, 'bulkRenew'])->name('bulk-renew');
            });
        });

        // System Resource Usage Tracker (server-wide CPU/RAM/IO)
        Route::prefix('resources')->name('resources.')->group(function () {
            Route::get('/', [AdminResourceUsageController::class, 'index'])->name('index');
            Route::get('/{accountId}', [AdminResourceUsageController::class, 'show'])->name('show');
        });

        // Bandwidth Dashboard
        Route::prefix('bandwidth')->name('bandwidth.')->group(function () {
            Route::get('/', [AdminBandwidthController::class, 'index'])->name('index');
        });

        // Update Manager
        Route::prefix('updates')->name('updates.')->group(function () {
            Route::get('/', [AdminUpdateManagerController::class, 'index'])->name('index');
            Route::post('/onox', [AdminUpdateManagerController::class, 'runOnoxUpdate'])->name('onox.run');
            Route::post('/system', [AdminUpdateManagerController::class, 'runSystemUpdate'])->name('system.run');
            Route::patch('/settings', [AdminUpdateManagerController::class, 'updateSettings'])->name('settings.update');
            Route::post('/check', [AdminUpdateManagerController::class, 'checkNow'])->name('check');
        });

        // Maintenance Mode
        Route::prefix('maintenance')->name('maintenance.')->group(function () {
            Route::get('/', [AdminMaintenanceModeController::class, 'index'])->name('index');
            Route::patch('/', [AdminMaintenanceModeController::class, 'update'])->name('update');
            Route::post('/enable', [AdminMaintenanceModeController::class, 'enableNow'])->name('enable');
            Route::post('/disable', [AdminMaintenanceModeController::class, 'disable'])->name('disable');
        });

        // Announcements (broadcast to customers)
        Route::prefix('announcements')->name('announcements.')->group(function () {
            Route::get('/', [AdminAnnouncementController::class, 'index'])->name('index');
            Route::post('/', [AdminAnnouncementController::class, 'store'])->name('store');
            Route::patch('/{id}', [AdminAnnouncementController::class, 'update'])->name('update');
            Route::post('/{id}/toggle', [AdminAnnouncementController::class, 'toggle'])->name('toggle');
            Route::delete('/{id}', [AdminAnnouncementController::class, 'destroy'])->name('destroy');
        });

        // Postfix Server Configuration (Phase 2 mail server hazırlık)
        Route::prefix('mail/postfix')->name('mail.postfix.')->group(function () {
            Route::get('/', [AdminPostfixConfigController::class, 'index'])->name('index');
            Route::patch('/', [AdminPostfixConfigController::class, 'update'])->name('update');
            Route::post('/reset', [AdminPostfixConfigController::class, 'resetToDefaults'])->name('reset');
            Route::get('/export', [AdminPostfixConfigController::class, 'exportMainCf'])->name('export');
            Route::post('/reload', [AdminPostfixConfigController::class, 'reload'])->name('reload');
            Route::post('/restart', [AdminPostfixConfigController::class, 'restart'])->name('restart');
            Route::post('/test', [AdminPostfixConfigController::class, 'testConfig'])->name('test');
            Route::post('/queue/flush', [AdminPostfixConfigController::class, 'flushQueue'])->name('queue.flush');
            Route::delete('/queue/{queueId}', [AdminPostfixConfigController::class, 'deleteFromQueue'])->name('queue.delete');
        });

        // Dovecot Server Configuration (Phase 2 mail server — IMAP/POP3/LMTP)
        Route::prefix('mail/dovecot')->name('mail.dovecot.')->group(function () {
            Route::get('/', [AdminDovecotConfigController::class, 'index'])->name('index');
            Route::patch('/', [AdminDovecotConfigController::class, 'update'])->name('update');
            Route::post('/reset', [AdminDovecotConfigController::class, 'resetToDefaults'])->name('reset');
            Route::get('/export', [AdminDovecotConfigController::class, 'exportConf'])->name('export');
            Route::post('/reload', [AdminDovecotConfigController::class, 'reload'])->name('reload');
            Route::post('/restart', [AdminDovecotConfigController::class, 'restart'])->name('restart');
            Route::post('/test', [AdminDovecotConfigController::class, 'testConfig'])->name('test');
            Route::delete('/sessions/{sessionId}', [AdminDovecotConfigController::class, 'killSession'])->name('sessions.kill');
        });

        // Rspamd / Anti-Spam Server Configuration (Phase 2 mail server)
        Route::prefix('mail/rspamd')->name('mail.rspamd.')->group(function () {
            Route::get('/', [AdminRspamdConfigController::class, 'index'])->name('index');
            Route::patch('/', [AdminRspamdConfigController::class, 'update'])->name('update');
            Route::post('/reset', [AdminRspamdConfigController::class, 'resetToDefaults'])->name('reset');
            Route::get('/export', [AdminRspamdConfigController::class, 'exportConf'])->name('export');
            Route::post('/reload', [AdminRspamdConfigController::class, 'reload'])->name('reload');
            Route::post('/restart', [AdminRspamdConfigController::class, 'restart'])->name('restart');
            Route::post('/learn-spam', [AdminRspamdConfigController::class, 'learnSpam'])->name('learn-spam');
            Route::post('/learn-ham', [AdminRspamdConfigController::class, 'learnHam'])->name('learn-ham');
            Route::post('/bayes-reset', [AdminRspamdConfigController::class, 'bayesReset'])->name('bayes-reset');
        });

        // Support Tickets routes kaldırıldı — eklenti entegrasyonu (WHMCS/WiseCP) ile dış sistemden
        // Route::get('/tickets', ...
        // Route::get('/tickets/{ticket}', ...

        // Outbound Webhooks (Phase 1.5 — panel → WHMCS event push)
        Route::prefix('webhooks/outbound')->name('webhooks.outbound.')->group(function () {
            Route::get('/', [AdminOutboundWebhookController::class, 'index'])->name('index');
            Route::post('/', [AdminOutboundWebhookController::class, 'store'])->name('store');
            Route::patch('/{endpoint}', [AdminOutboundWebhookController::class, 'update'])->name('update');
            Route::post('/{endpoint}/toggle', [AdminOutboundWebhookController::class, 'toggle'])->name('toggle');
            Route::post('/{endpoint}/test', [AdminOutboundWebhookController::class, 'testEndpoint'])->name('test');
            Route::get('/{endpoint}/logs', [AdminOutboundWebhookController::class, 'viewLogs'])->name('logs');
            Route::delete('/{endpoint}', [AdminOutboundWebhookController::class, 'destroy'])->name('destroy');
        });

        // Monitoring — Prometheus Exporter + Grafana (Phase 3)
        Route::prefix('monitoring')->name('monitoring.')->group(function () {
            Route::get('/', [AdminMonitoringController::class, 'index'])->name('index');
            Route::post('/regenerate-token', [AdminMonitoringController::class, 'regenerateToken'])->name('regenerate-token');
            Route::get('/grafana/{dashboard}', [AdminMonitoringController::class, 'downloadDashboard'])->name('grafana.download');
            Route::get('/alerts', [AdminMonitoringController::class, 'downloadAlerts'])->name('alerts.download');
        });

        // Phase 4 — AI Asistan Yönetimi
        Route::prefix('ai')->name('ai.')->group(function () {
            Route::get('/settings', [AiSettingsController::class, 'index'])->name('settings');
            Route::patch('/settings', [AiSettingsController::class, 'update'])->name('settings.update');
            Route::post('/settings/test/{provider}', [AiSettingsController::class, 'testProvider'])->name('settings.test');
            Route::patch('/settings/api-key/{provider}', [AiSettingsController::class, 'updateApiKey'])->name('settings.api-key');
        });

        // Phase 4 — Plugin Marketplace & Manager
        Route::prefix('plugins')->name('plugins.')->group(function () {
            // Listings
            Route::get('/', [PluginController::class, 'index'])->name('index');
            Route::get('/installed', [PluginController::class, 'installed'])->name('installed');

            // Marketplace (more specific first — must precede /{slug})
            Route::get('/marketplace', [PluginController::class, 'marketplace'])->name('marketplace');
            Route::get('/marketplace/{slug}', [PluginController::class, 'marketplaceShow'])->name('marketplace.show');
            Route::post('/marketplace/{slug}/install', [PluginController::class, 'install'])->name('marketplace.install');
            Route::post('/marketplace/{slug}/rate', [PluginController::class, 'rate'])->name('marketplace.rate');

            // Vendor placeholder
            Route::get('/vendor', [PluginController::class, 'vendor'])->name('vendor');

            // Upload + legacy install endpoint
            Route::post('/upload', [PluginController::class, 'uploadInstall'])->name('upload');
            Route::post('/install/{slug}', [PluginController::class, 'install'])->name('install');

            // Installed plugin management (more specific routes first)
            Route::post('/{slug}/update', [PluginController::class, 'update'])->name('update');
            Route::post('/{slug}/rate', [PluginController::class, 'rate'])->name('rate');
            Route::post('/{slug}/toggle', [PluginController::class, 'toggle'])->name('toggle');
            Route::patch('/{slug}/settings', [PluginController::class, 'settingsUpdate'])->name('settings.update');
            Route::delete('/{slug}', [PluginController::class, 'uninstall'])->name('uninstall');
            Route::get('/{slug}', [PluginController::class, 'show'])->name('show');
        });

        // Phase 5 — License Key Management
        Route::prefix('license')->name('license.')->group(function () {
            Route::get('/', [LicenseController::class, 'index'])->name('index');
            Route::get('/activate', [LicenseController::class, 'index'])->name('activate');
            Route::post('/activate', [LicenseController::class, 'activate'])->name('activate.store');
            Route::post('/deactivate', [LicenseController::class, 'deactivate'])->name('deactivate');
            Route::post('/heartbeat', [LicenseController::class, 'triggerHeartbeat'])->name('heartbeat');

            // Feature toggle (admin override) — Adim 2
            Route::post('/feature/toggle', [LicenseController::class, 'toggleFeature'])->name('feature.toggle');
            Route::post('/feature/reset', [LicenseController::class, 'resetFeature'])->name('feature.reset');

            // Adim 4 — manuel JWT yapistirma + IP transfer
            Route::post('/paste-jwt', [LicenseController::class, 'pasteJwt'])->name('paste-jwt');
            Route::post('/ip-transfer', [LicenseController::class, 'ipTransfer'])->name('ip-transfer');
        });

        // Webhook Playground — rewritten (Phase 2: inbound logger + outbound sender + replay)
        Route::prefix('webhook-playground')->name('webhook-playground.')->group(function () {
            Route::get('/', [WebhookPlaygroundController::class, 'index'])->name('index');
            Route::post('/inbox', [WebhookPlaygroundController::class, 'createInbox'])->name('inbox.create');
            Route::delete('/inbox/{slug}', [WebhookPlaygroundController::class, 'deleteInbox'])->name('inbox.delete');
            Route::get('/request/{id}', [WebhookPlaygroundController::class, 'viewRequest'])->name('request.show');
            Route::post('/outbound', [WebhookPlaygroundController::class, 'sendOutbound'])->name('outbound');
            Route::post('/replay/{id}', [WebhookPlaygroundController::class, 'replay'])->name('replay');
        });

        // Phase 5 — API Tester (embedded Swagger-like explorer)
        Route::prefix('api-tester')->name('api-tester.')->group(function () {
            Route::get('/', [ApiTesterController::class, 'index'])->name('index');
            Route::post('/execute', [ApiTesterController::class, 'execute'])->name('execute');
        });

        // Phase 5 — E-posta Şablonları
        Route::prefix('email-templates')->name('email-templates.')->group(function () {
            Route::get('/', [AdminEmailTemplateController::class, 'index'])->name('index');
            Route::get('/{key}/preview', [AdminEmailTemplateController::class, 'preview'])->name('preview');
            Route::post('/test', [AdminEmailTemplateController::class, 'sendTest'])->name('test');
        });

        // Knowledge Base routes kaldırıldı — eklenti entegrasyonu için
        // Hosting firması kendi KB sistemini (WHMCS/WiseCP) entegre edebilir

        // Phase 5 — Public Status Page management
        Route::prefix('status')->name('status.')->group(function () {
            Route::get('/', [AdminStatusManagerController::class, 'index'])->name('index');

            // Components
            Route::post('/components', [AdminStatusManagerController::class, 'storeComponent'])->name('components.store');
            Route::patch('/components/{component}', [AdminStatusManagerController::class, 'updateComponent'])->name('components.update');
            Route::delete('/components/{component}', [AdminStatusManagerController::class, 'destroyComponent'])->name('components.destroy');
            Route::post('/components/{component}/check', [AdminStatusManagerController::class, 'runCheck'])->name('components.check');

            // Incidents
            Route::get('/incidents', [AdminStatusManagerController::class, 'incidents'])->name('incidents');
            Route::post('/incidents', [AdminStatusManagerController::class, 'storeIncident'])->name('incidents.store');
            Route::patch('/incidents/{incident}', [AdminStatusManagerController::class, 'updateIncident'])->name('incidents.update');
            Route::post('/incidents/{incident}/updates', [AdminStatusManagerController::class, 'addIncidentUpdate'])->name('incidents.update.post');
            Route::post('/incidents/{incident}/resolve', [AdminStatusManagerController::class, 'resolveIncident'])->name('incidents.resolve');

            // Maintenance
            Route::get('/maintenance', [AdminStatusManagerController::class, 'maintenance'])->name('maintenance');
            Route::post('/maintenance', [AdminStatusManagerController::class, 'storeMaintenance'])->name('maintenance.store');
            Route::post('/maintenance/{id}/start', [AdminStatusManagerController::class, 'startMaintenance'])->name('maintenance.start');
            Route::post('/maintenance/{id}/complete', [AdminStatusManagerController::class, 'completeMaintenance'])->name('maintenance.complete');
        });
    });

// Stop impersonate available outside admin guard (customer panel)
Route::middleware('auth')->post('/impersonate/stop', [AdminImpersonateController::class, 'stop'])->name('impersonate.stop');

Route::middleware(['auth', 'customer'])
    ->prefix('panel')
    ->name('customer.')
    ->group(function () {
        Route::get('/', [CustomerDashboardController::class, 'index'])->name('dashboard');
        Route::get('/dashboard', [CustomerDashboardController::class, 'index']);

        Route::get('/domains', [CustomerDomainController::class, 'index'])->name('domains.index');
        Route::post('/domains', [CustomerDomainController::class, 'store'])->name('domains.store');
        // Faz I — One-click setup wizard (must register BEFORE {domain} routes so /wizard isn't bound as id)
        Route::get('/domains/wizard', [CustomerDomainController::class, 'wizard'])->name('domains.wizard');
        Route::post('/domains/wizard', [CustomerDomainController::class, 'wizardStore'])->name('domains.wizard.store');
        Route::get('/domains/{domain}/wizard-status', [CustomerDomainController::class, 'wizardStatus'])->name('domains.wizard.status');
        Route::delete('/domains/{domain}', [CustomerDomainController::class, 'destroy'])->name('domains.destroy');
        Route::patch('/domains/{domain}/php-version', [CustomerDomainController::class, 'updatePhpVersion'])->name('domains.php-version');
        Route::post('/domains/{domain}/reprovision-system-subdomains', [CustomerDomainController::class, 'reprovisionSystemSubdomains'])->name('domains.reprovision-system-subdomains');
        // Phase 2 — wildcard subdomain (*.example.com)
        Route::post('/domains/{domain}/wildcard/enable',  [CustomerDomainController::class, 'enableWildcard'])->name('domains.wildcard-enable');
        Route::post('/domains/{domain}/wildcard/disable', [CustomerDomainController::class, 'disableWildcard'])->name('domains.wildcard-disable');

        // Subdomains
        Route::get('/subdomains', [CustomerSubdomainController::class, 'index'])->name('subdomains.index');
        Route::post('/subdomains', [CustomerSubdomainController::class, 'store'])->name('subdomains.store');
        Route::delete('/subdomains/{domain}', [CustomerSubdomainController::class, 'destroy'])->name('subdomains.destroy');

        // Epic 7 — Database
        Route::get('/databases', [CustomerDatabaseController::class, 'index'])->name('databases.index');
        Route::post('/databases', [CustomerDatabaseController::class, 'storeDatabase'])->name('databases.store');
        // Faz I: Wizard (atomic DB + user + grant)
        Route::get('/databases/wizard', [CustomerDatabaseController::class, 'wizardShow'])->name('databases.wizard');
        Route::post('/databases/wizard', [CustomerDatabaseController::class, 'wizardStore'])->name('databases.wizard.store');
        // Faz I: phpMyAdmin SSO POST (returns JSON {redirect_url})
        Route::post('/databases/{database}/pma-sso', [CustomerDatabaseController::class, 'pmaSso'])->name('databases.pma-sso');
        // Faz I: DB detail page + per-table operations + search
        Route::get('/databases/{database}', [CustomerDatabaseController::class, 'show'])->name('databases.show');
        Route::post('/databases/{database}/tables/action', [CustomerDatabaseController::class, 'tableAction'])->name('databases.tables.action');
        Route::post('/databases/{database}/search', [CustomerDatabaseController::class, 'search'])->name('databases.search');
        Route::delete('/databases/{database}', [CustomerDatabaseController::class, 'destroyDatabase'])->name('databases.destroy');
        Route::post('/databases/{database}/import', [CustomerDatabaseController::class, 'import'])->name('databases.import');
        Route::get('/databases/{database}/export', [CustomerDatabaseController::class, 'export'])->name('databases.export');
        Route::get('/databases/{database}/phpmyadmin', [CustomerDatabaseController::class, 'phpmyadmin'])->name('databases.phpmyadmin');
        Route::post('/databases/users', [CustomerDatabaseController::class, 'storeUser'])->name('databases.users.store');
        Route::delete('/databases/users/{user}', [CustomerDatabaseController::class, 'destroyUser'])->name('databases.users.destroy');
        Route::post('/databases/users/{user}/password', [CustomerDatabaseController::class, 'passwordUser'])->name('databases.users.password');
        Route::post('/databases/grant', [CustomerDatabaseController::class, 'grant'])->name('databases.grant');
        Route::post('/databases/revoke', [CustomerDatabaseController::class, 'revoke'])->name('databases.revoke');

        // Epic 8 — DNS
        Route::get('/dns', [CustomerDnsController::class, 'index'])->name('dns.index');
        Route::post('/dns/zones', [CustomerDnsController::class, 'storeZone'])->name('dns.zones.store');
        Route::delete('/dns/zones/{zone}', [CustomerDnsController::class, 'destroyZone'])->name('dns.zones.destroy');
        Route::post('/dns/zones/{zone}/records', [CustomerDnsController::class, 'storeRecord'])->name('dns.records.store');
        Route::patch('/dns/records/{record}', [CustomerDnsController::class, 'updateRecord'])->name('dns.records.update');
        Route::delete('/dns/records/{record}', [CustomerDnsController::class, 'destroyRecord'])->name('dns.records.destroy');
        Route::get('/dns/records/{record}/propagation', [CustomerDnsController::class, 'propagation'])->name('dns.propagation');

        // DNSSEC (Phase 2) — zone-wide KSK+ZSK + DS record yönetimi.
        // Müşteri panelden tek tıkla aktive eder, dönen DS kayıtlarını registrar'a girer.
        Route::post('/dns/zones/{zone}/dnssec/enable', [CustomerDnsController::class, 'enableDnssec'])->name('dns.dnssec.enable');
        Route::post('/dns/zones/{zone}/dnssec/disable', [CustomerDnsController::class, 'disableDnssec'])->name('dns.dnssec.disable');
        Route::post('/dns/zones/{zone}/dnssec/rollover', [CustomerDnsController::class, 'rolloverDnssec'])->name('dns.dnssec.rollover');

        // Epic 11 — FTP/SFTP + Phase 1.5 multi-user
        Route::get('/ftp', [CustomerFtpController::class, 'index'])->name('ftp.index');
        Route::post('/ftp', [CustomerFtpController::class, 'store'])->name('ftp.store');
        Route::delete('/ftp/{ftpUser}', [CustomerFtpController::class, 'destroy'])->name('ftp.destroy');
        Route::post('/ftp/{ftpUser}/password', [CustomerFtpController::class, 'updatePassword'])->name('ftp.password');
        Route::patch('/ftp/{ftpUser}/quota', [CustomerFtpController::class, 'setQuota'])->name('ftp.quota');
        Route::post('/ftp/{ftpUser}/disconnect', [CustomerFtpController::class, 'disconnectAll'])->name('ftp.disconnect');

        Route::get('/account', [CustomerAccountController::class, 'show'])->name('account.show');
        Route::get('/account/resources', [CustomerAccountController::class, 'resources'])->name('account.resources');

        // Epic 9 — SSL (cPanel SSL/TLS Manager parity, Faz H)
        Route::prefix('ssl')->name('ssl.')->group(function () {
            Route::get('/', [CustomerSslController::class, 'index'])->name('index');
            Route::post('/', [CustomerSslController::class, 'store'])->name('store');
            Route::post('/{certificate}/renew', [CustomerSslController::class, 'renew'])->name('renew');
            Route::delete('/{certificate}', [CustomerSslController::class, 'destroy'])->name('destroy');

            // Faz H — cPanel parity
            Route::post('/csr', [CustomerSslController::class, 'generateCsr'])->name('csr');
            Route::post('/manual-install', [CustomerSslController::class, 'installManual'])->name('manual-install');
            Route::post('/decode', [CustomerSslController::class, 'decodeCert'])->name('decode');
            Route::patch('/{domain}/force-https', [CustomerSslController::class, 'toggleForceHttps'])->name('force-https');
            Route::patch('/{domain}/hsts', [CustomerSslController::class, 'toggleHsts'])->name('hsts');
            Route::patch('/autossl', [CustomerSslController::class, 'updateAutoSsl'])->name('autossl');
            Route::post('/autossl/run', [CustomerSslController::class, 'runAutoSslNow'])->name('autossl.run');
        });

        // Customer Self-Snapshots
        Route::prefix('snapshots')->name('snapshots.')->group(function () {
            Route::get('/', [CustomerSnapshotController::class, 'index'])->name('index');
            Route::post('/', [CustomerSnapshotController::class, 'store'])->name('store');
            Route::post('/{snapshot}/restore', [CustomerSnapshotController::class, 'restore'])->name('restore');
            Route::get('/{snapshot}/download', [CustomerSnapshotController::class, 'download'])->name('download');
            Route::delete('/{snapshot}', [CustomerSnapshotController::class, 'destroy'])->name('destroy');
        });

        // Epic 15 — Backups
        Route::get('/backups', [CustomerBackupController::class, 'index'])->name('backups.index');
        Route::post('/backups', [CustomerBackupController::class, 'store'])->name('backups.store');
        Route::post('/backups/{backup}/restore', [CustomerBackupController::class, 'restore'])->name('backups.restore');
        Route::delete('/backups/{backup}', [CustomerBackupController::class, 'destroy'])->name('backups.destroy');

        // WebDisk (WebDAV)
        Route::get('/webdisk', [CustomerWebdiskController::class, 'index'])->name('webdisk.index');
        Route::post('/webdisk', [CustomerWebdiskController::class, 'store'])->name('webdisk.store');
        Route::post('/webdisk/{webdisk}/password', [CustomerWebdiskController::class, 'updatePassword'])->name('webdisk.password');
        Route::post('/webdisk/{webdisk}/toggle', [CustomerWebdiskController::class, 'toggle'])->name('webdisk.toggle');
        Route::delete('/webdisk/{webdisk}', [CustomerWebdiskController::class, 'destroy'])->name('webdisk.destroy');

        // Image Manager (cPanel "Images")
        Route::get('/images', [CustomerImageController::class, 'index'])->name('images.index');
        Route::post('/images/resize', [CustomerImageController::class, 'resize'])->name('images.resize');
        Route::post('/images/thumbnail', [CustomerImageController::class, 'thumbnail'])->name('images.thumbnail');
        Route::post('/images/convert', [CustomerImageController::class, 'convert'])->name('images.convert');
        Route::post('/images/rotate', [CustomerImageController::class, 'rotate'])->name('images.rotate');
        Route::post('/images/img-tag', [CustomerImageController::class, 'imgTag'])->name('images.img-tag');

        // Epic 10 — File Manager
        Route::get('/files', [CustomerFileController::class, 'index'])->name('files.index');
        Route::post('/files/upload', [CustomerFileController::class, 'upload'])->middleware('throttle:uploads')->name('files.upload');
        Route::post('/files/mkdir', [CustomerFileController::class, 'mkdir'])->name('files.mkdir');
        Route::post('/files/rename', [CustomerFileController::class, 'rename'])->name('files.rename');
        Route::delete('/files', [CustomerFileController::class, 'destroy'])->name('files.destroy');
        Route::get('/files/download', [CustomerFileController::class, 'download'])->name('files.download');
        Route::get('/files/read', [CustomerFileController::class, 'read'])->name('files.read');
        Route::post('/files/save', [CustomerFileController::class, 'save'])->name('files.save');
        Route::post('/files/zip', [CustomerFileController::class, 'zip'])->name('files.zip');
        Route::post('/files/unzip', [CustomerFileController::class, 'unzip'])->name('files.unzip');
        Route::post('/files/chmod', [CustomerFileController::class, 'chmod'])->name('files.chmod');
        Route::post('/files/chown', [CustomerFileController::class, 'chown'])->name('files.chown');
        Route::post('/files/copy', [CustomerFileController::class, 'copy'])->name('files.copy');
        Route::post('/files/move', [CustomerFileController::class, 'move'])->name('files.move');
        Route::get('/files/tree', [CustomerFileController::class, 'tree'])->name('files.tree');
        Route::get('/files/search', [CustomerFileController::class, 'search'])->name('files.search');

        // Trash — cPanel-style soft-delete bin (.trash/)
        Route::get('/files/trash', [CustomerFileController::class, 'trashIndex'])->name('files.trash.index');
        Route::delete('/files/trash', [CustomerFileController::class, 'trashEmpty'])->name('files.trash.empty');
        Route::post('/files/trash/restore', [CustomerFileController::class, 'trashRestore'])->name('files.trash.restore');

        // Email — mailbox CRUD ve subroute'lar
        Route::get('/email', [CustomerEmailController::class, 'index'])->name('email.index');
        Route::post('/email', [CustomerEmailController::class, 'store'])->name('email.store');

        // {emailAccount} routes — numeric ID constraint (autoresponders/filters/spam gibi static path'lerle çakışmayı önler)
        Route::get('/email/{emailAccount}', [CustomerEmailController::class, 'show'])->name('email.show')->whereNumber('emailAccount');
        Route::patch('/email/{emailAccount}/password', [CustomerEmailController::class, 'updatePassword'])->name('email.update-password')->whereNumber('emailAccount');
        Route::delete('/email/{emailAccount}', [CustomerEmailController::class, 'destroy'])->name('email.destroy')->whereNumber('emailAccount');

        // One-click Webmail SSO (token-based, cache-backed) + Apple .mobileconfig profile
        Route::post('/email/{emailAccount}/webmail-sso', [CustomerEmailController::class, 'webmailSso'])->name('email.webmail-sso')->whereNumber('emailAccount');
        Route::get('/email/{emailAccount}/mobileconfig', [CustomerEmailController::class, 'downloadMobileConfig'])->name('email.mobileconfig')->whereNumber('emailAccount');
        Route::post('/email/forwarders', [CustomerEmailController::class, 'storeForwarder'])->name('email.forwarders.store');
        Route::delete('/email/forwarders/{forwarder}', [CustomerEmailController::class, 'destroyForwarder'])->name('email.forwarders.destroy');

        Route::get('/email/autoresponders', [CustomerEmailController::class, 'autoresponders'])->name('email.autoresponders.index');
        Route::post('/email/autoresponders', [CustomerEmailController::class, 'storeAutoresponder'])->name('email.autoresponders.store');
        Route::delete('/email/autoresponders/{autoresponder}', [CustomerEmailController::class, 'destroyAutoresponder'])->name('email.autoresponders.destroy');
        Route::post('/email/autoresponders/{autoresponder}/toggle', [CustomerEmailController::class, 'toggleAutoresponder'])->name('email.autoresponders.toggle');

        // Webmail (Roundcube/SnappyMail SSO)
        Route::get('/email/webmail', [CustomerWebmailController::class, 'index'])->name('email.webmail.index');
        Route::get('/email/webmail/{emailAccount}/open', [CustomerWebmailController::class, 'open'])->name('email.webmail.open');

        Route::get('/email/filters', [CustomerEmailController::class, 'filters'])->name('email.filters.index');
        Route::post('/email/filters', [CustomerEmailController::class, 'storeFilter'])->name('email.filters.store');
        Route::delete('/email/filters/{id}', [CustomerEmailController::class, 'destroyFilter'])->name('email.filters.destroy');
        Route::post('/email/filters/{id}/toggle', [CustomerEmailController::class, 'toggleFilter'])->name('email.filters.toggle');

        // Mail Kurulum Sihirbazı
        Route::get('/email/setup-guide/{emailAccountId?}', [CustomerMailSetupController::class, 'index'])->name('email.setup');
        Route::post('/email/dns-auto-setup/{domain}', [CustomerMailSetupController::class, 'applyDnsRecords'])->name('email.dns-auto');
        Route::get('/email/dns-suggest/{domain}', [CustomerMailSetupController::class, 'suggestDnsRecords'])->name('email.dns-suggest');

        // Legacy mail placeholder (sidebar still references mail.index)
        Route::get('/mail', fn () => redirect()->route('customer.email.index'))->name('mail.index');

        // Cron Jobs
        Route::get('/cron', [CustomerCronController::class, 'index'])->name('cron.index');
        Route::post('/cron', [CustomerCronController::class, 'store'])->name('cron.store');
        Route::patch('/cron/{cronJob}', [CustomerCronController::class, 'update'])->name('cron.update');
        Route::delete('/cron/{cronJob}', [CustomerCronController::class, 'destroy'])->name('cron.destroy');

        // Redirects
        Route::get('/redirects', [CustomerRedirectController::class, 'index'])->name('redirects.index');
        Route::post('/redirects', [CustomerRedirectController::class, 'store'])->name('redirects.store');
        Route::delete('/redirects/{redirect}', [CustomerRedirectController::class, 'destroy'])->name('redirects.destroy');

        // Security
        Route::prefix('security')->name('security.')->group(function () {
            Route::get('/ip-blocker', [CustomerSecurityController::class, 'ipBlocker'])->name('ip-blocker');
            Route::post('/ip-blocker', [CustomerSecurityController::class, 'storeIpBlock'])->name('ip-blocker.store');
            Route::delete('/ip-blocker/{id}', [CustomerSecurityController::class, 'destroyIpBlock'])->name('ip-blocker.destroy');
            Route::get('/hotlink', [CustomerSecurityController::class, 'hotlink'])->name('hotlink');
            Route::patch('/hotlink', [CustomerSecurityController::class, 'updateHotlink'])->name('hotlink.update');
            Route::get('/ssh-keys', [CustomerSecurityController::class, 'sshKeys'])->name('ssh-keys');
            Route::post('/ssh-keys', [CustomerSecurityController::class, 'storeSshKey'])->name('ssh-keys.store');
            Route::delete('/ssh-keys/{id}', [CustomerSecurityController::class, 'destroySshKey'])->name('ssh-keys.destroy');
            Route::get('/error-pages', [CustomerSecurityController::class, 'errorPages'])->name('error-pages');
            Route::post('/error-pages', [CustomerSecurityController::class, 'storeErrorPage'])->name('error-pages.store');
            Route::delete('/error-pages/{id}', [CustomerSecurityController::class, 'destroyErrorPage'])->name('error-pages.destroy');
            Route::get('/directory-privacy', [CustomerSecurityController::class, 'directoryPrivacy'])->name('directory-privacy');
            Route::post('/directory-privacy', [CustomerSecurityController::class, 'storeDirectoryPrivacy'])->name('directory-privacy.store');
            Route::delete('/directory-privacy/{id}', [CustomerSecurityController::class, 'destroyDirectoryPrivacy'])->name('directory-privacy.destroy');
            Route::post('/directory-privacy/{id}/toggle', [CustomerSecurityController::class, 'toggleDirectoryPrivacy'])->name('directory-privacy.toggle');
        });

        // Stats
        Route::prefix('stats')->name('stats.')->group(function () {
            Route::get('/', [CustomerStatsController::class, 'index'])->name('index');
            Route::get('/resources', [CustomerStatsController::class, 'resources'])->name('resources');
            Route::get('/bandwidth', [CustomerBandwidthController::class, 'index'])->name('bandwidth');
            Route::get('/visitors', [CustomerStatsController::class, 'visitors'])->name('visitors');
            Route::get('/errors', [CustomerStatsController::class, 'errors'])->name('errors');
        });

        // PHP Configuration (MultiPHP INI Editor)
        Route::prefix('php')->name('php.')->group(function () {
            Route::get('/', [CustomerPhpController::class, 'index'])->name('index');
            Route::patch('/{domain}', [CustomerPhpController::class, 'update'])->name('update');
            Route::delete('/{domain}/reset', [CustomerPhpController::class, 'reset'])->name('reset');
        });

        // PHP Error Log (cPanel "Errors" muadili) — Phase 2
        Route::prefix('php-errors')->name('php-errors.')->group(function () {
            Route::get('/', [CustomerPhpErrorLogController::class, 'index'])->name('index');
            Route::get('/live', [CustomerPhpErrorLogController::class, 'live'])->name('live');
            Route::post('/clear', [CustomerPhpErrorLogController::class, 'clear'])->name('clear');
            Route::get('/download', [CustomerPhpErrorLogController::class, 'download'])->name('download');
        });

        // Personal API Tokens (Sanctum)
        Route::prefix('api-tokens')->name('api-tokens.')->group(function () {
            Route::get('/', [CustomerApiTokenController::class, 'index'])->name('index');
            Route::post('/', [CustomerApiTokenController::class, 'store'])->name('store');
            Route::delete('/{id}', [CustomerApiTokenController::class, 'destroy'])->name('destroy');
        });

        // Customer Tickets routes kaldırıldı — hosting firması dış sistem (WHMCS/WiseCP) entegre eder

        // WordPress Toolkit (Phase 2)
        Route::prefix('wp')->name('wp.')->group(function () {
            // ── Mevcut rotalar (Phase 1) ──────────────────────────────────
            Route::get('/', [CustomerWordPressToolkitController::class, 'index'])->name('index');
            Route::post('/{app}/update', [CustomerWordPressToolkitController::class, 'update'])->name('update');
            Route::post('/{app}/toggle-auto-update', [CustomerWordPressToolkitController::class, 'toggleAutoUpdate'])->name('toggle-auto-update');
            Route::get('/{app}/login', [CustomerWordPressToolkitController::class, 'loginAsAdmin'])->name('login');
            Route::post('/{app}/clone', [CustomerWordPressToolkitController::class, 'clone'])->name('clone');

            // ── Staging (önce — çakışmayı önler) ─────────────────────────
            Route::get('/staging/{staging}', [CustomerWordPressToolkitController::class, 'staging'])->name('staging.show');
            Route::post('/staging/{staging}/push', [CustomerWordPressToolkitController::class, 'pushStaging'])->name('staging.push');
            Route::delete('/staging/{staging}', [CustomerWordPressToolkitController::class, 'deleteStaging'])->name('staging.delete');

            // ── Plugin yönetimi ───────────────────────────────────────────
            Route::get('/{app}/plugins', [CustomerWordPressToolkitController::class, 'plugins'])->name('plugins');
            Route::post('/{app}/plugins/install', [CustomerWordPressToolkitController::class, 'pluginInstall'])->name('plugins.install');
            Route::post('/{app}/plugins/{slug}/activate', [CustomerWordPressToolkitController::class, 'pluginActivate'])->name('plugins.activate');
            Route::post('/{app}/plugins/{slug}/deactivate', [CustomerWordPressToolkitController::class, 'pluginDeactivate'])->name('plugins.deactivate');
            Route::post('/{app}/plugins/{slug}/update', [CustomerWordPressToolkitController::class, 'pluginUpdate'])->name('plugins.update');
            Route::delete('/{app}/plugins/{slug}', [CustomerWordPressToolkitController::class, 'pluginDelete'])->name('plugins.delete');

            // ── Tema yönetimi ─────────────────────────────────────────────
            Route::get('/{app}/themes', [CustomerWordPressToolkitController::class, 'themes'])->name('themes');
            Route::post('/{app}/themes/{slug}/activate', [CustomerWordPressToolkitController::class, 'themeActivate'])->name('themes.activate');
            Route::delete('/{app}/themes/{slug}', [CustomerWordPressToolkitController::class, 'themeDelete'])->name('themes.delete');

            // ── Kullanıcı yönetimi ────────────────────────────────────────
            Route::get('/{app}/users', [CustomerWordPressToolkitController::class, 'users'])->name('users');
            Route::post('/{app}/users', [CustomerWordPressToolkitController::class, 'userCreate'])->name('users.create');
            Route::delete('/{app}/users/{userId}', [CustomerWordPressToolkitController::class, 'userDelete'])->name('users.delete');
            Route::post('/{app}/users/{userId}/reset-password', [CustomerWordPressToolkitController::class, 'userResetPassword'])->name('users.reset-password');

            // ── Ayarlar & Araçlar ─────────────────────────────────────────
            Route::post('/{app}/debug', [CustomerWordPressToolkitController::class, 'debug'])->name('debug');
            Route::post('/{app}/maintenance', [CustomerWordPressToolkitController::class, 'maintenance'])->name('maintenance');
            Route::post('/{app}/harden', [CustomerWordPressToolkitController::class, 'harden'])->name('harden');
            Route::post('/{app}/search-replace', [CustomerWordPressToolkitController::class, 'searchReplace'])->name('search-replace');
            Route::get('/{app}/db-export', [CustomerWordPressToolkitController::class, 'dbExport'])->name('db-export');
            Route::get('/{app}/cron', [CustomerWordPressToolkitController::class, 'cron'])->name('cron');
            Route::post('/{app}/cron/run', [CustomerWordPressToolkitController::class, 'runCron'])->name('cron.run');

            // ── Staging oluştur ───────────────────────────────────────────
            Route::get('/{app}/staging', [CustomerWordPressToolkitController::class, 'staging'])->name('staging');
            Route::post('/{app}/staging', [CustomerWordPressToolkitController::class, 'createStaging'])->name('staging.create');

            // ── Show (en sona — {app} wildcard diğerlerine çakışmasın) ────
            Route::get('/{app}', [CustomerWordPressToolkitController::class, 'show'])->name('show');
        });

        // App Installer (Softaculous-lite)
        Route::prefix('apps')->name('apps.')->group(function () {
            Route::get('/', [CustomerAppInstallerController::class, 'catalog'])->name('catalog');
            Route::get('/installed', [CustomerAppInstallerController::class, 'installed'])->name('installed');
            Route::get('/{slug}', [CustomerAppInstallerController::class, 'show'])->name('show');
            Route::post('/{slug}', [CustomerAppInstallerController::class, 'install'])->name('install');
            Route::delete('/installed/{app}', [CustomerAppInstallerController::class, 'uninstall'])->name('uninstall');
        });

        // Git Version Control (cPanel "Git Version Control" muadili)
        Route::prefix('git')->name('git.')->group(function () {
            Route::get('/', [CustomerGitController::class, 'index'])->name('index');
            Route::post('/', [CustomerGitController::class, 'store'])->name('store');
            Route::post('/{id}/pull', [CustomerGitController::class, 'pull'])->name('pull');
            Route::post('/{id}/deploy', [CustomerGitController::class, 'deploy'])->name('deploy');
            Route::delete('/{id}', [CustomerGitController::class, 'destroy'])->name('destroy');
        });

        // Disk Usage Analyzer (cPanel "Disk Usage" muadili)
        Route::get('/disk-usage', [CustomerDiskUsageController::class, 'index'])->name('disk-usage.index');

        // Resource Usage Monitor (cPanel "Resource Usage" muadili) — Phase 2
        // CPU/RAM/IO grafikleri + canlı cgroup-read + paket limit gösterimi
        Route::prefix('resources')->name('resources.')->group(function () {
            Route::get('/', [CustomerResourceUsageController::class, 'index'])->name('index');
            Route::get('/live', [CustomerResourceUsageController::class, 'live'])->name('live');
            Route::get('/series', [CustomerResourceUsageController::class, 'series'])->name('series');
        });

        // Mailing Lists (Mailman benzeri)
        Route::prefix('email/mailing-lists')->name('email.mailing-lists.')->group(function () {
            Route::get('/', [CustomerMailingListController::class, 'index'])->name('index');
            Route::post('/', [CustomerMailingListController::class, 'store'])->name('store');
            Route::delete('/{list}', [CustomerMailingListController::class, 'destroy'])->name('destroy');
        });

        // Email Address Importer (cPanel Address Importer muadili)
        Route::prefix('email/importer')->name('email.importer.')->group(function () {
            Route::get('/', [CustomerEmailImporterController::class, 'index'])->name('index');
            Route::post('/preview', [CustomerEmailImporterController::class, 'preview'])->name('preview');
            Route::post('/commit', [CustomerEmailImporterController::class, 'commit'])->name('commit');
            Route::get('/template/{type}', [CustomerEmailImporterController::class, 'template'])->name('template');
        });

        // Email Deliverability (DKIM/SPF/DMARC status per domain)
        Route::prefix('email/deliverability')->name('email.deliverability.')->group(function () {
            Route::get('/', [CustomerEmailDeliverabilityController::class, 'index'])->name('index');
            Route::get('/{domain}', [CustomerEmailDeliverabilityController::class, 'show'])->name('show');
        });

        // GnuPG Keys (PGP email encryption)
        Route::prefix('security/gpg')->name('security.gpg.')->group(function () {
            Route::get('/', [CustomerGpgKeyController::class, 'index'])->name('index');
            Route::post('/', [CustomerGpgKeyController::class, 'store'])->name('store');
            Route::post('/import', [CustomerGpgKeyController::class, 'import'])->name('import');
            Route::get('/{id}/download', [CustomerGpgKeyController::class, 'download'])->name('download');
            Route::delete('/{id}', [CustomerGpgKeyController::class, 'destroy'])->name('destroy');
        });

        // Spam Filter (SpamAssassin config per email)
        Route::prefix('email/spam')->name('email.spam.')->group(function () {
            Route::get('/', [CustomerSpamFilterController::class, 'index'])->name('index');
            Route::patch('/{emailAccount}', [CustomerSpamFilterController::class, 'update'])->name('update');
        });

        // Leech Protection (brute force protection per path)
        Route::prefix('security/leech')->name('security.leech.')->group(function () {
            Route::get('/', [CustomerLeechProtectionController::class, 'index'])->name('index');
            Route::post('/', [CustomerLeechProtectionController::class, 'store'])->name('store');
            Route::delete('/{id}', [CustomerLeechProtectionController::class, 'destroy'])->name('destroy');
        });

        // ModSecurity per-site (cPanel ModSecurity Tools — per-domain WAF on/off + exceptions)
        Route::prefix('security/modsec')->name('security.modsec.')->group(function () {
            Route::get('/', [CustomerModSecurityController::class, 'index'])->name('index');
            Route::post('/domains/{domain}/toggle', [CustomerModSecurityController::class, 'toggleDomain'])->name('toggle');
            Route::post('/domains/{domain}/exceptions', [CustomerModSecurityController::class, 'addException'])->name('exception.add');
            Route::delete('/domains/{domain}/exceptions/{ruleId}', [CustomerModSecurityController::class, 'removeException'])->name('exception.remove');
        });

        // Optimize Website (mod_deflate + mod_expires)
        Route::prefix('optimize')->name('optimize.')->group(function () {
            Route::get('/', [CustomerOptimizeWebsiteController::class, 'index'])->name('index');
            Route::patch('/', [CustomerOptimizeWebsiteController::class, 'update'])->name('update');
        });

        // Index Manager (directory listing visibility)
        Route::prefix('indexes')->name('indexes.')->group(function () {
            Route::get('/', [CustomerIndexManagerController::class, 'index'])->name('index');
            Route::post('/', [CustomerIndexManagerController::class, 'store'])->name('store');
            Route::delete('/{id}', [CustomerIndexManagerController::class, 'destroy'])->name('destroy');
        });

        // 2FA Self-Service (UI wrapper — uses Fortify routes for POST/DELETE)
        Route::get('/account/two-factor', [CustomerTwoFactorController::class, 'index'])->name('account.two-factor.index');
        // Onay sonrası recovery codes'u tekrar görmek için ayrı endpoint;
        // password.confirm middleware son 3 saat içinde re-auth zorunlu kılar.
        Route::get('/account/two-factor/recovery-codes', [CustomerTwoFactorController::class, 'viewRecoveryCodes'])
            ->middleware('password.confirm')
            ->name('account.two-factor.recovery-codes');

        // Email Routing (per-domain mail routing mode + MX)
        Route::prefix('email/routing')->name('email.routing.')->group(function () {
            Route::get('/', [CustomerEmailRoutingController::class, 'index'])->name('index');
            Route::patch('/{domain}', [CustomerEmailRoutingController::class, 'update'])->name('update');
        });

        // Track Delivery (customer-scoped mail logs)
        Route::prefix('email/tracking')->name('email.tracking.')->group(function () {
            Route::get('/', [CustomerEmailTrackingController::class, 'index'])->name('index');
            Route::get('/export', [CustomerEmailTrackingController::class, 'export'])->name('export');
            Route::get('/{mailId}/detail', [CustomerEmailTrackingController::class, 'detail'])->name('detail');
        });

        // BoxTrapper (challenge-response anti-spam)
        Route::prefix('email/boxtrapper')->name('email.boxtrapper.')->group(function () {
            Route::get('/', [CustomerBoxTrapperController::class, 'index'])->name('index');
            Route::patch('/{emailAccount}', [CustomerBoxTrapperController::class, 'update'])->name('update');
            Route::post('/queue/{queueId}/release', [CustomerBoxTrapperController::class, 'releaseFromQueue'])->name('queue.release');
            Route::post('/queue/{queueId}/whitelist', [CustomerBoxTrapperController::class, 'whitelistFromQueue'])->name('queue.whitelist');
            Route::delete('/queue/{queueId}', [CustomerBoxTrapperController::class, 'deleteFromQueue'])->name('queue.delete');
        });

        // Default Address (catch-all per domain)
        Route::prefix('email/default-address')->name('email.default-address.')->group(function () {
            Route::get('/', [CustomerEmailDefaultAddressController::class, 'index'])->name('index');
            Route::patch('/{domain}', [CustomerEmailDefaultAddressController::class, 'update'])->name('update');
        });

        // Email Disk Usage + Quota Editor
        Route::prefix('email/disk-usage')->name('email.disk-usage.')->group(function () {
            Route::get('/', [CustomerEmailDiskUsageController::class, 'index'])->name('index');
            Route::patch('/mailboxes/{emailAccount}/quota', [CustomerEmailDiskUsageController::class, 'updateQuota'])->name('quota.update');
            Route::post('/mailboxes/{emailAccount}/expunge', [CustomerEmailDiskUsageController::class, 'expungeTrash'])->name('expunge');
            Route::post('/mailboxes/{emailAccount}/compact', [CustomerEmailDiskUsageController::class, 'compactMailbox'])->name('compact');
        });

        // MIME Types & Apache Handlers
        Route::prefix('mime-types')->name('mime-types.')->group(function () {
            Route::get('/', [CustomerMimeTypesController::class, 'index'])->name('index');
            Route::post('/mime', [CustomerMimeTypesController::class, 'storeMime'])->name('mime.store');
            Route::delete('/mime/{id}', [CustomerMimeTypesController::class, 'destroyMime'])->name('mime.destroy');
            Route::post('/handler', [CustomerMimeTypesController::class, 'storeHandler'])->name('handler.store');
            Route::delete('/handler/{id}', [CustomerMimeTypesController::class, 'destroyHandler'])->name('handler.destroy');
        });

        // Domain Aliases / Parked Domains
        Route::prefix('domains/aliases')->name('domains.aliases.')->group(function () {
            Route::get('/', [CustomerDomainAliasController::class, 'index'])->name('index');
            Route::post('/', [CustomerDomainAliasController::class, 'store'])->name('store');
            Route::delete('/{id}', [CustomerDomainAliasController::class, 'destroy'])->name('destroy');
        });

        // Phase 4 — Push Notifications: customer prefix'inden çıkarıldı,
        // /auth grubuna taşındı (admin + customer ortak — bkz. yukarıdaki bölüm).

        // Phase 4 — AI Assistant
        // throttle:ai-chat AppServiceProvider'da RateLimiter::for('ai-chat', ...) ile
        // tanımlı; üretim token/cost drain'i önler.
        Route::post('/api/ai/chat',    [AiAssistantController::class, 'chat'])->middleware('throttle:ai-chat')->name('ai.chat');
        Route::post('/api/ai/stream',  [AiAssistantController::class, 'stream'])->middleware('throttle:ai-chat')->name('ai.stream');
        Route::get('/api/ai/history',  [AiAssistantController::class, 'history'])->middleware('throttle:60,1')->name('ai.history');
        Route::delete('/api/ai/history', [AiAssistantController::class, 'clear'])->middleware('throttle:10,1')->name('ai.clear');
    });

// ════════════════════════════════════════════════════════════════════════════
// Phase 5 — Onboarding / Product Tour (shared: customer + admin)
// ════════════════════════════════════════════════════════════════════════════
Route::middleware('auth')
    ->prefix('api/onboarding')
    ->name('onboarding.')
    ->group(function () {
        Route::get('/', [OnboardingController::class, 'show'])->name('show');
        Route::post('/complete-tour', [OnboardingController::class, 'completeTour'])->name('complete-tour');
        Route::post('/dismiss-tip', [OnboardingController::class, 'dismissTip'])->name('dismiss-tip');
        Route::post('/reset-tour', [OnboardingController::class, 'resetTour'])->name('reset-tour');
    });

// ════════════════════════════════════════════════════════════════════════════
// Reseller Panel — /reseller/*
// ════════════════════════════════════════════════════════════════════════════
Route::middleware(['auth', 'reseller'])
    ->prefix('reseller')
    ->name('reseller.')
    ->group(function () {
        Route::get('/', [ResellerDashboardController::class, 'index'])->name('dashboard');
        Route::get('/dashboard', [ResellerDashboardController::class, 'index']);

        // Müşteri hesapları (salt okunur liste + detay)
        Route::get('/accounts', [ResellerAccountsController::class, 'index'])->name('accounts.index');
        Route::get('/accounts/{account}', [ResellerAccountsController::class, 'show'])->name('accounts.show');

        // Alt-paketler (CRUD)
        Route::get('/sub-packages', [ResellerSubPackagesController::class, 'index'])->name('sub-packages.index');
        Route::post('/sub-packages', [ResellerSubPackagesController::class, 'store'])->name('sub-packages.store');
        Route::patch('/sub-packages/{subPackage}', [ResellerSubPackagesController::class, 'update'])->name('sub-packages.update');
        Route::delete('/sub-packages/{subPackage}', [ResellerSubPackagesController::class, 'destroy'])->name('sub-packages.destroy');

        // Markalama (self-servis)
        Route::get('/branding', [ResellerBrandingController::class, 'index'])->name('branding.index');
        Route::patch('/branding', [ResellerBrandingController::class, 'update'])->name('branding.update');
        Route::post('/branding/logo', [ResellerBrandingController::class, 'uploadLogo'])->middleware('throttle:uploads')->name('branding.logo');
        // Phase 2: white-label diagnostic + re-apply
        Route::get('/branding/status', [ResellerBrandingController::class, 'status'])->name('branding.status');
        Route::post('/branding/reapply', [ResellerBrandingController::class, 'reapply'])->name('branding.reapply');

        // Gelir (salt okunur)
        Route::get('/revenue', [ResellerRevenueController::class, 'index'])->name('revenue.index');
    });

// ════════════════════════════════════════════════════════════════════════════
// Public Webhooks — harici sistem POST'ları (GitHub/GitLab/Bitbucket/playground)
//
// Bu endpoint'ler CSRF muafiyetine sahip (`withoutMiddleware` ile VerifyCsrfToken
// kaldırıldı), çünkü external sistem CSRF token gönderemez. Auth path'teki signed
// secret / slug'a dayanır + throttle 60/dk.
//
// URL geriye dönük korunur: /webhooks/git/{secret} ve /webhooks/inbox/{slug}.
// ════════════════════════════════════════════════════════════════════════════
Route::post('/webhooks/git/{secret}', [CustomerGitController::class, 'webhook'])
    ->withoutMiddleware([\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class])
    ->middleware('throttle:60,1')
    ->name('webhooks.git');

Route::any('/webhooks/inbox/{slug}', [WebhookInboxController::class, 'receive'])
    ->withoutMiddleware([\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class])
    ->middleware('throttle:60,1')
    ->name('webhooks.inbox');

// Webhook Playground inbound receiver (Phase 2 — admin sandbox)
// Any HTTP method captured + logged. HMAC verify if inbox has saved secret.
Route::any('/webhooks/playground/{slug}', [WebhookPlaygroundController::class, 'inboundReceive'])
    ->withoutMiddleware([\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class])
    ->middleware('throttle:120,1')
    ->name('webhooks.playground');


// ════════════════════════════════════════════════════════════════════════════
// Prometheus Metrics Endpoint — /metrics
// METRICS_TOKEN env set edilmişse Bearer/X-Prometheus-Token doğrulaması yapılır.
// ════════════════════════════════════════════════════════════════════════════
Route::get('/metrics', MetricsController::class)->name('metrics');

// ════════════════════════════════════════════════════════════════════════════
// phpMyAdmin alias routes — auth-gated redirect to configured phpMyAdmin URL.
// Eski (auth-suz) global /phpmyadmin-open route'u open-redirect riski yaratıyordu;
// artık auth middleware altında + ?db= query sadece allowed-chars whitelist'inden geçer.
// ════════════════════════════════════════════════════════════════════════════
$pmaRedirect = function (\Illuminate\Http\Request $request) {
    $base = rtrim(config('onoxsoft.phpmyadmin_url', '/phpmyadmin/'), '/');
    $db = $request->query('db');

    // ?db= parametresi sadece [A-Za-z0-9_-]+ kabul eder — injection / SSRF amaçlı
    // path traversal veya scheme manipülasyonunu engeller.
    if ($db !== null && ! preg_match('/^[A-Za-z0-9_-]{1,64}$/', $db)) {
        $db = null;
    }

    return redirect()->away($base.'/'.($db ? '?db='.urlencode($db) : ''));
};

Route::middleware('auth')->group(function () use ($pmaRedirect) {
    Route::get('/phpmyadmin-open', $pmaRedirect)->name('phpmyadmin');
});

Route::middleware(['auth', 'admin'])
    ->prefix('admin')
    ->name('admin.mysql.phpmyadmin.')
    ->group(function () use ($pmaRedirect) {
        Route::get('/mysql/phpmyadmin/open', $pmaRedirect)->name('open');
    });

require __DIR__.'/auth.php';
