# Redirect Loop Fix - Deployment Guide

## Problem
The application was experiencing an infinite redirect loop when accessed at `https://Cbtapps.onrender.com` with error:
```
ERR_TOO_MANY_REDIRECTS
Cbtapps.onrender.com redirected you too many times.
```

## Root Cause
The `SetLbbContextFromSubdomain` middleware was incorrectly parsing `Cbtapps.onrender.com` as having a subdomain (`Cbtapps`). It tried to find an LBB with that subdomain, failed, and redirected back to the same URL, creating an infinite loop.

## Solution Implemented

### 1. Created `config/tenancy.php`
Added a configuration file to manage multi-tenancy settings:
- `base_domain`: The main domain for your application
- `central_domains`: List of domains considered as central/main domains

### 2. Updated Environment Variables

**Local Development (`.env`):**
```env
APP_URL=http://localhost:8000
APP_DOMAIN=localhost:8000
```

**Development on Render (`.env.dev`):**
```env
APP_URL=https://Cbtapps.onrender.com
APP_DOMAIN=Cbtapps.onrender.com
```

**For Production (`.env.prod` - when ready):**
```env
APP_URL=https://Cbtapps.com
APP_DOMAIN=Cbtapps.com
```

### 3. Fixed `SetLbbContextFromSubdomain.php`
Updated the middleware with:
- Proper subdomain detection using the configured `APP_DOMAIN`
- Enhanced `getSubdomain()` method that checks if host ends with base domain
- Improved `isCentralDomain()` method that directly matches the base domain
- Fallback logic for local development

## How It Works Now

### Main Domain (Central Domain)
- **URL**: `https://Cbtapps.onrender.com`
- **Detection**: Host matches `APP_DOMAIN` exactly
- **Result**: No subdomain detected → Application loads normally

### Subdomain (LBB-specific)
- **URL**: `https://lbb1.Cbtapps.onrender.com`
- **Detection**: Host ends with `APP_DOMAIN` with a prefix
- **Result**: Extracts `lbb1` as subdomain → Validates LBB → Sets context

### Local Development
- **URL**: `http://localhost:8000`
- **Detection**: Matches central domain list
- **Result**: No subdomain → Normal operation

## Deployment Steps for Render

### 1. Update Environment Variables in Render
Go to your Render dashboard → Cbtapps service → Environment Variables:

Add these variables:
```
APP_URL=https://Cbtapps.onrender.com
APP_DOMAIN=Cbtapps.onrender.com
```

### 2. Deploy Changes
The following files were modified/created:
- ✅ `config/tenancy.php` (new file)
- ✅ `.env.dev` (updated with APP_DOMAIN)
- ✅ `app/Http/Middleware/SetLbbContextFromSubdomain.php` (fixed)

### 3. Clear Configuration Cache
After deployment, the configuration cache will be automatically cleared when:
- New code is deployed
- Or manually: `php artisan config:clear`

### 4. Verify the Fix
1. Visit `https://Cbtapps.onrender.com`
2. Should load normally without redirect loop
3. Check logs to ensure no errors

## Testing Checklist

- [ ] Main domain loads without redirect loop
- [ ] Login page is accessible
- [ ] Dashboard loads after login
- [ ] Subdomain routing works (when LBBs with subdomains exist)
- [ ] No errors in Laravel logs

## Future Considerations

### For Production Deployment
When moving to `Cbtapps.com`:

1. **Update Production Environment Variables:**
   ```env
   APP_URL=https://Cbtapps.com
   APP_DOMAIN=Cbtapps.com
   ```

2. **Configure Custom Domains in Render:**
   - Add `Cbtapps.com` as a custom domain
   - Add DNS records (A or CNAME) as per Render's instructions

3. **Configure Subdomains (Optional):**
   - If you want `lbb1.Cbtapps.com`, add it as a custom domain in Render
   - Each subdomain needs DNS configuration

### Session Configuration
Ensure session cookies work across subdomains:

```env
SESSION_DOMAIN=.Cbtapps.onrender.com  # For dev
SESSION_DOMAIN=.Cbtapps.com            # For prod
```

## Troubleshooting

### Still getting redirect errors?
1. Clear all browser cookies
2. Clear configuration cache: `php artisan config:clear`
3. Verify `APP_DOMAIN` is set correctly in environment variables
4. Check Laravel logs: `storage/logs/laravel.log`

### Subdomains not working?
1. Verify LBB record exists with correct subdomain
2. Check LBB status is ACTIVE
3. Ensure custom domains are configured in Render
4. Verify DNS records are correct

### Session issues across domains?
1. Check `SESSION_DOMAIN` is set with leading dot: `.domain.com`
2. Ensure `SESSION_SECURE=true` for HTTPS
3. Verify `SESSION_SAME_SITE` setting if needed

## Files Changed Summary

| File | Status | Description |
|------|--------|-------------|
| `config/tenancy.php` | ✅ Created | Multi-tenancy configuration |
| `.env` | ✅ Updated | Added `APP_DOMAIN=localhost:8000` |
| `.env.dev` | ✅ Updated | Added `APP_DOMAIN=Cbtapps.onrender.com` |
| `app/Http/Middleware/SetLbbContextFromSubdomain.php` | ✅ Fixed | Proper subdomain detection |

## Technical Details

### Subdomain Detection Logic
```php
// For Cbtapps.onrender.com
$host = "Cbtapps.onrender.com";
$baseDomain = "Cbtapps.onrender.com";

// Check if host ends with base domain
if (str_ends_with($host, $baseDomain)) {
    $potentialSubdomain = str_replace($baseDomain, '', $host);
    // Result: "" (empty) → No subdomain
}

// For lbb1.Cbtapps.onrender.com
$host = "lbb1.Cbtapps.onrender.com";

if (str_ends_with($host, $baseDomain)) {
    $potentialSubdomain = str_replace($baseDomain, '', $host);
    // Result: "lbb1" → Subdomain detected
}
```

## Support
If issues persist after following this guide:
1. Check Laravel logs: `storage/logs/laravel.log`
2. Enable debug mode temporarily: `APP_DEBUG=true`
3. Verify Render deployment logs
4. Test with `php artisan route:list --path=/` to see routes

---

**Fix implemented on**: March 20, 2026  
**Status**: ✅ Ready for deployment