<?php

use App\Http\Controllers\Admin\AdminManagementController;
use App\Http\Controllers\Admin\AnnouncementController;
use App\Http\Controllers\Admin\BlogController;
use App\Http\Controllers\Admin\CustomReportController;
use App\Http\Controllers\Admin\BrandController;
use App\Http\Controllers\Admin\ChatController as AdminChatController;
use App\Http\Controllers\Admin\KnowledgebaseController;
use App\Http\Controllers\Admin\LanguageManagerController;
use App\Http\Controllers\Admin\PageController;
use App\Http\Controllers\Admin\TagController;
use App\Http\Controllers\Admin\WorkflowController;
use App\Http\Controllers\Admin\SlaPlanController;
use App\Http\Controllers\Admin\QuoteController;
use App\Http\Controllers\Admin\Auth\ConfirmablePasswordController;
// use App\Http\Controllers\Admin\Auth\EmailVerificationNotificationController;
use App\Http\Controllers\Admin\Auth\AuthenticatedSessionController;
use App\Http\Controllers\Admin\TwoFactorController;
use App\Http\Controllers\Admin\Auth\PasswordController;
use App\Http\Controllers\Admin\Auth\EmailVerificationPromptController;
use App\Http\Controllers\Admin\Auth\VerifyEmailController;
use App\Http\Controllers\Admin\BasketController;
use App\Http\Controllers\Admin\BillingController;
use App\Http\Controllers\Admin\CancellationRequestController;
use App\Http\Controllers\Admin\ClientBalanceController;
use App\Http\Controllers\Admin\ContractController;
use App\Http\Controllers\Admin\ClientController;
use App\Http\Controllers\Admin\ClientCustomFieldController;
use App\Http\Controllers\Admin\CommunicationTemplateController;
use App\Http\Controllers\Admin\CurrencyController;
use App\Http\Controllers\Admin\DashboardController;
use App\Http\Controllers\Admin\DownloadController;
use App\Http\Controllers\Admin\DomainCostController;
use App\Http\Controllers\Admin\EmailCampaignController;
use App\Http\Controllers\Admin\EmailMarketingController;
use App\Http\Controllers\Admin\EmailTemplateTestController;
use App\Http\Controllers\Admin\EscalationRuleController;
use App\Http\Controllers\Admin\FraudModuleController;
use App\Http\Controllers\Admin\FraudModuleSettingsController;
use App\Http\Controllers\Admin\InvoiceBillingController;
use App\Http\Controllers\Admin\LanguageController;
use App\Http\Controllers\Admin\LogController;
use App\Http\Controllers\Admin\NetworkStatusController;
use App\Http\Controllers\Admin\NetworkToolsController;
use App\Http\Controllers\Admin\OrderController;
use App\Http\Controllers\Admin\PaymentGatewayController;
use App\Http\Controllers\Admin\QueueController;
use App\Http\Controllers\Admin\PermissionManagementController;
use App\Http\Controllers\Admin\PostImageUploadController;
use App\Http\Controllers\Admin\ProductCategoryController;
use App\Http\Controllers\Admin\ProductConfigOptionController;
use App\Http\Controllers\Admin\ProductConfigOptionGroupController;
use App\Http\Controllers\Admin\ProductController;
use App\Http\Controllers\Admin\ProductGroupController;
use App\Http\Controllers\Admin\ProfileController;
use App\Http\Controllers\Admin\ReportsController;
use App\Http\Controllers\Admin\RoleManagementController;
use App\Http\Controllers\Admin\ServiceCostController;
use App\Http\Controllers\Admin\SettingsController;
use App\Http\Controllers\Admin\SmsReportController;
use App\Http\Controllers\Admin\TaxController;
use App\Http\Controllers\Admin\TicketController;
use App\Http\Controllers\Admin\TicketDepartmentController;
use App\Http\Controllers\Admin\TicketPredefinedReplyController;
use App\Http\Controllers\Admin\TicketStatusController;
use App\Http\Controllers\Admin\TldController;
use App\Http\Controllers\Admin\AffiliateController;
use App\Http\Controllers\Admin\UploadController;
use Illuminate\Support\Facades\Route;

Route::prefix('admin')->name('admin.')->middleware([\App\Http\Middleware\Admin\BlockAdminOnBrandDomains::class, \App\Http\Middleware\Admin\AdminIpWhitelist::class])->group(function () {
    // Redirect /admin to dashboard (or login if not authenticated)
    Route::get('/', function () {
        return auth()->guard('admin')->check()
            ? redirect()->route('admin.dashboard')
            : redirect()->route('admin.login');
    });

    // Guest routes
    // PRC-161: SEC-Critical — /admin/register PUBLIC route'u kaldırıldı.
    // Eski davranış: tek POST request ile random e-mail + password ile admin
    // hesabı oluşturuluyor + hemen Auth::login (full panel takeover).
    // İlk admin için: `sail artisan db:seed --class=AdminSeeder` veya
    // mevcut admin paneli `/admin/admin-management` üzerinden create.
    Route::middleware('guest:admin')->group(function () {
        Route::get('login', [AuthenticatedSessionController::class, 'create'])->name('login');
        // PRC-167: SEC-Critical — POST login route'una 'admin-login' named
        // limiter (20/min/IP + 5/min/email). LoginRequest::throttleKey()
        // zaten 5/key uyguluyor (email|ip in-request), bu route-level
        // savunma password spraying'i ek olarak engelliyor.
        Route::post('login', [AuthenticatedSessionController::class, 'store'])
            ->middleware('throttle:admin-login');
    });

    // 2FA verification (authenticated but not yet 2FA verified)
    // PRC-166: SEC-Critical — POST verify route '2fa-verify' named limiter
    // ile korunuyor (5/min/user + 20/min/IP). 6 hane TOTP brute-force engellendi.
    Route::middleware(['auth:admin'])->group(function () {
        Route::get('/2fa/verify', [TwoFactorController::class, 'showVerify'])->name('2fa.verify');
        Route::post('/2fa/verify', [TwoFactorController::class, 'verify'])
            ->middleware('throttle:2fa-verify')
            ->name('2fa.verify.post');
        // PRC-770 — email/sms OTP yeniden gönder (canResend + throttle guard)
        Route::post('/2fa/resend', [TwoFactorController::class, 'resend'])
            ->middleware('throttle:3,1')
            ->name('2fa.resend');
    });

    // Logout (always accessible when authenticated)
    Route::middleware(['auth:admin'])->group(function () {
        Route::post('logout', [AuthenticatedSessionController::class, 'destroy'])->name('logout');
    });

    // Authenticated routes
    // PRC-248: `auth.session` middleware password change'den sonra diğer
    // device session'larını otomatik invalidate eder. AuthenticateSession
    // session'a `password_hash_admin` yazar; password değiştiğinde DB hash
    // ile mismatch → diğer cihazlardaki request'ler kendiliğinden logout.
    Route::middleware(['auth:admin', 'auth.session', 'verified', \App\Http\Middleware\Admin\EnsureTwoFactorVerified::class])->group(function () {
        Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');

        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');
        Route::get('verify-email', EmailVerificationPromptController::class)->name('verification.notice');
        Route::get('verify-email/{id}/{hash}', VerifyEmailController::class)->middleware(['signed', 'throttle:6,1'])->name('verification.verify');
        // Route::post('email/verification-notification', [EmailVerificationNotificationController::class, 'store'])->middleware('throttle:6,1')->name('verification.send');
        // PRC-252 — confirm-password endpoints enable Laravel's `password.confirm`
        // middleware contract. Sensitive routes redirect here when
        // `auth.password_confirmed_at` session value is missing/stale.
        Route::get('confirm-password', [ConfirmablePasswordController::class, 'show'])->name('password.confirm');
        Route::post('confirm-password', [ConfirmablePasswordController::class, 'store'])->middleware('throttle:6,1');

        // PRC-252 — admin password change gated by `password.confirm` (fresh
        // password re-entry within config('auth.password_timeout') = 3h) +
        // throttle 5/15min to slow brute-force on `current_password` rule.
        // Middleware param routes the redirect to admin-namespaced confirm
        // route (default `password.confirm` doesn't exist outside admin).
        Route::put('password', [PasswordController::class, 'update'])
            ->middleware(['password.confirm:admin.password.confirm', 'throttle:5,15'])
            ->name('password.update');
        // 2FA Setup (inside authenticated + 2FA verified group)
        Route::get('/2fa/setup', [TwoFactorController::class, 'setup'])->name('2fa.setup');
        Route::post('/2fa/enable', [TwoFactorController::class, 'enable'])->name('2fa.enable');
        Route::post('/2fa/confirm', [TwoFactorController::class, 'confirm'])->name('2fa.confirm');
        Route::delete('/2fa/disable', [TwoFactorController::class, 'disable'])->name('2fa.disable');

        // File Download (secure)
        Route::get('/file-download/{attachment}', [UploadController::class, 'download'])->name('file-download');
        Route::get('/file-preview/{attachment}', [UploadController::class, 'preview'])->name('file-preview');

        // Client Routes — PRC-185 RBAC coverage. Group-level `can:view clients`
        // gates the entire client-detail surface; mutations layer create/edit/
        // delete keys on top.
        Route::prefix('clients')->name('clients.')->middleware('can:view clients')->group(function () {
            Route::get('/', [ClientController::class, 'index'])->name('index');
            Route::get('/create', [ClientController::class, 'create'])->middleware('can:create clients')->name('create');
            Route::post('/', [ClientController::class, 'store'])->middleware('can:create clients')->name('store');

            // Client Detail Tabs
            Route::get('/{client}/overview', [ClientController::class, 'overview'])->name('overview');
            Route::get('/{client}/edit', [ClientController::class, 'edit'])->middleware('can:edit clients')->name('edit');
            Route::put('/{client}', [ClientController::class, 'update'])->middleware('can:edit clients')->name('update');
            Route::delete('/{client}', [ClientController::class, 'destroy'])->middleware('can:delete clients')->name('destroy');
            Route::post('/{client}/reset-2fa', [ClientController::class, 'resetTwoFactor'])->middleware('can:edit clients')->name('reset-2fa');

            Route::get('/{client}/products', [ClientController::class, 'products'])->name('products');
            // PRC-752 — soft-deleted hizmeti geri al (web form; {productId} int: trashed model-binding'e takılmasın)
            Route::post('/{client}/products/{productId}/restore', [ClientController::class, 'restoreProduct'])->middleware('can:edit clients')->name('products.restore');
            Route::get('/{client}/products/create', [ClientController::class, 'productCreate'])->middleware('can:edit clients')->name('products.create');
            Route::post('/{client}/products', [ClientController::class, 'productStore'])->middleware('can:edit clients')->name('products.store');
            Route::get('/{client}/products/{product}/detail', [ClientController::class, 'productDetail'])->name('products.detail');
            Route::put('/{client}/products/{product}', [ClientController::class, 'productUpdate'])->middleware('can:edit clients')->name('products.update');
            Route::post('/{client}/products/{product}/send-welcome-email', [ClientController::class, 'productSendWelcomeEmail'])->middleware('can:edit clients')->name('products.send-welcome-email');
            Route::post('/{client}/products/{product}/transfer-ownership', [ClientController::class, 'productTransferOwnership'])->middleware('can:edit clients')->name('products.transfer-ownership');
            Route::get('/{client}/domains', [ClientController::class, 'domains'])->name('domains');
            Route::get('/{client}/domains/{domain}/detail', [ClientController::class, 'domainDetail'])->name('domains.detail');
            Route::put('/{client}/domains/{domain}', [ClientController::class, 'domainUpdate'])->middleware('can:edit clients')->name('domains.update');
            Route::post('/{client}/domains/{domain}/renewal-order', [ClientController::class, 'domainCreateRenewalOrder'])
                ->middleware('can:edit clients')
                ->name('domains.create-renewal-order');
            Route::get('/{client}/tickets', [ClientController::class, 'tickets'])->name('tickets');
            Route::get('/{client}/emails', [ClientController::class, 'emails'])->name('emails');
            Route::get('/{client}/logs', [ClientController::class, 'logs'])->middleware('can:view logs')->name('logs');
            Route::get('/{client}/invoices', [ClientController::class, 'invoices'])->middleware('can:view invoices')->name('invoices');
            Route::get('/{client}/transactions', [ClientController::class, 'transactions'])->middleware('can:view transactions')->name('transactions');
            Route::get('/{client}/orders', [ClientController::class, 'orders'])->middleware('can:view orders')->name('orders');
            Route::get('/{client}/quotes', [ClientController::class, 'quotes'])->middleware('can:view quotes')->name('quotes');
            Route::get('/{client}/reseller', [ClientController::class, 'reseller'])->name('reseller');
            Route::put('/{client}/reseller', [ClientController::class, 'resellerUpdate'])->middleware('can:edit clients')->name('reseller.update');
            Route::get('/{client}/authorizations', [ClientController::class, 'authorizations'])->name('authorizations');
            Route::get('/{client}/consents', [ClientController::class, 'consents'])->name('consents');
        });

        // Authorization mutations (revoke, resend invitation) live under routes/api.php
        // behind Bearer-token auth. This avoids the admin CSRF path and matches
        // the project convention for admin AJAX actions.

        // Client Custom Fields Routes
        Route::prefix('settings/client-custom-fields')->name('client-custom-fields.')->group(function () {
            Route::get('/', [ClientCustomFieldController::class, 'index'])->name('index');
            Route::get('/create', [ClientCustomFieldController::class, 'create'])->name('create');
            Route::post('/', [ClientCustomFieldController::class, 'store'])->name('store');
            Route::get('/{customField}/edit', [ClientCustomFieldController::class, 'edit'])->name('edit');
            Route::put('/{customField}', [ClientCustomFieldController::class, 'update'])->name('update');
        });

        // Language Routes
        Route::prefix('settings/languages')->name('settings.languages.')->group(function () {
            Route::get('', [LanguageController::class, 'index'])->name('index');
            Route::post('', [LanguageController::class, 'store'])->name('store');
            // PRC-554 — Dedicated edit page (modal'dan page'e migration);
            // slug-locale-lock URL'lerini de yönetir.
            Route::get('/{language}/edit', [LanguageController::class, 'edit'])->middleware('can:view languages')->name('edit');
            Route::put('/{language}', [LanguageController::class, 'update'])->name('update');
            // PRC-554 — Locale-aware route slug'larını dil bazında güncelle.
            Route::put('/{language}/route-slugs', [LanguageController::class, 'updateRouteSlugs'])->middleware('can:update languages')->name('route-slugs.update');
        });

        // Currency Routes
        Route::prefix('settings/currencies')->name('settings.currencies.')->group(function () {
            Route::get('/', [CurrencyController::class, 'index'])->name('index');
            Route::post('/settings', [CurrencyController::class, 'saveSettings'])
                ->middleware('can:manage settings')->name('settings.update');
            Route::put('/{currency}', [CurrencyController::class, 'update'])->name('update');
        });

        // Payment Gateways Routes
        // PRC-1070: decrypted gateway cred'leri tutar — izinsiz erişim/düzenleme YASAK.
        Route::prefix('payment-gateways')->name('payment-gateways.')->middleware('can:view payment gateways')->group(function () {
            Route::get('/', [PaymentGatewayController::class, 'index'])->name('index');
            Route::get('/{name}/edit', [PaymentGatewayController::class, 'edit'])->name('edit');
            Route::put('/{name}', [PaymentGatewayController::class, 'update'])->middleware('can:update payment gateways')->name('update');
        });

        // PRC-327 / PRC-398..403 — Module Management UI (universal pattern).
        // Permission gating + audit logging come from the ManagesModules
        // trait + LogsAdminActivity on each controller.
        $moduleFamilies = [
            'sms-modules'           => \App\Http\Controllers\Admin\SmsModuleController::class,
            'email-modules'         => \App\Http\Controllers\Admin\EmailModuleController::class,
            'citizenship-modules'   => \App\Http\Controllers\Admin\CitizenshipModuleController::class,
            'dns-providers'         => \App\Http\Controllers\Admin\DnsProviderController::class,
            'currency-providers'    => \App\Http\Controllers\Admin\CurrencyProviderController::class,
        ];
        foreach ($moduleFamilies as $prefix => $controller) {
            Route::prefix($prefix)->name($prefix . '.')->group(function () use ($controller) {
                Route::get('/', [$controller, 'index'])->name('index');
                Route::get('/{module}/edit', [$controller, 'edit'])->name('edit');
                Route::put('/{module}', [$controller, 'update'])->name('update');
                Route::post('/{module}/toggle', [$controller, 'toggle'])->name('toggle');
                Route::post('/{module}/test', [$controller, 'test'])->name('test');
            });
        }

        // PRC-649 — DNS defaults (active provider + auto-setup toggle) moved
        // from the settings page onto /admin/dns-providers.
        Route::post('dns-providers/defaults', [\App\Http\Controllers\Admin\DnsProviderController::class, 'saveDefaults'])
            ->middleware('can:manage dns providers')
            ->name('dns-providers.save-defaults');

        // Product Categories
        Route::prefix('product/product-categories')->name('product-categories.')->group(function () {
            Route::get('/', [ProductCategoryController::class, 'index'])->name('index');
            Route::get('/create', [ProductCategoryController::class, 'create'])->name('create');
            Route::post('/', [ProductCategoryController::class, 'store'])->name('store');
            Route::get('/{productCategory}/edit', [ProductCategoryController::class, 'edit'])->name('edit');
            Route::put('/{productCategory}', [ProductCategoryController::class, 'update'])->name('update');
        });

        // Product Groups
        Route::prefix('product/product-groups')->name('product-groups.')->group(function () {
            Route::get('/', [ProductGroupController::class, 'index'])->name('index');
            Route::post('/', [ProductGroupController::class, 'store'])->name('store');
            Route::get('/{productGroup}/edit', [ProductGroupController::class, 'edit'])->name('edit');
            Route::put('/{productGroup}', [ProductGroupController::class, 'update'])->name('update');
        });

        // Product Config Options
        Route::prefix('product/product-config-options')->name('product-config-options.')->group(function () {
            Route::get('/', [ProductConfigOptionController::class, 'index'])->name('index');
            Route::get('/create', [ProductConfigOptionController::class, 'create'])->name('create');
            Route::post('/', [ProductConfigOptionController::class, 'store'])->name('store');
            Route::get('/{productConfigOption}/edit', [ProductConfigOptionController::class, 'edit'])->name('edit');
            Route::put('/{productConfigOption}', [ProductConfigOptionController::class, 'update'])->name('update');
            Route::delete('/{productConfigOption}', [ProductConfigOptionController::class, 'destroy'])->name('destroy');
            Route::post('/{id}/archive', [ProductConfigOptionController::class, 'archive'])->name('archive');
            Route::post('/{id}/restore', [ProductConfigOptionController::class, 'restore'])->name('restore');
            Route::delete('/{id}/force', [ProductConfigOptionController::class, 'forceDelete'])->name('force-delete');
        });

        // Product Config Option Groups
        Route::prefix('product/product-config-option-groups')->name('product-config-option-groups.')->group(function () {
            Route::get('/', [ProductConfigOptionGroupController::class, 'index'])->name('index');
            Route::get('/create', [ProductConfigOptionGroupController::class, 'create'])->name('create');
            Route::post('/', [ProductConfigOptionGroupController::class, 'store'])->name('store');
            Route::get('/{productConfigOptionGroup}/edit', [ProductConfigOptionGroupController::class, 'edit'])->name('edit');
            Route::put('/{productConfigOptionGroup}', [ProductConfigOptionGroupController::class, 'update'])->name('update');
            Route::delete('/{productConfigOptionGroup}', [ProductConfigOptionGroupController::class, 'destroy'])->name('destroy');
            Route::post('/{id}/archive', [ProductConfigOptionGroupController::class, 'archive'])->name('archive');
            Route::post('/{id}/restore', [ProductConfigOptionGroupController::class, 'restore'])->name('restore');
            Route::delete('/{id}/force', [ProductConfigOptionGroupController::class, 'forceDelete'])->name('force-delete');
            Route::post('/{id}/duplicate', [ProductConfigOptionGroupController::class, 'duplicate'])->name('duplicate');
        });

        // Products
        Route::prefix('product/products')->name('products.')->group(function () {
            Route::get('/', [ProductController::class, 'index'])->name('index');
            Route::get('/create', [ProductController::class, 'create'])->name('create');
            Route::post('/', [ProductController::class, 'store'])->middleware('can:create products')->name('store');
            Route::get('/{product}/edit', [ProductController::class, 'edit'])->name('edit');
            Route::put('/{product}', [ProductController::class, 'update'])->middleware('can:update products')->name('update');
            Route::delete('/{product}', [ProductController::class, 'destroy'])->name('destroy');
            Route::get('/group/{group}/options', [ProductController::class, 'getGroupOptions'])->middleware('can:view products')->name('group.options');
            Route::get('/module-fields', [ProductController::class, 'getModuleFields'])->middleware('can:view products')->name('module-fields');
            Route::get('/available-modules', [ProductController::class, 'availableModulesForType'])->middleware('can:view products')->name('available-modules');
        });

        // PRC-60: 3rd-party licenses
        // PRC-1070: LicenseController hiç authorize etmiyordu → route-level gate.
        Route::prefix('licenses')->name('licenses.')->middleware('can:view licenses')->group(function () {
            Route::get('/', [App\Http\Controllers\Admin\LicenseController::class, 'index'])->name('index');
            Route::get('/{license}', [App\Http\Controllers\Admin\LicenseController::class, 'show'])->name('show');
            Route::post('/{license}/manual-issue', [App\Http\Controllers\Admin\LicenseController::class, 'manualIssue'])->middleware('can:manage licenses')->name('manual-issue');
            Route::post('/{license}/revoke', [App\Http\Controllers\Admin\LicenseController::class, 'revoke'])->middleware('can:manage licenses')->name('revoke');
            Route::delete('/{license}', [App\Http\Controllers\Admin\LicenseController::class, 'destroy'])->middleware('can:delete licenses')->name('destroy');
        });

        // Admin Panel - Registrar Routes
        Route::prefix('product/registrars')->name('registrars.')->middleware(['auth:admin'])->group(function () {
            Route::get('/', [App\Http\Controllers\Admin\RegistrarController::class, 'index'])->name('index');
            Route::get('/{name}/edit', [App\Http\Controllers\Admin\RegistrarController::class, 'edit'])->name('edit')->where('name', '[a-zA-Z0-9\-]+');
            Route::put('/{name}', [App\Http\Controllers\Admin\RegistrarController::class, 'update'])->name('update')->where('name', '[a-zA-Z0-9\-]+')->middleware('can:update registrars');
        });

        // TLD Yönetimi - Admin (view ve CRUD)
        Route::prefix('tlds')->name('tlds.')->group(function () {
            Route::get('/', [TldController::class, 'index'])->name('index');
            Route::get('/create', [TldController::class, 'create'])->name('create')->middleware('can:create tlds');
            Route::get('/{tld}/edit', [TldController::class, 'edit'])->name('edit');
            Route::post('/', [TldController::class, 'store'])->name('store');
            Route::put('/{tld}', [TldController::class, 'update'])->name('update');
        });

        // Server Groups
        Route::prefix('server-groups')->name('server-groups.')->group(function () {
            Route::get('/', [App\Http\Controllers\Admin\ServerGroupController::class, 'index'])->name('index');
            Route::get('/create', [App\Http\Controllers\Admin\ServerGroupController::class, 'create'])->name('create');
            Route::post('/', [App\Http\Controllers\Admin\ServerGroupController::class, 'store'])->name('store');
            Route::get('/{serverGroup}/edit', [App\Http\Controllers\Admin\ServerGroupController::class, 'edit'])->name('edit');
            Route::put('/{serverGroup}', [App\Http\Controllers\Admin\ServerGroupController::class, 'update'])->name('update');
        });

        // Servers
        Route::prefix('servers')->name('servers.')->group(function () {
            Route::get('/', [App\Http\Controllers\Admin\ServerController::class, 'index'])->name('index');
            Route::get('/create', [App\Http\Controllers\Admin\ServerController::class, 'create'])->name('create');
            Route::post('/', [App\Http\Controllers\Admin\ServerController::class, 'store'])->name('store');
            Route::get('/{server}/edit', [App\Http\Controllers\Admin\ServerController::class, 'edit'])->name('edit');
            Route::put('/{server}', [App\Http\Controllers\Admin\ServerController::class, 'update'])->name('update');
        });

        // Datacenters (PRC-817 — fiziksel sunucu lokasyon hiyerarşisi)
        Route::prefix('datacenters')->name('datacenters.')->group(function () {
            Route::get('/', [App\Http\Controllers\Admin\DatacenterController::class, 'index'])->name('index');
            Route::get('/create', [App\Http\Controllers\Admin\DatacenterController::class, 'create'])->name('create');
            Route::post('/', [App\Http\Controllers\Admin\DatacenterController::class, 'store'])->name('store');
            Route::get('/{datacenter}/edit', [App\Http\Controllers\Admin\DatacenterController::class, 'edit'])->name('edit');
            Route::put('/{datacenter}', [App\Http\Controllers\Admin\DatacenterController::class, 'update'])->name('update');
        });

        // Racks (PRC-817)
        Route::prefix('racks')->name('racks.')->group(function () {
            Route::get('/', [App\Http\Controllers\Admin\RackController::class, 'index'])->name('index');
            Route::get('/create', [App\Http\Controllers\Admin\RackController::class, 'create'])->name('create');
            Route::post('/', [App\Http\Controllers\Admin\RackController::class, 'store'])->name('store');
            Route::get('/{rack}/edit', [App\Http\Controllers\Admin\RackController::class, 'edit'])->name('edit');
            Route::put('/{rack}', [App\Http\Controllers\Admin\RackController::class, 'update'])->name('update');
        });

        // IP Pools (PRC-22)
        Route::middleware(['permission:view ip pools'])->group(function () {
            // NOTE: settings route MUST be registered BEFORE Route::resource — otherwise the
            // resource's PATCH ip-pools/{pool} update route would catch this URL with pool=settings.
            Route::patch('ip-pools/settings', [\App\Http\Controllers\Admin\IpPoolController::class, 'updateSettings'])
                ->middleware('permission:manage ip allocations')
                ->name('ip-pools.settings.update');
            Route::resource('ip-pools', \App\Http\Controllers\Admin\IpPoolController::class)->parameters(['ip-pools' => 'pool']);
            Route::post('ip-pools/{pool}/import-cidr', [\App\Http\Controllers\Admin\IpPoolController::class, 'importCidr'])->name('ip-pools.import-cidr');
            Route::post('ip-pools/{pool}/addresses', [\App\Http\Controllers\Admin\IpAddressController::class, 'store'])->name('ip-pools.addresses.store');
            Route::patch('ip-addresses/{ip}/reserve', [\App\Http\Controllers\Admin\IpAddressController::class, 'reserve'])->name('ip-addresses.reserve');
            Route::patch('ip-addresses/{ip}/unreserve', [\App\Http\Controllers\Admin\IpAddressController::class, 'unreserve'])->name('ip-addresses.unreserve');
            Route::patch('ip-addresses/{ip}/release', [\App\Http\Controllers\Admin\IpAddressController::class, 'release'])->name('ip-addresses.release');
            Route::patch('ip-addresses/{ip}/force-release', [\App\Http\Controllers\Admin\IpAddressController::class, 'forceRelease'])->middleware('permission:manage ip allocations')->name('ip-addresses.force-release');
            Route::patch('ip-addresses/{ip}/rdns', [\App\Http\Controllers\Admin\IpAddressController::class, 'updateRdns'])->name('ip-addresses.rdns');
            Route::post('client-products/{cp}/import-legacy-ip', [\App\Http\Controllers\Admin\IpAddressController::class, 'importLegacy'])->middleware('permission:manage ip allocations')->name('client-products.import-legacy-ip');
        });

        // Ticket Departments
        Route::prefix('ticket-departments')->name('ticket-departments.')->group(function () {
            Route::get('/', [TicketDepartmentController::class, 'index'])->name('index');
            Route::get('/create', [TicketDepartmentController::class, 'create'])->name('create');
            Route::post('/', [TicketDepartmentController::class, 'store'])->name('store');
            Route::get('/{ticketDepartment}/edit', [TicketDepartmentController::class, 'edit'])->name('edit');
            Route::put('/{ticketDepartment}', [TicketDepartmentController::class, 'update'])->name('update');
            Route::post('/test-mail-connection', [TicketDepartmentController::class, 'testMailConnection'])->middleware('can:update ticket departments')->name('test-mail-connection');
        });

        // Support Announcement Banners (PRC-790, cache-backed)
        Route::prefix('support-banners')->name('support-banners.')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\SupportBannerController::class, 'index'])->middleware('permission:view support banners')->name('index');
            Route::get('/create', [\App\Http\Controllers\Admin\SupportBannerController::class, 'create'])->middleware('permission:manage support banners')->name('create');
            Route::post('/', [\App\Http\Controllers\Admin\SupportBannerController::class, 'store'])->middleware('permission:manage support banners')->name('store');
            Route::get('/{id}/edit', [\App\Http\Controllers\Admin\SupportBannerController::class, 'edit'])->middleware('permission:manage support banners')->name('edit');
            Route::put('/{id}', [\App\Http\Controllers\Admin\SupportBannerController::class, 'update'])->middleware('permission:manage support banners')->name('update');
            Route::delete('/{id}', [\App\Http\Controllers\Admin\SupportBannerController::class, 'destroy'])->middleware('permission:manage support banners')->name('destroy');
        });

        // Ticket Statuses
        Route::prefix('ticket-statuses')->name('ticket-statuses.')->group(function () {
            Route::get('/', [TicketStatusController::class, 'index'])->name('index');
            Route::get('/create', [TicketStatusController::class, 'create'])->name('create');
            Route::post('/', [TicketStatusController::class, 'store'])->name('store');
            Route::get('/{ticketStatus}/edit', [TicketStatusController::class, 'edit'])->name('edit');
            Route::put('/{ticketStatus}', [TicketStatusController::class, 'update'])->name('update');
        });

        // Tickets
        Route::prefix('tickets')->name('tickets.')->group(function () {
            Route::get('/', [TicketController::class, 'index'])->name('index');
            Route::get('/create', [TicketController::class, 'create'])->name('create');
            Route::post('/', [TicketController::class, 'store'])->name('store');
            // PRC-66 — ticket merging (must come before {ticket} param routes)
            Route::get('/merge/search', [\App\Http\Controllers\Admin\TicketMergeController::class, 'search'])->middleware('can:merge tickets')->name('merge.search');
            // PRC-683 — orijinal ham .eml indirme (admin-only; {ticket} wildcard'ından ÖNCE)
            Route::get('/eml/{eml}/download', [\App\Http\Controllers\Admin\TicketOriginalEmailController::class, 'download'])->name('eml.download');
            Route::get('/{ticket}', [TicketController::class, 'show'])->name('show');
            Route::post('/{ticket}/reply', [TicketController::class, 'reply'])->name('reply');
            Route::post('/{ticket}/merge', [\App\Http\Controllers\Admin\TicketMergeController::class, 'merge'])->middleware('can:merge tickets')->name('merge');
        });

        // SMS Reports
        Route::prefix('sms-reports')->name('sms-reports.')->group(function () {
            Route::get('/', [SmsReportController::class, 'index'])->name('index');
        });

        // Ticket Predefined Replies
        Route::prefix('ticket-predefined-replies')->name('ticket-predefined-replies.')->group(function () {
            Route::get('/', [TicketPredefinedReplyController::class, 'index'])->name('index');
            Route::get('/create', [TicketPredefinedReplyController::class, 'create'])->name('create');
            Route::post('/', [TicketPredefinedReplyController::class, 'store'])->name('store');
            Route::get('/{ticketPredefinedReply}/edit', [TicketPredefinedReplyController::class, 'edit'])->name('edit');
            Route::put('/{ticketPredefinedReply}', [TicketPredefinedReplyController::class, 'update'])->name('update');
        });

        // Communication Templates (PRC-619 — tek otorite)
        Route::prefix('communication-templates')->name('communication-templates.')->group(function () {
            Route::get('/', [CommunicationTemplateController::class, 'index'])->name('index');
            Route::get('/create', [CommunicationTemplateController::class, 'create'])->name('create');
            Route::post('/', [CommunicationTemplateController::class, 'store'])->name('store');

            // Test gönderimi (eski email-templates/test)
            // PRC-1070: test-mail gönderimi izinsiz tetiklenemez.
            Route::get('/test', [EmailTemplateTestController::class, 'index'])->middleware('can:view email templates')->name('test');
            Route::post('/test', [EmailTemplateTestController::class, 'test'])->middleware('can:update email templates')->name('test.post');

            Route::get('/{communicationTemplate}/edit', [CommunicationTemplateController::class, 'edit'])->name('edit');
            Route::put('/{communicationTemplate}', [CommunicationTemplateController::class, 'update'])->name('update');
        });

        // Email Marketing
        // PRC-796 — İYS izin senkron durum ekranı
        Route::get('/iys', [\App\Http\Controllers\Admin\IysController::class, 'index'])
            ->middleware('permission:view iys')
            ->name('iys.index');

        Route::prefix('email-marketing')->name('email-marketing.')->group(function () {
            Route::get('/', [EmailMarketingController::class, 'index'])->name('index');
            Route::post('/settings', [EmailMarketingController::class, 'updateSettings'])
                ->middleware('can:manage settings')
                ->name('settings.update');
            Route::get('/create', [EmailMarketingController::class, 'create'])->name('create');
            Route::post('/', [EmailMarketingController::class, 'store'])->name('store');
            Route::get('/{emailMarketing}/edit', [EmailMarketingController::class, 'edit'])->name('edit');
            Route::put('/{emailMarketing}', [EmailMarketingController::class, 'update'])->name('update');

            // PRC-30 — Subscribers tab
            Route::get('/{list}/subscribers',
                [\App\Http\Controllers\Admin\EmailMarketingSubscriberController::class, 'index'])
                ->where('list', '[0-9]+')
                ->middleware('permission:view email marketing')
                ->name('subscribers.index');
        });

        // Email Campaigns
        Route::prefix('email-campaigns')->name('email-campaigns.')->group(function () {
            Route::get('/', [EmailCampaignController::class, 'index'])->name('index');
            Route::get('/create', [EmailCampaignController::class, 'create'])->name('create');
            Route::post('/', [EmailCampaignController::class, 'store'])->name('store');
            Route::get('/{emailCampaign}/edit', [EmailCampaignController::class, 'edit'])->name('edit');
            Route::put('/{emailCampaign}', [EmailCampaignController::class, 'update'])->name('update');

            // PRC-31 — Send/test/cancel
            Route::middleware('permission:send email campaigns')->group(function () {
                Route::post('/{emailCampaign}/send', [\App\Http\Controllers\Admin\EmailCampaignSendController::class, 'send'])->name('send');
                Route::post('/{emailCampaign}/send-test', [\App\Http\Controllers\Admin\EmailCampaignSendController::class, 'sendTest'])->name('send-test');
                Route::post('/{emailCampaign}/cancel', [\App\Http\Controllers\Admin\EmailCampaignSendController::class, 'cancel'])->name('cancel');
            });
        });

        // Escalation Rules
        Route::prefix('escalation-rules')->name('escalation-rules.')->group(function () {
            Route::get('/', [EscalationRuleController::class, 'index'])->name('index');
            Route::get('/create', [EscalationRuleController::class, 'create'])->name('create');
            Route::post('/', [EscalationRuleController::class, 'store'])->name('store');
            Route::get('/{escalationRule}/edit', [EscalationRuleController::class, 'edit'])->name('edit');
            Route::put('/{escalationRule}', [EscalationRuleController::class, 'update'])->name('update');
        });

        // AI Staff Management
        Route::prefix('ai-staff')->name('ai-staff.')->middleware('can:view ai staff')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\AiStaffController::class, 'index'])->name('index');
            Route::get('/create', [\App\Http\Controllers\Admin\AiStaffController::class, 'create'])->name('create');
            Route::post('/', [\App\Http\Controllers\Admin\AiStaffController::class, 'store'])->name('store');
            Route::get('/{aiStaffProfile}/edit', [\App\Http\Controllers\Admin\AiStaffController::class, 'edit'])->name('edit');
            Route::put('/{aiStaffProfile}', [\App\Http\Controllers\Admin\AiStaffController::class, 'update'])->name('update');
            Route::get('/drafts', [\App\Http\Controllers\Admin\AiStaffDraftController::class, 'index'])->name('drafts');
            Route::get('/dashboard', [\App\Http\Controllers\Admin\AiStaffDashboardController::class, 'index'])->name('dashboard');
            Route::get('/training', [\App\Http\Controllers\Admin\AiTrainingController::class, 'index'])->name('training.index');
            Route::get('/training/create', [\App\Http\Controllers\Admin\AiTrainingController::class, 'create'])->name('training.create');
            Route::post('/training', [\App\Http\Controllers\Admin\AiTrainingController::class, 'store'])->name('training.store');
            Route::get('/training/{dataset}/edit', [\App\Http\Controllers\Admin\AiTrainingController::class, 'edit'])->name('training.edit');
            Route::put('/training/{dataset}', [\App\Http\Controllers\Admin\AiTrainingController::class, 'update'])->name('training.update');
        });

        // System Management — Admin Management (PRC-231 RBAC coverage)
        Route::prefix('system/admin-management')->name('admin-management.')->middleware('can:view admin management')->group(function () {
            Route::get('/', [AdminManagementController::class, 'index'])->name('index');
            Route::get('/create', [AdminManagementController::class, 'create'])->middleware('can:create admin management')->name('create');
            Route::post('/', [AdminManagementController::class, 'store'])->middleware('can:create admin management')->name('store');
            Route::get('/{admin}/edit', [AdminManagementController::class, 'edit'])->middleware('can:update admin management')->name('edit');
            Route::put('/{admin}', [AdminManagementController::class, 'update'])->middleware('can:update admin management')->name('update');
        });

        // System Management — Role Management (PRC-231 RBAC coverage)
        Route::prefix('system/role-management')->name('role-management.')->middleware('can:view role management')->group(function () {
            Route::get('/', [RoleManagementController::class, 'index'])->name('index');
            Route::get('/create', [RoleManagementController::class, 'create'])->middleware('can:create role management')->name('create');
            Route::post('/', [RoleManagementController::class, 'store'])->middleware('can:create role management')->name('store');
            Route::get('/{role}/edit', [RoleManagementController::class, 'edit'])->middleware('can:update role management')->name('edit');
            Route::put('/{role}', [RoleManagementController::class, 'update'])->middleware('can:update role management')->name('update');
        });

        // System Management — Permission Management (PRC-231 RBAC coverage)
        Route::prefix('system/permission-management')->name('permission-management.')->middleware('can:view permission management')->group(function () {
            Route::get('/', [PermissionManagementController::class, 'index'])->name('index');
        });

        // Orders
        Route::prefix('orders')->name('orders.')->middleware('can:view orders')->group(function () {
            Route::get('/', [OrderController::class, 'index'])->name('index');
            Route::get('/pending', [OrderController::class, 'pending'])->name('pending');
            Route::get('/cancelled', [OrderController::class, 'cancelled'])->name('cancelled');
            Route::get('/refunds', [OrderController::class, 'refunds'])->name('refunds');
            Route::get('/create', [OrderController::class, 'create'])->name('create');
            Route::post('/', [OrderController::class, 'store'])->name('store');
            Route::get('/{order}', [OrderController::class, 'show'])->name('show');
            Route::get('/{order}/edit', [OrderController::class, 'edit'])->name('edit');
            Route::put('/{order}', [OrderController::class, 'update'])->name('update');
            Route::post('/calculate-totals', [OrderController::class, 'calculateTotals'])->name('calculate-totals');
        });

        // Transactions — PRC-227 RBAC coverage
        Route::prefix('transactions')->name('transactions.')->middleware('can:view transactions')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\TransactionController::class, 'index'])->name('index');
            Route::get('/create', [\App\Http\Controllers\Admin\TransactionController::class, 'create'])->middleware('can:create transactions')->name('create');
            Route::get('/failed', [\App\Http\Controllers\Admin\TransactionController::class, 'failed'])->name('failed');
            Route::get('/add-balance', [\App\Http\Controllers\Admin\TransactionController::class, 'addBalance'])->middleware('can:create transactions')->name('add-balance');
            Route::get('/{transaction}', [\App\Http\Controllers\Admin\TransactionController::class, 'show'])->name('show');
            Route::get('/{transaction}/edit', [\App\Http\Controllers\Admin\TransactionController::class, 'edit'])->middleware('can:update transactions')->name('edit');
        });

        // Fraud Detection
        Route::prefix('fraud')->name('fraud.')->middleware('can:view fraud')->group(function () {
            Route::get('/', [FraudModuleController::class, 'index'])->name('index');
            Route::get('/review', [FraudModuleController::class, 'review'])->name('review');
            Route::post('/{order}/recheck', [FraudModuleController::class, 'recheck'])->middleware('can:manage fraud')->name('recheck');
            Route::post('/{order}/approve', [FraudModuleController::class, 'approve'])->middleware('can:manage fraud')->name('approve');
            Route::post('/{order}/reject', [FraudModuleController::class, 'reject'])->middleware('can:manage fraud')->name('reject');
            Route::get('/{order}/check-details', [FraudModuleController::class, 'checkDetails'])->name('check-details');

            // Fraud Module Settings
            Route::prefix('modules')->name('modules.')->middleware('can:manage fraud')->group(function () {
                Route::get('/', [FraudModuleSettingsController::class, 'index'])->name('index');
                Route::get('/{slug}/edit', [FraudModuleSettingsController::class, 'edit'])->name('edit');
                Route::put('/{slug}', [FraudModuleSettingsController::class, 'update'])->name('update');
                Route::post('/{slug}/test', [FraudModuleSettingsController::class, 'test'])->name('test');
                Route::post('/{slug}/toggle', [FraudModuleSettingsController::class, 'toggle'])->name('toggle');
                Route::post('/priorities', [FraudModuleSettingsController::class, 'updatePriorities'])->name('update-priorities');
            });
        });

        // Store Themes
        Route::prefix('settings/themes')->name('settings.themes.')->middleware('can:manage settings')->group(function () {
            Route::post('/activate', [\App\Http\Controllers\Admin\StoreThemeController::class, 'activate'])->name('activate');
        });

        // Vergilendirme (Taxes) - Admin View
        Route::prefix('settings/taxes')->name('settings.taxes.')->group(function () {
            Route::get('/', [TaxController::class, 'index'])->name('index');
            Route::put('/settings', [TaxController::class, 'updateSettings'])->name('update-settings');
        });

        // Settings Routes
        Route::prefix('settings')->name('settings.')->group(function () {
            Route::get('/', [SettingsController::class, 'index'])->name('index');
            Route::get('/records', [SettingsController::class, 'records'])->name('records');
            Route::put('/', [SettingsController::class, 'update'])->name('update');
        });

        // Service Costs Routes
        Route::prefix('service-costs')->name('service-costs.')->middleware('can:view service costs')->group(function () {
            Route::get('/', [ServiceCostController::class, 'index'])->name('index');
            Route::get('/create', [ServiceCostController::class, 'create'])->name('create');
            Route::post('/', [ServiceCostController::class, 'store'])->name('store');
            Route::get('/{serviceCost}/edit', [ServiceCostController::class, 'edit'])->name('edit');
            Route::put('/{serviceCost}', [ServiceCostController::class, 'update'])->name('update');
            Route::delete('/{serviceCost}', [ServiceCostController::class, 'destroy'])->name('destroy');
        });

        // Domain Costs Routes
        Route::prefix('domain-costs')->name('domain-costs.')->middleware('can:view domain costs')->group(function () {
            Route::get('/', [DomainCostController::class, 'index'])->name('index');
            Route::get('/create', [DomainCostController::class, 'create'])->name('create');
            Route::post('/', [DomainCostController::class, 'store'])->name('store');
            Route::get('/{domainCost}/edit', [DomainCostController::class, 'edit'])->name('edit');
            Route::put('/{domainCost}', [DomainCostController::class, 'update'])->name('update');
            Route::delete('/{domainCost}', [DomainCostController::class, 'destroy'])->name('destroy');
        });

        // Client Balances Routes
        Route::prefix('client-balances')->name('client-balances.')->middleware('can:view client balances')->group(function () {
            Route::get('/', [ClientBalanceController::class, 'index'])->name('index');
            Route::get('/create', [ClientBalanceController::class, 'create'])->name('create');
            Route::post('/add-balance', [ClientBalanceController::class, 'addBalance'])->middleware('can:create client balances')->name('add-balance');
            Route::get('/{client}', [ClientBalanceController::class, 'show'])->name('show');
            Route::get('/{client}/transactions', [ClientBalanceController::class, 'transactions'])->name('transactions');
        });

        // Coupons Routes
        Route::prefix('coupons')->name('coupons.')->middleware('can:view coupons')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\CouponController::class, 'index'])->name('index');
            Route::get('/create', [\App\Http\Controllers\Admin\CouponController::class, 'create'])->name('create');
            Route::post('/', [\App\Http\Controllers\Admin\CouponController::class, 'store'])->name('store');
            Route::get('/{coupon}/edit', [\App\Http\Controllers\Admin\CouponController::class, 'edit'])->name('edit');
            Route::put('/{coupon}', [\App\Http\Controllers\Admin\CouponController::class, 'update'])->name('update');
            Route::get('/{coupon}', [\App\Http\Controllers\Admin\CouponController::class, 'show'])->name('show');
        });

        // Expenses Routes (PRC-814 — Gider & P&L MVP-1)
        // PRC-707 — Data Import / migration tool
        Route::get('data-import', [\App\Http\Controllers\Admin\DataImportController::class, 'index'])
            ->middleware('can:view data imports')->name('data-import.index');

        Route::prefix('expenses')->name('expenses.')->middleware('can:view expenses')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\ExpenseController::class, 'index'])->name('index');
            Route::get('/create', [\App\Http\Controllers\Admin\ExpenseController::class, 'create'])->middleware('can:create expenses')->name('create');
            Route::post('/', [\App\Http\Controllers\Admin\ExpenseController::class, 'store'])->middleware('can:create expenses')->name('store');
            Route::get('/{expense}/edit', [\App\Http\Controllers\Admin\ExpenseController::class, 'edit'])->middleware('can:update expenses')->name('edit');
            Route::put('/{expense}', [\App\Http\Controllers\Admin\ExpenseController::class, 'update'])->middleware('can:update expenses')->name('update');
            Route::get('/{expense}/receipt/{attachment}', [\App\Http\Controllers\Admin\ExpenseController::class, 'downloadReceipt'])->name('receipt.download');
        });

        // SSL Certificates Routes (PRC-1068 — SSL yönetimi + Comodo/reseller manuel-kurulum backstop)
        Route::prefix('ssl-certificates')->name('ssl-certificates.')->middleware('can:view ssl certificates')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\AdminSslCertificateController::class, 'index'])->name('index');
            Route::get('/{cert}/manual-install', [\App\Http\Controllers\Admin\AdminSslCertificateController::class, 'manualInstallForm'])->middleware('can:manage ssl certificates')->name('manual-install');
            Route::post('/{cert}/manual-install', [\App\Http\Controllers\Admin\AdminSslCertificateController::class, 'manualInstall'])->middleware('can:manage ssl certificates')->name('manual-install.store');
            Route::post('/{cert}/revoke', [\App\Http\Controllers\Admin\AdminSslCertificateController::class, 'revoke'])->middleware('can:manage ssl certificates')->name('revoke');
        });

        // Recurring Expenses Routes (PRC-815 — tekrarlayan gider tanımı)
        Route::prefix('recurring-expenses')->name('recurring-expenses.')->middleware('can:view recurring expenses')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\RecurringExpenseController::class, 'index'])->name('index');
            Route::get('/create', [\App\Http\Controllers\Admin\RecurringExpenseController::class, 'create'])->middleware('can:create recurring expenses')->name('create');
            Route::post('/', [\App\Http\Controllers\Admin\RecurringExpenseController::class, 'store'])->middleware('can:create recurring expenses')->name('store');
            Route::get('/{recurringExpense}/edit', [\App\Http\Controllers\Admin\RecurringExpenseController::class, 'edit'])->middleware('can:update recurring expenses')->name('edit');
            Route::put('/{recurringExpense}', [\App\Http\Controllers\Admin\RecurringExpenseController::class, 'update'])->middleware('can:update recurring expenses')->name('update');
        });

        // Expense Categories Routes (PRC-814 — dropdown yönetimi)
        Route::prefix('expense-categories')->name('expense-categories.')->middleware('can:manage expense settings')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\ExpenseCategoryController::class, 'index'])->name('index');
        });

        // Vendors Routes (PRC-814 — tedarikçi dropdown yönetimi)
        Route::prefix('vendors')->name('vendors.')->middleware('can:manage expense settings')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\VendorController::class, 'index'])->name('index');
        });

        // Promotions Routes (PRC-578)
        Route::prefix('promotions')->name('promotions.')->middleware('can:view promotions')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\PromotionController::class, 'index'])->name('index');
            Route::get('/create', [\App\Http\Controllers\Admin\PromotionController::class, 'create'])->name('create');
            Route::post('/', [\App\Http\Controllers\Admin\PromotionController::class, 'store'])->name('store');
            Route::get('/{promotion}/edit', [\App\Http\Controllers\Admin\PromotionController::class, 'edit'])->name('edit');
            Route::put('/{promotion}', [\App\Http\Controllers\Admin\PromotionController::class, 'update'])->name('update');
            Route::get('/{promotion}', [\App\Http\Controllers\Admin\PromotionController::class, 'show'])->name('show');
        });

        // Client Discounts Routes
        Route::prefix('client-discounts')->name('client-discounts.')->middleware('can:view client discounts')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\ClientDiscountController::class, 'index'])->name('index');
            Route::get('/create', [\App\Http\Controllers\Admin\ClientDiscountController::class, 'create'])->middleware('can:create client discounts')->name('create');
            Route::post('/', [\App\Http\Controllers\Admin\ClientDiscountController::class, 'store'])->middleware('can:create client discounts')->name('store');
            Route::get('/{clientDiscount}/edit', [\App\Http\Controllers\Admin\ClientDiscountController::class, 'edit'])->middleware('can:update client discounts')->name('edit');
            Route::put('/{clientDiscount}', [\App\Http\Controllers\Admin\ClientDiscountController::class, 'update'])->middleware('can:update client discounts')->name('update');
            Route::get('/{clientDiscount}', [\App\Http\Controllers\Admin\ClientDiscountController::class, 'show'])->name('show');
        });

        // Client Groups Routes
        Route::prefix('client-groups')->name('client-groups.')->middleware('can:view client groups')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\ClientGroupController::class, 'index'])->name('index');
            Route::get('/create', [\App\Http\Controllers\Admin\ClientGroupController::class, 'create'])->middleware('can:create client groups')->name('create');
            Route::post('/', [\App\Http\Controllers\Admin\ClientGroupController::class, 'store'])->middleware('can:create client groups')->name('store');
            Route::get('/{clientGroup}/edit', [\App\Http\Controllers\Admin\ClientGroupController::class, 'edit'])->middleware('can:update client groups')->name('edit');
            Route::put('/{clientGroup}', [\App\Http\Controllers\Admin\ClientGroupController::class, 'update'])->middleware('can:update client groups')->name('update');
            Route::delete('/{clientGroup}', [\App\Http\Controllers\Admin\ClientGroupController::class, 'destroy'])->middleware('can:delete client groups')->name('destroy');
            Route::get('/{clientGroup}', [\App\Http\Controllers\Admin\ClientGroupController::class, 'show'])->name('show');
        });

        // Basket Routes
        Route::prefix('baskets')->name('baskets.')->middleware('can:view baskets')->group(function () {
            Route::get('/', [BasketController::class, 'index'])->name('index');
            Route::get('/create', [BasketController::class, 'create'])->name('create');
            Route::post('/', [BasketController::class, 'store'])->name('store');
            Route::get('/{basket}', [BasketController::class, 'show'])->name('show');
            Route::get('/{basket}/edit', [BasketController::class, 'edit'])->name('edit');
            Route::put('/{basket}', [BasketController::class, 'update'])->name('update');
        });

        // Cancellation Requests Routes
        Route::prefix('cancellation-requests')->name('cancellation-requests.')->middleware('can:view cancellation requests')->group(function () {
            Route::get('/', [CancellationRequestController::class, 'index'])->name('index');
            Route::get('/{cancellationRequest}', [CancellationRequestController::class, 'show'])->name('show');
            Route::get('/{cancellationRequest}/edit', [CancellationRequestController::class, 'edit'])->middleware('can:update cancellation requests')->name('edit');
            Route::put('/{cancellationRequest}', [CancellationRequestController::class, 'update'])->middleware('can:update cancellation requests')->name('update');
            Route::delete('/{cancellationRequest}', [CancellationRequestController::class, 'destroy'])->middleware('can:delete cancellation requests')->name('destroy');
        });

        // Billing Routes — PRC-227 RBAC coverage.
        // Group-level `can:view invoices` enforces the baseline read gate;
        // per-route middleware then layers granular write/cancel/payment/etc.
        // gates on top. Mutations that didn't have a 1:1 existing permission
        // key fall back to `manage billing` (added in PRC-227).
        Route::prefix('billing')->name('billing.')->middleware('can:view invoices')->group(function () {
            Route::get('/', [BillingController::class, 'index'])->name('index');
            Route::get('/create', [BillingController::class, 'create'])->middleware('can:create invoices')->name('create');
            Route::post('/', [BillingController::class, 'store'])->middleware('can:create invoices')->name('store');
            Route::post('/from-order', [BillingController::class, 'createFromOrder'])->middleware('can:create invoices')->name('create-from-order');
            Route::get('/{invoice}/edit', [BillingController::class, 'edit'])->middleware('can:update invoices')->name('edit');
            Route::put('/{invoice}', [BillingController::class, 'update'])->middleware('can:update invoices')->name('update');
            Route::delete('/{invoice}', [BillingController::class, 'destroy'])->middleware('can:delete invoices')->name('destroy');

            // Fatura işlemleri
            Route::post('/{invoice}/process-payment', [BillingController::class, 'processPayment'])->middleware('can:process invoice payments')->name('process-payment');
            Route::post('/{invoice}/process-auto-payment', [BillingController::class, 'processAutoPayment'])->middleware('can:process invoice payments')->name('process-auto-payment');
            Route::post('/{invoice}/cancel', [BillingController::class, 'cancel'])->middleware('can:cancel invoices')->name('cancel');
            Route::get('/{invoice}/download-pdf', [BillingController::class, 'downloadPdf'])->middleware('can:download invoice pdfs')->name('download-pdf');
            Route::post('/{invoice}/recalculate', [BillingController::class, 'recalculate'])->middleware('can:recalculate invoices')->name('recalculate');

            // Status değişiklikler — update-invoices yetkisi
            Route::post('/{invoice}/mark-paid', [BillingController::class, 'markPaid'])->middleware('can:update invoices')->name('mark-paid');
            Route::post('/{invoice}/mark-unpaid', [BillingController::class, 'markUnpaid'])->middleware('can:update invoices')->name('mark-unpaid');
            // PRC-704 — ödeme öncesi resmi e-fatura kesimi
            Route::post('/{invoice}/issue-legal-invoice', [BillingController::class, 'issueLegalInvoice'])->middleware('can:update invoices')->name('issue-legal-invoice');
            Route::post('/{invoice}/mark-cancelled', [BillingController::class, 'markCancelled'])->middleware('can:cancel invoices')->name('mark-cancelled');
            Route::post('/{invoice}/mark-fraud', [BillingController::class, 'markFraud'])->middleware('can:update invoices')->name('mark-fraud');

            // PRC-673 — muhasebe/e-fatura sevki hariç tut/geri al (manuel override)
            Route::post('/{invoice}/toggle-accounting', [BillingController::class, 'toggleAccountingExcluded'])->middleware('can:update invoices')->name('toggle-accounting');

            // Email gönderme
            Route::post('/{invoice}/send-email', [BillingController::class, 'sendEmail'])->middleware('can:update invoices')->name('send-email');

            // Ödeme ekleme (tab içinde)
            Route::post('/{invoice}/add-payment', [BillingController::class, 'storePayment'])->middleware('can:process invoice payments')->name('store-payment');

            // Transaction yönetimi
            Route::put('/transactions/{transaction}', [BillingController::class, 'updateTransaction'])->middleware('can:update transactions')->name('transactions.update');
            Route::delete('/transactions/{transaction}', [BillingController::class, 'deleteTransaction'])->middleware('can:delete transactions')->name('transactions.delete');

            // Bedel ekleme
            Route::post('/{invoice}/add-late-fee', [BillingController::class, 'addLateFee'])->middleware('can:add late fees')->name('add-late-fee');
            Route::post('/{invoice}/add-grace-period-fee', [BillingController::class, 'addGracePeriodFee'])->middleware('can:add grace period fees')->name('add-grace-period-fee');
            Route::post('/{invoice}/add-redemption-fee', [BillingController::class, 'addRedemptionFee'])->middleware('can:add redemption fees')->name('add-redemption-fee');

            // Invoice Items
            Route::post('/{invoice}/save-items', [BillingController::class, 'saveItems'])->middleware('can:update invoices')->name('save-items');

            // Item Picker API endpoints — read-only metadata for picker UI
            Route::get('/client-services/{clientId}', [BillingController::class, 'getClientServices'])->name('client-services');
            Route::get('/client-domains/{clientId}', [BillingController::class, 'getClientDomains'])->name('client-domains');
            Route::get('/products', [BillingController::class, 'getProducts'])->name('products');
            Route::get('/products/{productId}/pricing', [BillingController::class, 'getProductPricing'])->name('product-pricing');
            Route::get('/tlds', [BillingController::class, 'getTlds'])->name('tlds');
            Route::get('/tlds/{tldId}/pricing', [BillingController::class, 'getTldPricing'])->name('tld-pricing');

            // Invoice creation actions
            Route::post('/add-funds', [BillingController::class, 'storeAddFunds'])->middleware('can:create invoices')->name('store-add-funds');
            Route::post('/billable-item', [BillingController::class, 'storeBillableItem'])->middleware('can:create invoices')->name('store-billable-item');
            Route::post('/generate-due-invoices', [BillingController::class, 'generateDueInvoices'])->middleware('can:create invoices')->name('generate-due-invoices');

            // Invoice Billing Rules (PRC-75) — multi-criteria dispatch rules
            Route::prefix('rules')->name('rules.')->middleware('can:manage billing rules')->group(function () {
                Route::get('/', [\App\Http\Controllers\Admin\InvoiceBillingRuleController::class, 'index'])->name('index');
                Route::post('/settings', [\App\Http\Controllers\Admin\InvoiceBillingRuleController::class, 'saveSettings'])
                    ->middleware('can:manage settings')->name('settings.update');
                Route::get('/create', [\App\Http\Controllers\Admin\InvoiceBillingRuleController::class, 'create'])->name('create');
                Route::post('/', [\App\Http\Controllers\Admin\InvoiceBillingRuleController::class, 'store'])->name('store');
                Route::get('/fields', [\App\Http\Controllers\Admin\InvoiceBillingRuleController::class, 'fields'])->name('fields');
                Route::post('/reorder', [\App\Http\Controllers\Admin\InvoiceBillingRuleController::class, 'reorder'])->name('reorder');
                Route::get('/{rule}/edit', [\App\Http\Controllers\Admin\InvoiceBillingRuleController::class, 'edit'])->name('edit');
                Route::put('/{rule}', [\App\Http\Controllers\Admin\InvoiceBillingRuleController::class, 'update'])->name('update');
                Route::delete('/{rule}', [\App\Http\Controllers\Admin\InvoiceBillingRuleController::class, 'destroy'])->name('destroy');
                Route::post('/{rule}/test', [\App\Http\Controllers\Admin\InvoiceBillingRuleController::class, 'test'])->name('test');
            });
        });

        // Log Routes
        Route::prefix('logs')->name('logs.')->middleware('can:view logs')->group(function () {
            Route::get('/', [LogController::class, 'index'])->name('index');
            Route::get('/system', [LogController::class, 'system'])->name('system');
            Route::get('/payment', [LogController::class, 'payment'])->name('payment');
            Route::get('/mail', [LogController::class, 'mail'])->name('mail');
            Route::get('/payment-provider', [LogController::class, 'paymentProvider'])->name('payment-provider');
            Route::get('/module', [LogController::class, 'module'])->name('module');
            Route::get('/client', [LogController::class, 'client'])->name('client');
            Route::get('/admin', [LogController::class, 'admin'])->name('admin');
            Route::get('/php', [LogController::class, 'php'])->name('php');
            Route::get('/tracking', [\App\Http\Controllers\Admin\TrackingLogController::class, 'tracking'])
                ->middleware('can:view admin logs')
                ->name('tracking');
            Route::get('/{log}', [LogController::class, 'show'])->name('show');
        });

        // Network Tools Routes
        Route::prefix('network-tools')->name('network-tools.')->middleware('can:view network tools')->group(function () {
            Route::get('/', [NetworkToolsController::class, 'index'])->name('index');
            Route::get('/whois', [NetworkToolsController::class, 'whoisPage'])->name('whois');
            Route::get('/ping', [NetworkToolsController::class, 'pingPage'])->name('ping');
            Route::get('/traceroute', [NetworkToolsController::class, 'traceroutePage'])->name('traceroute');
            Route::get('/dns', [NetworkToolsController::class, 'dnsPage'])->name('dns');
            Route::get('/mx', [NetworkToolsController::class, 'mxPage'])->name('mx');
            Route::get('/txt', [NetworkToolsController::class, 'txtPage'])->name('txt');
            Route::get('/tld-config', [NetworkToolsController::class, 'tldConfigPage'])->name('tld-config');
        });

        // PRC-873 — PROCP lisans sistemi yönetim/durum sayfası (Slice B)
        Route::prefix('system/license')->name('system.license.')->middleware('can:manage settings')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\SystemLicenseController::class, 'index'])->name('index');
            Route::post('/', [\App\Http\Controllers\Admin\SystemLicenseController::class, 'update'])->name('update');
            Route::post('/test', [\App\Http\Controllers\Admin\SystemLicenseController::class, 'test'])->name('test');
        });

        // PRC-869 — Kurulum-sonrası sistem sağlık kontrolü
        Route::prefix('system/health')->name('system.health.')->middleware('can:manage settings')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\SystemHealthController::class, 'index'])->name('index');
            Route::post('/mail-test', [\App\Http\Controllers\Admin\SystemHealthController::class, 'mailTest'])->name('mail-test');
        });

        // Network Statuses Routes
        Route::prefix('network-statuses')->name('network-statuses.')->middleware('can:manage settings')->group(function () {
            Route::get('/', [NetworkStatusController::class, 'index'])->name('index');
            Route::get('/create', [NetworkStatusController::class, 'create'])->name('create');
            Route::post('/', [NetworkStatusController::class, 'store'])->name('store');
            Route::get('/{networkStatus}/edit', [NetworkStatusController::class, 'edit'])->name('edit');
            Route::put('/{networkStatus}', [NetworkStatusController::class, 'update'])->name('update');
        });

        // Queue Management Routes
        Route::prefix('queue')->name('queue.')->group(function () {
            Route::get('/', [QueueController::class, 'index'])->name('index');
        });

        // Backup Management (PRC-827)
        Route::get('/backups', [\App\Http\Controllers\Admin\BackupController::class, 'index'])
            ->middleware('can:manage backups')
            ->name('backups.index');

        // Reports Routes
        Route::prefix('reports')->name('reports.')->middleware('can:view reports')->group(function () {
            Route::get('/', [ReportsController::class, 'index'])->name('index');
            Route::get('/detail', [ReportsController::class, 'detail'])->name('detail');
            Route::get('/api', [ReportsController::class, 'getReports'])->name('api');
            Route::post('/api/{module}', [ReportsController::class, 'runReport'])->middleware('can:generate reports')->name('api.run');
        });

        // Live Chat — PRC-608: tüm grup view tickets ile gated (info endpoint PII döndürür).
        Route::prefix('chat')->name('chat.')->middleware('can:view tickets')->group(function () {
            Route::get('/', [AdminChatController::class, 'dashboard'])->name('dashboard');
            Route::post('/{session}/accept', [AdminChatController::class, 'accept'])->name('accept');
            Route::post('/{session}/assign', [AdminChatController::class, 'assign'])->name('assign');
            Route::post('/{session}/reassign', [AdminChatController::class, 'reassign'])->name('reassign');
            Route::get('/{session}/info', [AdminChatController::class, 'info'])->name('info');
            Route::post('/{session}/block', [AdminChatController::class, 'block'])->name('block');
            Route::post('/{session}/send', [AdminChatController::class, 'send'])->name('send');
            Route::get('/{session}/messages', [AdminChatController::class, 'messages'])->name('messages');
            Route::post('/{session}/close', [AdminChatController::class, 'close'])->name('close');
            Route::get('/history', [AdminChatController::class, 'history'])->name('history');
            Route::get('/{session}/transcript', [AdminChatController::class, 'transcript'])->name('transcript');
            Route::get('/{session}/transcript/pdf', [AdminChatController::class, 'transcriptPdf'])->name('transcript.pdf');
        });

        // Brands
        Route::prefix('brands')->name('brands.')->middleware('can:view brands')->group(function () {
            Route::get('/', [BrandController::class, 'index'])->name('index');
            Route::get('/create', [BrandController::class, 'create'])->middleware('can:create brands')->name('create');
            Route::post('/', [BrandController::class, 'store'])->middleware('can:create brands')->name('store');
            Route::get('/{brand}/edit', [BrandController::class, 'edit'])->middleware('can:update brands')->name('edit');
            Route::put('/{brand}', [BrandController::class, 'update'])->middleware('can:update brands')->name('update');
        });

        // PRC-841 — Resellers (standalone CRUD: controller+view'lar mevcuttu ama
        // route'ları HİÇ kayıtlı değildi = ölü koddu; başvuru akışıyla canlandırıldı).
        // Mutasyon AJAX'ları (destroy/approve/reject/request-info) API tarafında
        // (Bearer token kuralı) — bkz. routes/api.php.
        Route::prefix('resellers')->name('resellers.')->middleware('can:view resellers')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\ResellerController::class, 'index'])->name('index');
            Route::get('/create', [\App\Http\Controllers\Admin\ResellerController::class, 'create'])->middleware('can:create resellers')->name('create');
            Route::post('/', [\App\Http\Controllers\Admin\ResellerController::class, 'store'])->middleware('can:create resellers')->name('store');
            Route::get('/{reseller}/edit', [\App\Http\Controllers\Admin\ResellerController::class, 'edit'])->middleware('can:update resellers')->name('edit');
            Route::put('/{reseller}', [\App\Http\Controllers\Admin\ResellerController::class, 'update'])->middleware('can:update resellers')->name('update');
        });

        // Language Manager
        Route::prefix('language-manager')->name('language-manager.')->middleware('can:manage settings')->group(function () {
            Route::get('/', [LanguageManagerController::class, 'index'])->name('index');
            Route::post('/save', [LanguageManagerController::class, 'save'])->name('save');
            Route::get('/export', [LanguageManagerController::class, 'export'])->name('export');
            Route::post('/import', [LanguageManagerController::class, 'import'])->name('import');
        });

        // Workflows
        Route::middleware(['permission:view workflows'])->prefix('workflows')->name('workflows.')->group(function () {
            Route::get('/',                     [WorkflowController::class, 'index'])->name('index');
            Route::get('/builder',              [WorkflowController::class, 'builder'])->name('builder.create')->middleware('permission:manage workflows');
            Route::post('/graph',               [WorkflowController::class, 'saveGraph'])->name('save-graph.create')->middleware('permission:manage workflows');
            Route::get('/{workflow}/builder',   [WorkflowController::class, 'builder'])->name('builder.edit')->middleware('permission:manage workflows');
            Route::put('/{workflow}/graph',     [WorkflowController::class, 'saveGraph'])->name('save-graph.update')->middleware('permission:manage workflows');
            Route::post('/{workflow}/dry-run',  [WorkflowController::class, 'dryRun'])->name('dry-run')->middleware('permission:manage workflows');
            Route::delete('/{workflow}',        [WorkflowController::class, 'destroy'])->name('destroy')->middleware('permission:manage workflows');
        });

        // Custom Reports (PRC-24) — PRC-178 RBAC coverage (defense-in-depth).
        // CustomReportPolicy already enforces owner/admin checks on individual
        // records, but per route-level keys provide a 2nd layer that runs BEFORE
        // controller dispatch (any-permission-failed = 403 even without
        // touching the controller). Edit/update/delete/toggle-public require
        // either `manage custom reports` OR owner (policy handles owner).
        // Export keeps its dedicated `export custom reports` key (PRC-38).
        Route::middleware(['permission:view custom reports'])->prefix('reports/custom')->name('reports.custom.')->group(function () {
            Route::get('/',                          [CustomReportController::class, 'index'])->name('index');
            Route::get('/builder',                   [CustomReportController::class, 'create'])->middleware('permission:create custom reports')->name('create');
            Route::post('/',                         [CustomReportController::class, 'store'])->middleware('permission:create custom reports')->name('store');
            Route::post('/preview',                  [CustomReportController::class, 'preview'])->name('preview');
            Route::get('/{report}',                  [CustomReportController::class, 'show'])->name('show');
            Route::get('/{report}/edit',             [CustomReportController::class, 'edit'])->name('edit');
            Route::patch('/{report}',                [CustomReportController::class, 'update'])->name('update');
            Route::delete('/{report}',               [CustomReportController::class, 'destroy'])->name('destroy');
            Route::patch('/{report}/toggle-public',  [CustomReportController::class, 'togglePublic'])->middleware('permission:manage custom reports')->name('toggle-public');
            Route::get('/{report}/export',           [CustomReportController::class, 'export'])->middleware('permission:export custom reports')->name('export');
        });

        // SLA Plans
        Route::prefix('sla-plans')->name('sla-plans.')->middleware('can:view sla plans')->group(function () {
            Route::get('/', [SlaPlanController::class, 'index'])->name('index');
            Route::get('/create', [SlaPlanController::class, 'create'])->middleware('can:create sla plans')->name('create');
            Route::post('/', [SlaPlanController::class, 'store'])->middleware('can:create sla plans')->name('store');
            Route::get('/{slaPlan}/edit', [SlaPlanController::class, 'edit'])->middleware('can:update sla plans')->name('edit');
            Route::put('/{slaPlan}', [SlaPlanController::class, 'update'])->middleware('can:update sla plans')->name('update');
        });


        // Contracts
        Route::prefix('contracts')->name('contracts.')->middleware('can:view contracts')->group(function () {
            Route::get('/', [ContractController::class, 'index'])->name('index');
            Route::get('/create', [ContractController::class, 'create'])->middleware('can:create contracts')->name('create');
            Route::post('/', [ContractController::class, 'store'])->middleware('can:create contracts')->name('store');
            Route::get('/{contract}/edit', [ContractController::class, 'edit'])->middleware('can:update contracts')->name('edit');
            Route::put('/{contract}', [ContractController::class, 'update'])->middleware('can:update contracts')->name('update');
        });

        // Downloads
        Route::prefix('downloads')->name('downloads.')->middleware('can:view downloads')->group(function () {
            Route::get('/', [DownloadController::class, 'index'])->name('index');
            Route::get('/create', [DownloadController::class, 'create'])->middleware('can:create downloads')->name('create');
            Route::post('/', [DownloadController::class, 'store'])->middleware('can:create downloads')->name('store');
            Route::get('/{download}/edit', [DownloadController::class, 'edit'])->middleware('can:update downloads')->name('edit');
            Route::put('/{download}', [DownloadController::class, 'update'])->middleware('can:update downloads')->name('update');
        });

        // Invoice Billing Routes
        // PRC-133 — Blocked domain patterns (brand protect)
        Route::resource('blocked-domain-patterns', \App\Http\Controllers\Admin\BlockedDomainPatternController::class)
            ->except(['show'])
            ->middleware('can:manage blocked_domain_patterns');
        // PRC-319 / A-8 — enforcement mode setting moved from /admin/settings → here.
        Route::post('blocked-domain-patterns/settings', [\App\Http\Controllers\Admin\BlockedDomainPatternController::class, 'saveSettings'])
            ->middleware('can:manage blocked_domain_patterns')
            ->name('blocked-domain-patterns.settings');

        // PRC-95/PRC-299 — DNS zones management
        Route::prefix('dns-zones')->name('dns-zones.')->middleware('can:manage dns zones')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\DnsZoneController::class, 'index'])->name('index');
            Route::get('/create', [\App\Http\Controllers\Admin\DnsZoneController::class, 'create'])->name('create');
            Route::post('/', [\App\Http\Controllers\Admin\DnsZoneController::class, 'store'])->name('store');
            Route::get('/{zone}', [\App\Http\Controllers\Admin\DnsZoneController::class, 'show'])->name('show');
            Route::delete('/{zone}', [\App\Http\Controllers\Admin\DnsZoneController::class, 'destroy'])->name('destroy');
            Route::post('/{zone}/sync', [\App\Http\Controllers\Admin\DnsZoneController::class, 'sync'])->name('sync');
            Route::post('/{zone}/records', [\App\Http\Controllers\Admin\DnsZoneController::class, 'storeRecord'])->name('records.store');
            Route::put('/{zone}/records/{record}', [\App\Http\Controllers\Admin\DnsZoneController::class, 'updateRecord'])->name('records.update');
            Route::delete('/{zone}/records/{record}', [\App\Http\Controllers\Admin\DnsZoneController::class, 'destroyRecord'])->name('records.destroy');
        });

        // PRC-82 — Provisioning logs (persistent module-call queue)
        Route::prefix('provisioning-logs')->name('provisioning-logs.')->middleware('can:manage provisioning queue')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\ProvisioningLogController::class, 'index'])->name('index');
            Route::post('/bulk-retry', [\App\Http\Controllers\Admin\ProvisioningLogController::class, 'bulkRetry'])->name('bulk-retry');
            Route::get('/{provisioningLog}', [\App\Http\Controllers\Admin\ProvisioningLogController::class, 'show'])->name('show');
            Route::post('/{provisioningLog}/retry', [\App\Http\Controllers\Admin\ProvisioningLogController::class, 'retry'])->name('retry');
            Route::post('/{provisioningLog}/dismiss', [\App\Http\Controllers\Admin\ProvisioningLogController::class, 'dismiss'])->name('dismiss');
        });

        // Invoice billing modules — PRC-227 RBAC coverage
        Route::prefix('invoice-billings')->name('invoice-billings.')->middleware('can:view invoice billings')->group(function () {
            Route::get('/', [InvoiceBillingController::class, 'index'])->name('index');
            Route::get('/create', [InvoiceBillingController::class, 'create'])->middleware('can:create invoice billings')->name('create');
            Route::post('/', [InvoiceBillingController::class, 'store'])->middleware('can:create invoice billings')->name('store');
            Route::get('/{module}/edit', [InvoiceBillingController::class, 'edit'])->middleware('can:update invoice billings')->name('edit');
            Route::put('/{module}', [InvoiceBillingController::class, 'update'])->middleware('can:update invoice billings')->name('update');
            Route::delete('/{module}', [InvoiceBillingController::class, 'destroy'])->middleware('can:delete invoice billings')->name('destroy');
            Route::post('/{module}/test', [InvoiceBillingController::class, 'test'])->middleware('can:update invoice billings')->name('test');
            Route::post('/{module}/manual-billing', [InvoiceBillingController::class, 'manualBilling'])->middleware('can:update invoice billings')->name('manual-billing');
        });

        // Verifications Routes
        Route::prefix('verifications')->name('verifications.')->middleware('can:view verifications')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\VerificationController::class, 'index'])->name('index');
            Route::get('/documents/{verification}', [\App\Http\Controllers\Store\VerificationDocumentController::class, 'adminDownload'])->name('documents.download');
            Route::get('/{id}', [\App\Http\Controllers\Admin\VerificationController::class, 'show'])->name('show');
        });

        // Quotes
        Route::prefix('quotes')->name('quotes.')->middleware('can:view quotes')->group(function () {
            Route::get('/', [QuoteController::class, 'index'])->name('index');
            Route::get('/create', [QuoteController::class, 'create'])->name('create');
            Route::post('/', [QuoteController::class, 'store'])->name('store');
            Route::get('/{quote}/edit', [QuoteController::class, 'edit'])->name('edit');
            Route::put('/{quote}', [QuoteController::class, 'update'])->name('update');
            Route::post('/{quote}/send', [QuoteController::class, 'send'])->name('send');
            Route::post('/{quote}/accept', [QuoteController::class, 'accept'])->name('accept');
            Route::post('/{quote}/duplicate', [QuoteController::class, 'duplicate'])->name('duplicate');
            Route::get('/{quote}/download-pdf', [QuoteController::class, 'downloadPdf'])->name('download-pdf');
        });

        // Affiliates
        Route::prefix('affiliates')->name('affiliates.')->middleware('can:view affiliates')->group(function () {
            Route::get('/', [AffiliateController::class, 'index'])->name('index');
            Route::get('/payouts', [AffiliateController::class, 'payouts'])->name('payouts');
            Route::get('/reports', [AffiliateController::class, 'reports'])->name('reports');
            Route::get('/{affiliate}', [AffiliateController::class, 'show'])->name('show');
        });

        // Unified posts (announcements / knowledgebase / blog) + tags.
        // Each resource binds {post} to App\Models\Post via parameters override
        // so STI subclasses share the base model lookup; controllers enforce
        // the type via abort_if() on the postType() trait hook.
        Route::post('posts/upload-image', [PostImageUploadController::class, 'upload'])
            ->middleware('throttle:30,1')
            ->name('posts.upload-image');
        Route::resource('announcements', AnnouncementController::class)->parameters(['announcements' => 'post'])->except(['show'])->middleware('can:view announcements');
        Route::resource('knowledgebase', KnowledgebaseController::class)->parameters(['knowledgebase' => 'post'])->except(['show'])->middleware('can:view knowledgebase articles');
        Route::resource('blog', BlogController::class)->parameters(['blog' => 'post'])->except(['show'])->middleware('can:view blog');
        Route::resource('tags', TagController::class)->except(['show'])->middleware('can:view blog');
        Route::resource('menus', \App\Http\Controllers\Admin\MenuController::class)
             ->except(['show']);

        // Page builder
        Route::resource('pages', PageController::class)
             ->except(['show'])
             ->parameters(['pages' => 'page']);
        Route::post('pages/{page}/duplicate', [PageController::class, 'duplicate'])
             ->name('pages.duplicate');
        Route::post('pages/{page}/add-translation', [PageController::class, 'addTranslation'])
             ->name('pages.add-translation');
        Route::get('pages/{page}/preview', [PageController::class, 'preview'])
             ->name('pages.preview');
        Route::get('media', [\App\Http\Controllers\Admin\MediaController::class, 'index'])->name('media.index');

        // Addon dispatcher — framework-controlled, tek entry point
        Route::any('/addons/{name}/{action?}/{params?}', \App\Http\Controllers\Admin\AddonDispatchController::class)
            ->where('params', '.*')
            ->name('addons.dispatch');

        // Addon Modules — lifecycle UI (gated by global manage permission)
        Route::prefix('addon-modules')->name('addon-modules.')
            ->middleware('permission:manage addon-modules')
            ->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\AddonModulesController::class, 'index'])->name('index');
            Route::post('{name}/activate', [\App\Http\Controllers\Admin\AddonModulesController::class, 'activate'])->name('activate');
            Route::post('{name}/deactivate', [\App\Http\Controllers\Admin\AddonModulesController::class, 'deactivate'])->name('deactivate');
            Route::post('{name}/uninstall', [\App\Http\Controllers\Admin\AddonModulesController::class, 'uninstall'])->name('uninstall');
            Route::post('{name}/upgrade', [\App\Http\Controllers\Admin\AddonModulesController::class, 'upgrade'])->name('upgrade');
            Route::get('{name}/configure', [\App\Http\Controllers\Admin\AddonModulesController::class, 'configure'])->name('configure');
            Route::post('{name}/configure', [\App\Http\Controllers\Admin\AddonModulesController::class, 'saveConfig'])->name('configure.save');
        });

    });

    // API Routes — PRC-185 RBAC + auth coverage. Previously this group sat
    // outside the `auth:admin` middleware in this file, so `/admin/api/clients/*`
    // was reachable WITHOUT authentication (relied on session detection that
    // never ran). Wrap in auth:admin + 2FA + can:view clients to match the
    // sister routes/api.php gates.
    Route::prefix('api')->name('api.')->middleware([
        'auth:admin',
        'verified',
        \App\Http\Middleware\Admin\EnsureTwoFactorVerified::class,
        'can:view clients',
    ])->group(function () {
        // Client API
        Route::get('/clients/search', [ClientController::class, 'search'])->name('admin.clients.search');
        Route::get('/clients/{client}/products', [ClientController::class, 'getClientProducts'])->name('clients.products');
        Route::get('/clients/{client}/domains', [ClientController::class, 'getClientDomains'])->name('clients.domains');
    });
});
