# Mivita Multi-Domain & Subdomain Architecture Optimization

## Current Implementation Analysis

### Domain Structure Overview
The mivita.care application uses a multi-domain and subdomain architecture to serve different application areas:

#### Main Domains & Subdomains:
1. **Main Domain**: `mivita.care` (or `mivita.test` in development)
2. **Fixed Subdomains**:
   - `my.mivita.care` - CRM/Customer Management System
   - `in.mivita.care` - Portal for customers
   - `checkout.mivita.care` - Checkout/Payment processing
3. **Dynamic Subdomains**: `{shop-slug}.mivita.care` - Individual user shops
4. **Alternative Domain**: `mivita.shop` - Alternative shopping domain

### Current Architecture Issues

#### 1. Subdomain Middleware Problems
**File**: `app/Http/Middleware/Subdomain.php`

**Issues Identified**:
- Hard-coded shop selection (`'aloevera'`) for main domain
- Mixed responsibility (handles both dynamic shops and main domain logic)
- No proper fallback mechanism for invalid subdomains
- Configuration dependencies scattered across middleware
- Session management directly in middleware

#### 2. Routing Complexity
**Current Structure**:
```
routes/
├── web.php          # Main entry (mostly empty)
├── main.php         # Main domain routes
├── subdomain.php    # Dynamic subdomain routes  
├── crm.php          # CRM subdomain (my.)
├── portal.php       # Portal subdomain (in.)
├── checkout.php     # Checkout subdomain (checkout.)
├── api.php          # API routes
└── utility.php      # Utility routes
```

**Issues**:
- Route duplication across files
- No clear separation of concerns
- Complex domain-based routing in multiple files
- Inconsistent middleware application

#### 3. Configuration Management
**File**: `.env`

**Current Setup**:
```
APP_DOMAIN=mivita
APP_TLD_CARE=.test
APP_TLD_SHOP=.lshop
APP_URL_CHECKOUT=checkout.
APP_URL_CRM=my.
APP_URL_PORTAL=in.
```

**Issues**:
- Environment-dependent configuration
- No centralized domain management
- Missing validation for domain configurations

## Optimization Proposal

### 1. Enhanced Subdomain Middleware

Create a new, more robust subdomain middleware system:

```php
// app/Http/Middleware/DomainResolver.php
class DomainResolver
{
    public function handle($request, Closure $next)
    {
        $domain = $this->resolveDomain($request);
        
        // Set domain context
        app()->instance('domain.context', $domain);
        
        return $next($request);
    }
    
    private function resolveDomain($request): DomainContext
    {
        // Logic to determine domain type and set appropriate context
    }
}
```

### 2. Domain Configuration Service

```php
// app/Services/DomainService.php
class DomainService
{
    public function getSubdomainType(string $subdomain): string
    {
        // Determine if subdomain is fixed (my, in, checkout) or dynamic (user shop)
    }
    
    public function isValidUserShop(string $slug): bool
    {
        // Validate user shop existence and status
    }
    
    public function getDomainConfiguration(): array
    {
        // Return centralized domain configuration
    }
}
```

### 3. Improved Route Organization

```
routes/
├── web.php                 # Route registration orchestrator
├── domains/
│   ├── main.php           # Main domain (mivita.care)  
│   ├── shop.php           # Alternative domain (mivita.shop)
│   └── subdomains/
│       ├── crm.php        # my.mivita.care
│       ├── portal.php     # in.mivita.care  
│       ├── checkout.php   # checkout.mivita.care
│       └── user-shops.php # {slug}.mivita.care
├── api/
│   └── v1.php            # API routes
└── shared/
    ├── legal.php         # Legal pages (shared across domains)
    └── common.php        # Common functionality
```

### 4. Domain Context System

```php
// app/Domain/DomainContext.php
class DomainContext
{
    public function __construct(
        public readonly string $type,        // 'main', 'crm', 'portal', 'checkout', 'user-shop'
        public readonly string $domain,      // Full domain
        public readonly ?string $subdomain,  // Subdomain part
        public readonly ?UserShop $userShop  // For user shop contexts
    ) {}
    
    public function isMainDomain(): bool
    public function isCrmDomain(): bool  
    public function isPortalDomain(): bool
    public function isCheckoutDomain(): bool
    public function isUserShopDomain(): bool
}
```

## Implementation Benefits

### 1. Performance Improvements
- **Reduced Database Queries**: Cache user shop validity
- **Faster Route Resolution**: Dedicated route files per domain type
- **Optimized Middleware Stack**: Domain-specific middleware application

### 2. Maintainability
- **Clear Separation of Concerns**: Each domain type has its own route file
- **Centralized Configuration**: Single source of truth for domain settings
- **Consistent Architecture**: Uniform handling across all domain types

### 3. Scalability  
- **Easy Subdomain Addition**: New subdomains can be added without touching existing code
- **Flexible Configuration**: Environment-agnostic domain management
- **Modular Structure**: Independent development of domain-specific features

### 4. Security Enhancements
- **Domain Validation**: Proper validation of all subdomain requests
- **Context Isolation**: Clear boundaries between different application areas
- **CSRF Protection**: Domain-aware CSRF token handling

## Migration Strategy

### Phase 1: Foundation
1. Create new `DomainService` and `DomainContext` classes
2. Implement enhanced `DomainResolver` middleware
3. Add domain configuration management

### Phase 2: Route Reorganization  
1. Create new route structure under `routes/domains/`
2. Migrate existing routes to new organization
3. Update route service provider

### Phase 3: Testing & Optimization
1. Comprehensive testing of all domain types
2. Performance optimization and caching
3. Documentation updates

### Phase 4: Deployment
1. Gradual rollout with fallback mechanisms
2. Monitor performance and functionality
3. Remove old code after successful migration

## Risk Assessment

### Low Risk
- Domain service implementation
- Route reorganization
- Configuration centralization

### Medium Risk  
- Middleware replacement (affects all requests)
- Session handling changes
- Cache invalidation

### High Risk
- User shop subdomain handling (affects customer shops)
- Payment domain changes (affects revenue)

## Monitoring & Rollback Plan

### Monitoring Points
- Response times per domain type
- Error rates by subdomain
- User shop accessibility
- Payment processing success rates

### Rollback Strategy
- Feature flags for gradual enablement
- Database transaction rollbacks for configuration changes
- Immediate fallback to current middleware if critical issues arise

## Conclusion

This optimization will provide a more maintainable, scalable, and performant multi-domain architecture while preserving all existing functionality. The modular approach allows for incremental implementation and testing, reducing deployment risks.