# Optimized Route Structure

## Current Route Organization Issues

The current routing system has several problems:

- Route duplication across multiple files
- Complex domain-based routing spread across different files
- Inconsistent middleware application
- Hard to maintain and understand

## Proposed New Structure

```
routes/
├── web.php                     # Main route orchestrator
├── api.php                     # API routes (unchanged)
├── console.php                 # Console routes (unchanged)
├── channels.php                # Broadcasting routes (unchanged)
├── domains/
│   ├── main.php               # Main domain routes (mivita.care)
│   ├── shop.php               # Shop domain routes (mivita.shop)
│   └── subdomains/
│       ├── crm.php            # CRM routes (my.mivita.care)
│       ├── portal.php         # Portal routes (in.mivita.care)
│       ├── checkout.php       # Checkout routes (checkout.mivita.care)
│       └── user-shops.php     # User shop routes ({slug}.mivita.care)
└── shared/
    ├── legal.php             # Legal pages (shared across domains)
    ├── common.php            # Common functionality
    └── api/
        └── v1.php           # API version 1 routes
```

## Implementation Examples

### routes/web.php (Orchestrator)

```php
<?php

use App\Domain\DomainContext;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes Orchestrator
|--------------------------------------------------------------------------
|
| This file serves as the main orchestrator for all web routes.
| Domain-specific routes are loaded based on the current domain context.
|
*/

// Get domain context from middleware
$domainContext = app('domain.context');

// Load shared routes first (legal pages, etc.)
require __DIR__ . '/shared/legal.php';
require __DIR__ . '/shared/common.php';

// Load domain-specific routes based on context
match($domainContext->type) {
    'main' => require __DIR__ . '/domains/main.php',
    'main-shop' => require __DIR__ . '/domains/shop.php',
    'crm' => require __DIR__ . '/domains/subdomains/crm.php',
    'portal' => require __DIR__ . '/domains/subdomains/portal.php',
    'checkout' => require __DIR__ . '/domains/subdomains/checkout.php',
    'user-shop' => require __DIR__ . '/domains/subdomains/user-shops.php',
    default => null // Unknown domains handled by middleware
};
```

### routes/domains/main.php (Main Domain)

```php
<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Main Domain Routes (mivita.care)
|--------------------------------------------------------------------------
*/

Route::middleware(['domain.resolver'])->group(function () {

    // Home page
    Route::get('/', 'Web\SiteController@index')->name('home');

    // Registration
    Route::get('/registrierung', 'Web\RegisterController@index')->name('register_user');
    Route::get('/reg/{member_id?}', 'Web\RegisterController@member')->name('register_user_member');
    Route::post('/registrierung', 'Web\RegisterController@register')->name('register_user');
    Route::get('/registrierung/finish', 'Web\RegisterController@finish')->name('register_user_finish');

    // Contact
    Route::get('/kontakt', 'Web\ContactController@create')->name('contact_create');
    Route::post('/kontakt', 'Web\ContactController@store')->name('contact_store');

    // Dynamic site routing
    Route::get('/{site}/{subsite?}/{product_slug?}', 'Web\SiteController@site')->name('base.site');

    // Language switching
    Route::post('/change_website_lang', 'Web\SiteController@changeLang')->name('change_website_lang');
});
```

### routes/domains/subdomains/crm.php (CRM Domain)

```php
<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| CRM Domain Routes (my.mivita.care)
|--------------------------------------------------------------------------
*/

Route::domain(config('app.pre_url_crm') . config('app.domain') . config('app.tld_care'))
    ->middleware(['domain.resolver', 'web'])
    ->group(function () {

    // Cron jobs (public access)
    Route::get('/cron/jobs/action/{action}/{key}', 'CronController@action')->name('cron_jobs_action');
    Route::get('/cron/jobs/run/{key}', 'CronController@runCron')->name('cron_jobs_run');

    // Authentication routes
    Auth::routes();
    Route::get('/logout', function () {
        Auth::logout();
        return redirect()->route('login');
    })->name('logout');

    // Public routes
    Route::get('/', 'HomeController@index')->name('home');
    Route::get('/register/verify/{confirmationCode}', 'HomeController@verify')->name('register_verify');
    Route::get('/homeparty/{token?}/{gid?}', 'Web\HomepartyController@detail')->name('homeparty');
    Route::post('/homeparty/{token?}/{gid?}', 'Web\HomepartyController@detailStore')->name('homeparty');

    // Authenticated routes
    Route::middleware(['auth'])->group(function () {
        require __DIR__ . '/../../shared/crm/authenticated.php';
    });

    // Admin routes
    Route::middleware(['admin'])->group(function () {
        require __DIR__ . '/../../shared/crm/admin.php';
    });

    // Super admin routes
    Route::middleware(['superadmin'])->group(function () {
        require __DIR__ . '/../../shared/crm/superadmin.php';
    });

    // System admin routes
    Route::middleware(['sysadmin'])->group(function () {
        require __DIR__ . '/../../shared/crm/sysadmin.php';
    });
});
```

### routes/domains/subdomains/user-shops.php (User Shops)

```php
<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| User Shop Domain Routes ({slug}.mivita.care)
|--------------------------------------------------------------------------
*/

Route::middleware(['domain.resolver', 'web'])->group(function () {

    // Home page
    Route::get('/', 'Web\SiteController@index')->name('shop.home');

    // Shopping cart functionality
    Route::prefix('user/card')->name('user.card_')->group(function () {
        Route::get('/add/{id}/{quantity?}/{product_slug?}', 'Web\CardController@addToCardGet')->name('add_get');
        Route::post('/add/{id}', 'Web\CardController@addToCardPost')->name('add_post');
        Route::get('/show', 'Web\CardController@showCard')->name('show');
        Route::get('/checkout/server', 'Web\CardController@checkoutServer')->name('checkout_server');
        Route::post('/update', 'Web\CardController@updateCard')->name('update');
        Route::get('/remove/{rowId}', 'Web\CardController@removeCard')->name('remove');
        Route::get('/delete', 'Web\CardController@deleteCard')->name('delete');
    });

    // Shop navigation
    Route::get('/user/back/to/shop/{reference?}', 'Web\CardController@backToShop')->name('user.back_to_shop');
    Route::get('/domain/check', 'Web\SiteController@domainCheck')->name('user.domain_check');

    // Registration with referral
    Route::get('/registrierung', 'Web\RegisterController@index')->name('shop.register_user');
    Route::get('/reg/{member_id?}', 'Web\RegisterController@member')->name('shop.register_user_member');
    Route::post('/registrierung', 'Web\RegisterController@register')->name('shop.register_user');
    Route::get('/registrierung/finish', 'Web\RegisterController@finish')->name('shop.register_user_finish');

    // Dynamic site routing (must be last)
    Route::get('/{site}/{subsite?}/{product_slug?}', 'Web\SiteController@site')->name('shop.site');

    // Language switching
    Route::post('/change_website_lang', 'Web\SiteController@changeLang')->name('shop.change_website_lang');
});
```

### routes/shared/legal.php (Shared Legal Pages)

```php
<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Shared Legal Routes
|--------------------------------------------------------------------------
| These routes are available across all domain types
*/

Route::get('/datenschutz', 'HomeController@legalDataProtected')->name('datenschutz');
Route::get('/impressum', 'HomeController@legalImprint')->name('impressum');
Route::get('/agb', 'HomeController@legalAGB')->name('agb');

// English routes
Route::get('/data-protection', 'HomeController@legalDataProtected')->name('data_protected');
Route::get('/imprint', 'HomeController@legalImprint')->name('imprint');
Route::get('/terms', 'HomeController@legalAGB')->name('terms');
```

### routes/shared/common.php (Common Functionality)

```php
<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Common Routes
|--------------------------------------------------------------------------
| These routes provide common functionality across domains
*/

// Modal loading (AJAX)
Route::post('/loading/modal', 'HomeController@loadingModal')->name('loading_modal');

// Health check
Route::get('/health', function () {
    return response()->json(['status' => 'ok']);
})->name('health_check');

// Maintenance mode check
Route::get('/maintenance', function () {
    return view('maintenance');
})->name('maintenance');
```

## Benefits of New Structure

### 1. Clear Separation of Concerns

- Each domain type has its own route file
- Shared functionality is clearly separated
- Easy to understand which routes belong to which domain

### 2. Reduced Duplication

- Legal pages defined once and shared
- Common functionality centralized
- Domain-specific routes only defined once

### 3. Better Maintainability

- Changes to specific domain types are isolated
- Easier to add new domain types
- Clear structure for new developers

### 4. Performance Benefits

- Only relevant routes are loaded per domain
- Reduced route compilation time
- Better caching possibilities

### 5. Enhanced Security

- Domain-specific middleware applied correctly
- Easier to implement domain-specific security rules
- Clear boundaries between different application areas

## Migration Strategy

### Phase 1: Create New Structure

1. Create new directory structure
2. Copy existing routes to appropriate new files
3. Test each domain type individually

### Phase 2: Update Route Service Provider

1. Modify RouteServiceProvider to use new orchestrator
2. Implement domain context checking
3. Add fallback mechanisms

### Phase 3: Clean Up

1. Remove old route files
2. Update any hardcoded route references
3. Update documentation

### Phase 4: Optimize

1. Implement route caching per domain
2. Add performance monitoring
3. Optimize middleware stack per domain type
