<?php

use App\Http\Controllers\AdminController;
use App\Http\Controllers\AdminLoginController;
use App\Http\Controllers\BankController;
use App\Http\Controllers\BankLoginController;
use App\Http\Controllers\CategoryController;
use App\Http\Controllers\ChatController;
use App\Http\Controllers\BackupChunkUploadController;
use App\Http\Controllers\CustomLogoutController;
use App\Http\Controllers\ExportController;
use App\Http\Controllers\LangJsController;
use App\Http\Controllers\MailgunWebhookController;
use App\Http\Controllers\MailingsController;
use App\Http\Controllers\NewsletterUnsubscribeController;
use App\Http\Controllers\OrganizationController;
use App\Http\Controllers\OrganizationLoginController;
use App\Http\Controllers\PermissionController;
use App\Http\Controllers\PostController;
use App\Http\Controllers\PresenceController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\ResetNonUserPasswordController;
use App\Http\Controllers\RoleController;
use App\Http\Controllers\SearchController;
use App\Http\Controllers\StaticController;
use App\Http\Controllers\TagController;
use App\Http\Controllers\TestController;
use App\Http\Controllers\TransactionController;
use App\Http\Controllers\UserLoginController;
use App\Http\Requests\ProfileEmailVerificationRequest;
use App\Models\User;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\Facades\Route;
use Laravel\Jetstream\Http\Controllers\Livewire\ApiTokenController;
use Laravel\Jetstream\Http\Controllers\Livewire\PrivacyPolicyController;
use Laravel\Jetstream\Http\Controllers\Livewire\RegisterController;
use Laravel\Jetstream\Http\Controllers\Livewire\TermsOfServiceController;
use Laravel\Jetstream\Http\Livewire\Register;
use Laravel\Jetstream\Jetstream;
use Livewire\Livewire;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Namu\WireChat\Livewire\Pages\Chat as WireChatPage;
use Namu\WireChat\Livewire\Pages\Chats as WireChatsListPage;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

// Newsletter unsubscribe route (must be accessible without authentication)
Route::get('/newsletter/unsubscribe', [NewsletterUnsubscribeController::class, 'unsubscribe'])
    ->name('newsletter.unsubscribe');

// Legacy Cyclos payment link (no locale prefix) - as used by Lekkernasuh market payment links
// Redirects to the localized version so the auth/localization middleware applies correctly
Route::get('/do/member/payment', function (\Illuminate\Http\Request $request) {
    $locale = app()->getLocale();
    $query = $request->getQueryString();
    $url = "/{$locale}/do/member/payment" . ($query ? "?{$query}" : '');
    return redirect($url);
})->name('legacy.cyclos-payment');

/*
|--------------------------------------------------------------------------
/ DEBUG AND TESTING ROUTES
/ These are not localized and should not have the secret prefix.
|--------------------------------------------------------------------------
*/
if (App::environment(['local', 'development', 'testing'])) {

    // Broadcast test with manual authorization
    Route::get('/test/broadcast', function () {
        // manually authorize user 2
        $user = User::find(2);
        $toUserId = 2;
        Auth::login($user);
        return view('test.broadcast', compact(['user', 'toUserId']));
    });

    // IpLocation test
    Route::get('/test/ip-location', [TestController::class, 'viewIpLocation'])->name('ip-location');

    // Debug sandbox 1
    Route::get('/test/debug-1', [TestController::class, 'viewDebug1'])->name('debug-1');

    // Debug sandbox 2
    Route::get('/test/debug-2', [TestController::class, 'viewDebug2'])->name('debug-2');

    // Clear cache
    Route::get('/test/clear-cache', [TestController::class, 'clearCache'])->name('clear-cache');

    // Optimize clear
    Route::get('/test/opt-clear', [TestController::class, 'optimizeClear'])->name('optimize-clear');

    // Forcefully clear session and locale cookie
    Route::get('/test/reset-my-session', function () {
        session()->flush();
        // Create a response that redirects to the homepage
        $response = redirect('/');
        // Explicitly create a new cookie that immediately expires the old one
        $response->withCookie(cookie()->forget('laravel_localization'));
        // Return the response to the browser
        return $response;
    });

    // Test error pages to check logging of errors and LogError middleware
    Route::get('/test-error-page', function () {
        abort(404);
    });

    // Simulate a 500 Internal Server Error
    Route::get('/test-500', function () {
        throw new \Exception('Simulated server error');
    });
}

/*
|--------------------------------------------------------------------------
| Email Routes (No Locale Prefix)
|--------------------------------------------------------------------------
*/
Route::get('/email/verify/{type}/{id}/{hash}', function (ProfileEmailVerificationRequest $request) {
    \Log::info('Email verification route HIT', [
        'type' => request()->route('type'),
        'id' => request()->route('id'),
        'hash' => request()->route('hash'),
        'authenticated' => auth()->check(),
        'user_id' => auth()->id(),
    ]);

    // Get the user's current lang_preference from the profile model
    $profileModel = $request->profileModel;
    $userLocale = $profileModel->lang_preference ?? config('app.fallback_locale');

    if (empty($userLocale)) {
        $userLocale = config('app.fallback_locale');
    }

    // Store in session before fulfilling (in case fulfill triggers any locale changes)
    if (!session()->has('verification_original_locale')) {
        session(['verification_original_locale' => $userLocale]);
    }

    $request->fulfill();

    // Build the localized URL for the verification.verified route
    $localizedUrl = '/' . $userLocale . '/email/verified';

    \Log::info('Email verification redirect', [
        'profile_type' => get_class($profileModel),
        'profile_id' => $profileModel->id,
        'userLocale' => $userLocale,
        'redirect_url' => $localizedUrl,
    ]);

    return redirect($localizedUrl);
})->middleware(['auth', 'signed'])->name('verification.verify');

Route::get('/js/lang.js', [LangJsController::class, 'js'])->name('lang.js');

// Tags async select API (used by WireUI async-data)
Route::get('/api/tags/select', function (\Illuminate\Http\Request $request) {
    $locale = app()->getLocale();
    $search = $request->get('search', '');

    $query = \Illuminate\Support\Facades\DB::table('taggable_tags as tt')
        ->join('taggable_locale_context as tlc', 'tt.tag_id', '=', 'tlc.tag_id')
        ->join('taggable_contexts as tc', 'tlc.context_id', '=', 'tc.id')
        ->join('categories as c', 'tc.category_id', '=', 'c.id')
        ->join('categories as croot', \Illuminate\Support\Facades\DB::raw('COALESCE(c.parent_id, c.id)'), '=', 'croot.id')
        ->join('taggable_locales as tl', 'tt.tag_id', '=', 'tl.taggable_tag_id')
        ->where('tl.locale', $locale)
        ->select('tt.tag_id', 'tt.name', 'croot.color')
        ->distinct()
        ->orderBy('tt.name');

    if ($search) {
        $query->where('tt.name', 'like', '%' . $search . '%');
    } else {
        $query->limit(50);
    }

    return $query->get()->map(function ($t) {
        $color = $t->color ?? 'gray';
        return [
            'label' => $t->name,
            'value' => $t->tag_id,
            'color' => $color,
            'html'  => '<span class="bg-' . $color . '-400 inline-flex items-center rounded-md px-2 py-1 text-sm font-normal text-black">' . e($t->name) . '</span>',
        ];
    });
})->name('api.tags.select');

Route::get('/profile/settings/no-locale', [ProfileController::class, 'settingsNoLocale'])
    ->middleware(['auth'])
    ->name('profile.settings.no_locale');

/*
|--------------------------------------------------------------------------
| Main Localized Application Routes
|--------------------------------------------------------------------------
*/
Route::group([
    'prefix' => LaravelLocalization::setLocale(),
    'middleware' => ['localeSessionRedirect', 'localizationRedirect', 'localeViewPath']
], function () {

    /** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/

    //----- Non-Auth routes accessible for guests -----//

    // Fix 404 error when caching routes in combination with Livewire 3
    Livewire::setUpdateRoute(function ($handle) {
        return Route::post('/livewire/update', $handle)->name('default.livewire.update');
    });

    // Broadcasting authentication route - manually registered inside localized group
    // Uses custom controller to support multi-guard authentication
    Route::match(['get', 'post'], '/broadcasting/auth', '\App\Http\Controllers\BroadcastController@authenticate')
        ->middleware(['auth.any:admin,bank,organization,web']);

    Route::get('/', function () {
        return view('welcome');
    })->name('welcome');

    Route::get('/goodbye', function () {
        return view('goodbye-deleted-user');
    })->name('goodbye-deleted-user');

    // Store intended URL for redirect after login
    Route::post('/store-intended-url', function(\Illuminate\Http\Request $request) {
        $url = $request->input('url');
        if ($url) {
            session(['url.intended' => $url]);
        }
        return response()->json(['success' => true]);
    })->name('store-intended-url');

    // Fortify login routes
    Route::get(LaravelLocalization::transRoute('routes.login'), [\Laravel\Fortify\Http\Controllers\AuthenticatedSessionController::class, 'create'])
        ->middleware(['guest'])
        ->name('login');


    Route::post(LaravelLocalization::transRoute('routes.login'), [\Laravel\Fortify\Http\Controllers\AuthenticatedSessionController::class, 'store'])
        ->middleware(['guest']);

    Route::get(
        LaravelLocalization::transRoute('routes.password.request'),
        [\Laravel\Fortify\Http\Controllers\PasswordResetLinkController::class, 'create']
    )->middleware(['guest'])->name('password.request');

    Route::post(
        LaravelLocalization::transRoute('routes.password.email'),
        [\Laravel\Fortify\Http\Controllers\PasswordResetLinkController::class, 'store']
    )->middleware(['guest'])->name('password.email');

    // User Direct Login Route - accessible to both guests and authenticated users
    // Handles redirect to login for guests, or profile access for authenticated users
    Route::get('/user/{userId}/login', [UserLoginController::class, 'directLogin'])->name('user.direct-login');

    Route::get(
        LaravelLocalization::transRoute('routes.password.reset'),
        [\Laravel\Fortify\Http\Controllers\NewPasswordController::class, 'create']
    )->middleware(['guest'])->name('password.reset');

    Route::post(
        LaravelLocalization::transRoute('routes.password.update'),
        [\Laravel\Fortify\Http\Controllers\NewPasswordController::class, 'store']
    )->middleware(['guest'])->name('password.update');

    Route::view(LaravelLocalization::transRoute('routes.register'), 'auth.register')
        ->middleware(['guest'])
        ->name('register');

    Route::post(LaravelLocalization::transRoute('routes.logout'), [CustomLogoutController::class, 'destroy'])
        ->middleware(['auth'])
        ->name('logout');


    /* Static Site Content */
    Route::view(LaravelLocalization::transRoute('routes.static.getting-started'), 'static.getting-started')->name('static-getting-started');
    Route::view(LaravelLocalization::transRoute('routes.static.faq'), 'static.faq')->name('static-faq');
    Route::view(LaravelLocalization::transRoute('routes.static.privacy'), 'static.privacy')->name('static-privacy');
    Route::get('privacy-policy-download', [StaticController::class, 'downloadPrivacyPolicy'])->name('static-privacy-download');
    Route::view(LaravelLocalization::transRoute('routes.static.organizations'), 'static.organizations')->name('static-organizations');
    Route::view(LaravelLocalization::transRoute('routes.static.principles'), 'static.principles')->name('static-principles');
    Route::view(LaravelLocalization::transRoute('routes.static.report-issue'), 'static.report-issue')->name('static-report-issue');
    Route::view(LaravelLocalization::transRoute('routes.static.events'), 'static.events')->name('static-events');
    Route::view(LaravelLocalization::transRoute('routes.static.the-hague'), 'static.the-hague')->name('static-the-hague');
    Route::view(LaravelLocalization::transRoute('routes.static.lekkernassuh'), 'static.lekkernassuh')->name('static-lekkernassuh');
    Route::view(LaravelLocalization::transRoute('routes.static.amst-brus-lisb'), 'static.amst-brus-lisb')->name('static-amst-brus-lisb');
    Route::view(LaravelLocalization::transRoute('routes.static.work-w-us'), 'static.work-w-us')->name('static-work-w-us');
    Route::view(LaravelLocalization::transRoute('routes.static.philosophy'), 'static.philosophy')->name('static-philosophy');
    Route::view(LaravelLocalization::transRoute('routes.static.open-source'), 'static.open-source')->name('static-open-source');
    Route::view(LaravelLocalization::transRoute('routes.static.timebank-organization'), 'static.timebank-organization')->name('static-timebank-organization');
    Route::view(LaravelLocalization::transRoute('routes.static.history'), 'static.history')->name('static-history');
    Route::view(LaravelLocalization::transRoute('routes.static.press-media'), 'static.press-media')->name('static-press-media');
    Route::view(LaravelLocalization::transRoute('routes.static.economics-and-research'), 'static.research')->name('static-research');
    Route::view(LaravelLocalization::transRoute('routes.static.team'), 'static.team')->name('static-team');
    Route::view(LaravelLocalization::transRoute('routes.static.messenger'), 'static.messenger')->name('static-messenger');
    Route::view(LaravelLocalization::transRoute('routes.static.report-error'), 'static.report-error')->name('static-report-error');

    /* Public Call Routes */
    Route::get(LaravelLocalization::transRoute('routes.call.show'), 'App\Http\Controllers\CallController@showById')
        ->where(['id' => '[0-9]+'])
        ->name('call.show');

    /* Public Post Routes - accessible to both guests and authenticated users */
    Route::get(LaravelLocalization::transRoute('routes.post.show'), 'App\Http\Controllers\PostController@showById')
        ->where(['id' => '[0-9]+'])     // Add constraint: only numbers allowed
        ->name('post.show')
        ->missing(function () {
            return view('post.not_found');
        });

    Route::get(LaravelLocalization::transRoute('routes.post.show_by_id_international'), 'App\Http\Controllers\PostController@showById')
        ->name('post.show_by_id_international')
        ->missing(function () {
            return view('post.not_found');
        });

    Route::get(LaravelLocalization::transRoute('routes.post.show_by_slug'), 'App\Http\Controllers\PostController@showBySlug')
        ->name('post.show_by_slug')
        ->missing(function () {
            return view('post.not_found');
        });



    // Manually Registered WireChat Routes
    Route::group(['prefix' => 'chats', 'middleware' => ['auth.any:admin,bank,organization,web'],], function () {
        Route::get('/', WireChatsListPage::class)->name('chats');
        // Start conversation with specific profile route - must come BEFORE {conversation} to prevent route conflict
        Route::get('/{profileType}/{id}', [ChatController::class, 'startConversationWith'])
            ->where('profileType', 'user|organization|bank|admin')
            ->name('chat.start');
        Route::get('/{conversation}', WireChatPage::class)->middleware('belongsToConversation')->name('chat');
    });


    // Profile Settings... (Native vendor Jetstream view)
    // Should be outside verified middleware to prevent lockout: email address can still be changes if verification email is not received.
    Route::middleware(['auth:web', config('jetstream.auth_session')])->group(function () {
        Route::get(
            LaravelLocalization::transRoute('routes.profile.settings'),
            [ProfileController::class, 'settings']
        )->name('profile.settings');
    });

    //----- Protected auth verified routes -----//
    Route::middleware(['auth:web'])->group(function () {

        Route::middleware(['auth:web', config('jetstream.auth_session'), 'verified'])->group(function () {
            Route::group(['middleware' => ['registration-complete', 'principles-accepted']], function () {

                // 6. Routes for AJAX presence calls
                Route::post('/presence/heartbeat', [PresenceController::class, 'heartbeat'])->name('presence.heartbeat');
                Route::post('/presence/offline', [PresenceController::class, 'setOffline'])->name('presence.offline');
                Route::get('/presence/online', [PresenceController::class, 'getOnlineUsers'])->name('presence.online');

                Route::get('/main-page', function () {
                    return redirect()->route('main');
                });

                Route::get(LaravelLocalization::transRoute('routes.main'), function () {
                    return view('main-page');
                })->name('main');

                Route::get(LaravelLocalization::transRoute('routes.pay'), 'App\Http\Controllers\TransactionController@pay')->name('pay');

                Route::get(LaravelLocalization::transRoute('routes.pay-to-name'), 'App\Http\Controllers\TransactionController@payToName')
                    ->name('pay-to-name')
                    ->missing(function () {
                        return view('pay.profile_not_found');
                    });

                Route::get(LaravelLocalization::transRoute('routes.pay-amount-to-name'), 'App\Http\Controllers\TransactionController@payAmountToName')
                    ->name('pay-amount-to-name')
                    ->missing(function () {
                        return view('pay.profile_not_found');
                    });

                Route::get(LaravelLocalization::transRoute('routes.pay-amount-to-name-description'), 'App\Http\Controllers\TransactionController@payAmountToNameWithDescr')
                    ->name('pay-amount-to-name-description')
                    ->missing(function () {
                        return view('pay.profile_not_found');
                    });

                // Legacy Cyclos payment link, as used by Lekkernasuh
                Route::get('/do/member/payment', [TransactionController::class, 'doCyclosPayment']);

                Route::get(LaravelLocalization::transRoute('routes.transactions'), 'App\Http\Controllers\TransactionController@transactions')->name('transactions');

                Route::get(LaravelLocalization::transRoute('routes.contacts'), function () {
                    return view('contacts.show');
                })->name('contacts');

                Route::get(LaravelLocalization::transRoute('routes.calls.manage'), 'App\Http\Controllers\CallController@manage')->name('calls.manage');

                Route::get(LaravelLocalization::transRoute('routes.reports'), 'App\Http\Controllers\ReportController@reports')->name('reports');
                Route::get('/reports/pdf', 'App\Http\Controllers\ReportController@downloadPdf')->name('reports.pdf');

                Route::get(LaravelLocalization::transRoute('routes.statement'), 'App\Http\Controllers\TransactionController@statement')
                    ->where(['transactionId' => '[0-9]+'])     // Add constraint: only numbers allowed
                    ->name('transaction.show');

                Route::group(['middleware' => ['user.can:manage posts']], function () {
                    Route::get(LaravelLocalization::transRoute('routes.posts.manage'), 'App\Http\Controllers\PostController@manage')->name('posts.manage');
                    Route::get('/posts/backup-download/{filename}', function (string $filename) {
                        // Sanitize filename to prevent directory traversal
                        $filename = basename($filename);
                        $fullPath = storage_path('app/backups/' . $filename);

                        if (!file_exists($fullPath)) {
                            abort(404);
                        }

                        return response()->download($fullPath, $filename)->deleteFileAfterSend(true);
                    })->where('filename', '[a-zA-Z0-9_\-\.]+')->name('posts.backup-download');
                    Route::post('/posts/backup-upload/chunk', [BackupChunkUploadController::class, 'uploadChunk'])->name('posts.backup-upload-chunk');
                    Route::post('/posts/backup-upload/finalize', [BackupChunkUploadController::class, 'finalize'])->name('posts.backup-upload-finalize');
                });

                // Mailings management routes (Admin and Bank only)
                Route::group(['middleware' => ['user.can:manage posts']], function () {
                    Route::get('/mailings', [MailingsController::class, 'index'])->name('mailings.index');
                    Route::post('/mailings', [MailingsController::class, 'store'])->name('mailings.store');
                    Route::put('/mailings/{mailing}', [MailingsController::class, 'update'])->name('mailings.update');
                    Route::delete('/mailings/{mailing}', [MailingsController::class, 'destroy'])->name('mailings.destroy');
                    Route::post('/mailings/{mailing}/send', [MailingsController::class, 'send'])->name('mailings.send');
                    Route::post('/mailings/{mailing}/schedule', [MailingsController::class, 'schedule'])->name('mailings.schedule');
                    Route::post('/mailings/{mailing}/cancel', [MailingsController::class, 'cancel'])->name('mailings.cancel');
                    Route::get('/mailings/{mailing}/preview', [MailingsController::class, 'preview'])->name('mailings.preview');
                    Route::get('/mailings/{mailing}/preview-render', [MailingsController::class, 'previewRender'])->name('mailings.preview_render');
                });

                Route::get(LaravelLocalization::transRoute('routes.profile.show'), 'App\Http\Controllers\ProfileController@show')
                    ->where(['id' => '[0-9]+'])     // Add constraint: only numbers allowed
                    ->name('profile.show_by_type_and_id')
                    ->missing(function () {
                        return view('profile.not_found');
                    });

                Route::get(LaravelLocalization::transRoute('routes.profile.show_active'), 'App\Http\Controllers\ProfileController@showActive')
                ->name('profile.show_active');

                Route::get(LaravelLocalization::transRoute('routes.organization.show'), 'App\Http\Controllers\OrganizationController@show')
                    ->where(['orgId' => '[0-9]+'])     // Add constraint: only numbers allowed
                    ->name('organization.show')
                    ->missing(function () {
                        return view('profile-organization.not_found');
                    });

                Route::get(LaravelLocalization::transRoute('routes.bank.show'), 'App\Http\Controllers\BankController@show')
                    ->where(['bankId' => '[0-9]+'])     // Add constraint: only numbers allowed
                    ->name('bank.show')
                    ->missing(function () {
                        return view('profile.not_found');
                    });

                Route::get(LaravelLocalization::transRoute('routes.admin.show'), 'App\Http\Controllers\AdminController@show')
                    ->where(['orgId' => '[0-9]+'])     // Add constraint: only numbers allowed
                    ->name('admin.show')
                    ->missing(function () {
                        return view('profile.not_found');
                    });

                Route::get(LaravelLocalization::transRoute('routes.profile.edit'), 'App\Http\Controllers\ProfileController@edit')->name('profile.edit');

                Route::group(['middleware' => ['user.can:manage users']], function () {
                    Route::get(LaravelLocalization::transRoute('routes.users.manage'), 'App\Http\Controllers\ProfileController@index')->name('users-overview');
                });

                Route::group(['middleware' => ['user.can:manage categories']], function () {
                    Route::get(LaravelLocalization::transRoute('routes.categories.manage'), 'App\Http\Controllers\CategoryController@manage')->name('categories.manage');
                });

                Route::group(['middleware' => ['user.can:manage tags']], function () {
                    Route::get(LaravelLocalization::transRoute('routes.tags.manage'), 'App\Http\Controllers\TagController@manage')->name('tags.manage');
                });

                Route::group(['middleware' => ['user.can:manage profiles']], function () {
                    Route::get(LaravelLocalization::transRoute('routes.profiles.manage'), 'App\Http\Controllers\ProfileController@manage')->name('profiles.manage');
                });

                Route::group(['middleware' => ['user.can:manage permissions']], function () {
                    Route::get(LaravelLocalization::transRoute('routes.permissions.manage'), 'App\Http\Controllers\PermissionController@manage')->name('permissions.manage');
                });

                Route::group(['middleware' => ['user.can:manage roles']], function () {
                    Route::get(LaravelLocalization::transRoute('routes.roles.manage'), 'App\Http\Controllers\RoleController@manage')->name('roles.manage');
                });

                Route::get(LaravelLocalization::transRoute('routes.search.show'), [SearchController::class, 'show'])->name('search.show');

                Route::get('/email/verified', function () {
                    // Restore the original locale from session
                    $originalLocale = session('verification_original_locale');
                    $locale = $originalLocale ?: LaravelLocalization::getCurrentLocale();

                    // Restore the user's original lang_preference in the database
                    if ($originalLocale && auth()->check()) {
                        $user = auth()->user();
                        $user->lang_preference = $originalLocale;
                        $user->save();

                        \Log::info('Restored original locale after verification', [
                            'user_id' => $user->id,
                            'restored_locale' => $originalLocale,
                        ]);
                    }

                    // Clear the session variable
                    session()->forget('verification_original_locale');

                    $localizedRoute = LaravelLocalization::getURLFromRouteNameTranslated($locale, 'routes.main');

                    \Log::info('verification.verified route', [
                        'current_locale' => LaravelLocalization::getCurrentLocale(),
                        'restored_locale' => $originalLocale,
                        'redirect_locale' => $locale,
                        'localized_route' => $localizedRoute,
                    ]);

                    return redirect($localizedRoute ?: route('main'));
                })->name('verification.verified');

                // Jetstream routes (copied from vendor/laravel/jetstream/routes/livewire.php, to overrule, and to include in Laravel-localization class)
                Route::group(['middleware' => config('jetstream.middleware', ['web'])], function () {
                    if (Jetstream::hasTermsAndPrivacyPolicyFeature()) {
                        Route::get(LaravelLocalization::transRoute('routes.terms.show'), [TermsOfServiceController::class, 'show'])->name('app.terms.show');
                        Route::get(LaravelLocalization::transRoute('routes.policy.show'), [PrivacyPolicyController::class, 'show'])->name('app.policy.show');
                    }

                    $authMiddleware = config('jetstream.guard') ? 'auth:' . config('jetstream.guard') : 'auth';
                    $authSessionMiddleware = config('jetstream.auth_session', false) ? config('jetstream.auth_session') : null;

                    Route::group(['middleware' => array_values(array_filter([$authMiddleware, $authSessionMiddleware]))], function () {

                        // Organization & Profile... (Custom view)
                        Route::group(['middleware' => ['user.can:manage organizations']], function () {
                            Route::get(LaravelLocalization::transRoute('routes.profile.organization.show'), [OrganizationController::class, 'settings'])->name('profile.organization.settings');
                        });

                        // Bank & Profile... (Custom view)
                        Route::group(['middleware' => ['user.can:manage banks']], function () {
                            Route::get(LaravelLocalization::transRoute('routes.profile.bank.show'), [BankController::class, 'settings'])->name('profile.bank.settings');
                        });

                        // Admin & Profile... (Custom view)
                        Route::group(['middleware' => ['user.can:manage admins']], function () {
                            Route::get(LaravelLocalization::transRoute('routes.profile.admin.show'), [AdminController::class, 'settings'])->name('profile.admin.settings');
                        });

                        Route::group(['middleware' => 'verified'], function () {
                            // API...
                            if (Jetstream::hasApiFeatures()) {
                                Route::get('/user/api-tokens', [ApiTokenController::class, 'index'])->name('api-tokens.index');
                            }

                            // Exports
                            Route::get('export-test/', [ExportController::class, 'allUsersExport'])->name('export-test');
                        });
                    });
                });


                // Organization Routes
                // Direct link to organization login (for emails, etc.)
                Route::get('/organization/{organizationId}/login', [OrganizationLoginController::class, 'directLogin'])->name('organization.direct-login');

                Route::get(LaravelLocalization::transRoute('routes.organization.login'), [OrganizationLoginController::class, 'showLoginForm'])->name('organization.login');
                Route::post(LaravelLocalization::transRoute('routes.organization.login'), [OrganizationLoginController::class, 'login'])->name('organization.login.post');
                Route::get(LaravelLocalization::transRoute('routes.organization.logout'), [OrganizationLoginController::class, 'logout'])->name('organization.logout.get');
                Route::post(LaravelLocalization::transRoute('routes.organization.logout'), [OrganizationLoginController::class, 'logout'])->name('organization.logout.post');
                Route::group(['middleware' => ['web', 'organization.auth']], function () {
                    Route::get('/organization/main-page', function () {
                        return view('main-page');
                    })->name('organization.main');
                });

                // Bank Routes
                // Direct link to bank login (for emails, etc.)
                Route::get('/bank/{bankId}/login', [BankLoginController::class, 'directLogin'])->name('bank.direct-login');

                Route::get(LaravelLocalization::transRoute('routes.bank.login'), [BankLoginController::class, 'showLoginForm'])->name('bank.login');
                Route::post(LaravelLocalization::transRoute('routes.bank.login'), [BankLoginController::class, 'login'])->name('bank.login.post');
                Route::get(LaravelLocalization::transRoute('routes.bank.logout'), [BankLoginController::class, 'logout'])->name('bank.logout.get');
                Route::post(LaravelLocalization::transRoute('routes.bank.logout'), [BankLoginController::class, 'logout'])->name('bank.logout.post');
                Route::group(['middleware' => ['web', 'bank.auth']], function () {
                    Route::get('/bank/main-page', function () {
                        return view('main-page');
                    })->name('bank.main');
                });

                // Admin Routes
                // Direct link to admin login (for emails, etc.)
                Route::get('/admin/{adminId}/login', [AdminLoginController::class, 'directLogin'])->name('admin.direct-login');

                Route::get(LaravelLocalization::transRoute('routes.admin.login'), [AdminLoginController::class, 'showLoginForm'])->name('admin.login');
                Route::post(LaravelLocalization::transRoute('routes.admin.login'), [AdminLoginController::class, 'login'])->name('admin.login.post');
                Route::get(LaravelLocalization::transRoute('routes.admin.logout'), [AdminLoginController::class, 'logout'])->name('admin.logout.get');
                Route::post(LaravelLocalization::transRoute('routes.admin.logout'), [AdminLoginController::class, 'logout'])->name('admin.logout.post');
                Route::group(['middleware' => ['web', 'admin.auth']], function () {
                    Route::get('/admin/main-page', function () {
                        return view('main-page');
                    })->name('admin.main');
                });

                // Non-User Password Reset Routes
                Route::prefix('{profileType}/password')
                    ->whereIn('profileType', ['admin', 'bank', 'organization']) // Add all relevant profile types
                    ->name('non-user.password.')
                    ->group(function () {
                        Route::get('/reset', [ResetNonUserPasswordController::class, 'showLinkRequestForm'])->name('request'); // e.g., admin/password/reset
                        Route::post('/email', [ResetNonUserPasswordController::class, 'sendResetLinkEmail'])->name('email');   // e.g., POST admin/password/email
                        Route::get('/reset/{token}', [ResetNonUserPasswordController::class, 'showResetForm'])->name('reset');    // e.g., admin/password/reset/TOKEN
                        Route::post('/reset', [ResetNonUserPasswordController::class, 'reset'])->name('update');      // e.g., POST admin/password/reset
                    });
            }); // Registration-compete middleware group ends here
        });
    });
}); // End
