# Domain Setup Examples - Real World Scenarios

**For:** taskcodigital.com Multi-Tenant System

---

## Scenario 1: Basic Subdomain Setup

**Goal:** Create `acme.taskcodigital.com` for ACME Corp

### Step-by-Step

```bash
# 1. DNS already configured (wildcard *.taskcodigital.com)
# No additional DNS needed

# 2. Create tenant via API
curl -X POST https://taskcodigital.com/create-tenant \
  -H "Content-Type: application/json" \
  -d '{
    "tenant_id": "acme",
    "company_name": "ACME Corporation",
    "email": "admin@acme.com",
    "domain": "acme.taskcodigital.com",
    "plan": "pro",
    "max_users": 25
  }'

# 3. Access tenant
# Visit: https://acme.taskcodigital.com
# Login: admin@example.com / password
```

**Result:**
- ✅ Domain: `acme.taskcodigital.com`
- ✅ SSL: Automatically covered by wildcard certificate
- ✅ Database: `taskco-acme` created
- ✅ Ready to use immediately

---

## Scenario 2: Multiple Tenants on Subdomains

**Goal:** Create multiple tenants for different clients

```bash
# Client 1: ACME Corp
curl -X POST https://taskcodigital.com/create-tenant \
  -H "Content-Type: application/json" \
  -d '{
    "tenant_id": "acme",
    "company_name": "ACME Corp",
    "domain": "acme.taskcodigital.com",
    "plan": "enterprise",
    "max_users": 100
  }'

# Client 2: Demo Company
curl -X POST https://taskcodigital.com/create-tenant \
  -H "Content-Type: application/json" \
  -d '{
    "tenant_id": "demo",
    "company_name": "Demo Company",
    "domain": "demo.taskcodigital.com",
    "plan": "basic",
    "max_users": 10
  }'

# Client 3: Startup Inc
curl -X POST https://taskcodigital.com/create-tenant \
  -H "Content-Type: application/json" \
  -d '{
    "tenant_id": "startup",
    "company_name": "Startup Inc",
    "domain": "startup.taskcodigital.com",
    "plan": "pro",
    "max_users": 50
  }'
```

**Result:**
- ✅ `https://acme.taskcodigital.com` → ACME Corp
- ✅ `https://demo.taskcodigital.com` → Demo Company
- ✅ `https://startup.taskcodigital.com` → Startup Inc

---

## Scenario 3: Custom Domain for Premium Client

**Goal:** Client wants to use their own domain `acmecorp.com`

### Client Side (Customer does this)

**DNS Configuration at their registrar:**

```
Type: CNAME
Name: @
Value: taskcodigital.com
TTL: 3600

OR

Type: A
Name: @
Value: YOUR_SERVER_IP
TTL: 3600
```

### Your Side (You do this)

```bash
# 1. Add custom domain to tenant
php artisan tinker
```

```php
$tenant = \App\Models\Tenant::find('acme');

// Add custom domain
$customDomain = $tenant->domains()->create([
    'domain' => 'acmecorp.com',
    'is_primary' => false,
    'is_custom' => true,
    'status' => 'pending'
]);

// Configure SSL settings
$customDomain->sslConfig()->create([
    'ssl_enabled' => false,
    'ssl_provider' => 'Let\'s Encrypt'
]);

// Configure DNS tracking
$customDomain->dnsRecords()->create([
    'dns_status' => 'pending'
]);

// Configure HTTPS redirect
$customDomain->redirectSettings()->create([
    'force_https' => true,
    'redirect_enabled' => false
]);

echo "Custom domain added. Waiting for DNS propagation...";
```

```bash
# 2. Wait for DNS propagation (check with)
nslookup acmecorp.com

# 3. Get SSL certificate
sudo certbot --nginx -d acmecorp.com -d www.acmecorp.com

# 4. Verify and activate
php artisan tinker
```

```php
$domain = \App\Models\Domain::where('domain', 'acmecorp.com')->first();

// Activate domain
$domain->update(['status' => 'active']);

// Update DNS status
$domain->dnsRecords()->update([
    'dns_status' => 'verified',
    'dns_verified_at' => now()
]);

// Update SSL status
$domain->sslConfig()->update([
    'ssl_enabled' => true,
    'ssl_expires_at' => now()->addDays(90)
]);

echo "Custom domain activated!";
```

**Result:**
- ✅ `https://acmecorp.com` → Points to ACME tenant
- ✅ `https://acme.taskcodigital.com` → Still works (subdomain)
- ✅ Both domains show same tenant data

---

## Scenario 4: Migrating Existing Tenant to Custom Domain

**Goal:** Tenant started with `startup.taskcodigital.com`, now wants `startup.io`

```bash
# 1. Keep existing subdomain active
# 2. Add new custom domain

php artisan tinker
```

```php
$tenant = \App\Models\Tenant::find('startup');

// Add new custom domain (don't remove old one)
$newDomain = $tenant->domains()->create([
    'domain' => 'startup.io',
    'is_primary' => true,  // Make it primary
    'is_custom' => true,
    'status' => 'pending'
]);

// Configure settings
$newDomain->sslConfig()->create(['ssl_enabled' => false]);
$newDomain->dnsRecords()->create(['dns_status' => 'pending']);
$newDomain->redirectSettings()->create([
    'force_https' => true,
    'redirect_enabled' => true,
    'redirect_type' => 301
]);

// Set old subdomain as non-primary
$oldDomain = $tenant->domains()->where('domain', 'startup.taskcodigital.com')->first();
$oldDomain->update(['is_primary' => false]);

// Optional: Redirect old domain to new
$oldDomain->redirectSettings()->update([
    'redirect_enabled' => true,
    'redirect_to' => 'https://startup.io',
    'redirect_type' => 301
]);
```

```bash
# Get SSL for new domain
sudo certbot --nginx -d startup.io -d www.startup.io

# Activate
```

```php
$newDomain->update(['status' => 'active']);
$newDomain->dnsRecords()->update([
    'dns_status' => 'verified',
    'dns_verified_at' => now()
]);
$newDomain->sslConfig()->update([
    'ssl_enabled' => true,
    'ssl_expires_at' => now()->addDays(90)
]);
```

**Result:**
- ✅ `https://startup.io` → Primary (new)
- ✅ `https://startup.taskcodigital.com` → Redirects to startup.io (301)
- ✅ No data loss, seamless migration

---

## Scenario 5: WWW Subdomain Setup

**Goal:** Support both `taskcodigital.com` and `www.taskcodigital.com`

### Nginx Configuration

```nginx
server {
    listen 80;
    listen 443 ssl http2;
    
    server_name taskcodigital.com www.taskcodigital.com;
    
    # Redirect www to non-www
    if ($host = 'www.taskcodigital.com') {
        return 301 https://taskcodigital.com$request_uri;
    }
    
    # ... rest of configuration
}
```

### Or keep both (don't redirect)

```nginx
server {
    listen 80;
    listen 443 ssl http2;
    
    # Both work without redirect
    server_name taskcodigital.com www.taskcodigital.com;
    
    # ... rest of configuration
}
```

```bash
# Get SSL for both
sudo certbot --nginx -d taskcodigital.com -d www.taskcodigital.com
```

**Result:**
- ✅ `https://taskcodigital.com` → Works
- ✅ `https://www.taskcodigital.com` → Works (or redirects)

---

## Scenario 6: Development to Production Migration

**Goal:** Move from `localhost` development to `taskcodigital.com` production

### Step 1: Backup Everything

```bash
# Backup database
mysqldump -u root -p taskco_central > backup_central_$(date +%Y%m%d).sql

# Backup tenant databases
php artisan tinker --execute="
\App\Models\Tenant::all()->each(function(\$t) {
    \$db = 'taskco-' . \$t->id;
    exec('mysqldump -u root -p' . env('DB_PASSWORD') . ' ' . \$db . ' > backup_' . \$t->id . '_' . date('Ymd') . '.sql');
});
"

# Backup files
tar -czf backup_files_$(date +%Y%m%d).tar.gz /var/www/sajjad.site/erp-starterkit
```

### Step 2: Update Configuration

```env
# .env - Old (Development)
APP_URL=http://localhost:8000
APP_ENV=local
APP_DEBUG=true
SESSION_DOMAIN=localhost

# .env - New (Production)
APP_URL=https://taskcodigital.com
APP_ENV=production
APP_DEBUG=false
SESSION_DOMAIN=.taskcodigital.com
```

```php
// config/tenancy.php - Old
'central_domains' => [
    '127.0.0.1',
    'localhost',
],

// config/tenancy.php - New
'central_domains' => [
    'taskcodigital.com',
    'www.taskcodigital.com',
],
```

### Step 3: Update Existing Tenant Domains

```bash
php artisan tinker
```

```php
// Update all localhost domains to taskcodigital.com
\App\Models\Domain::where('domain', 'like', '%.localhost')->get()->each(function($domain) {
    $newDomain = str_replace('.localhost', '.taskcodigital.com', $domain->domain);
    $domain->update(['domain' => $newDomain]);
    echo "Updated: {$domain->domain} → {$newDomain}\n";
});
```

### Step 4: Clear Caches and Optimize

```bash
php artisan optimize:clear
php artisan config:cache
php artisan route:cache
php artisan view:cache
```

**Result:**
- ✅ All tenants migrated to new domain
- ✅ Production-ready configuration
- ✅ Backups created

---

## Scenario 7: Multi-Region Setup (Advanced)

**Goal:** Serve from multiple regions using subdomains

```
taskcodigital.com          → Main (US)
eu.taskcodigital.com      → Europe region
asia.taskcodigital.com    → Asia region
```

### DNS Configuration

```
# US (Default)
Type: A,  Name: @,     Value: US_SERVER_IP
Type: A,  Name: *,     Value: US_SERVER_IP

# Europe
Type: A,  Name: eu,    Value: EU_SERVER_IP
Type: A,  Name: *.eu,  Value: EU_SERVER_IP

# Asia
Type: A,  Name: asia,  Value: ASIA_SERVER_IP
Type: A,  Name: *.asia, Value: ASIA_SERVER_IP
```

### Configure Each Server

On US server:
```env
APP_URL=https://taskcodigital.com
SESSION_DOMAIN=.taskcodigital.com
```

On EU server:
```env
APP_URL=https://eu.taskcodigital.com
SESSION_DOMAIN=.eu.taskcodigital.com
```

On Asia server:
```env
APP_URL=https://asia.taskcodigital.com
SESSION_DOMAIN=.asia.taskcodigital.com
```

**Result:**
- ✅ `acme.taskcodigital.com` → US server
- ✅ `acme.eu.taskcodigital.com` → EU server
- ✅ `acme.asia.taskcodigital.com` → Asia server

---

## Scenario 8: Testing New Domain Before Going Live

**Goal:** Test custom domain without affecting production

### Add to /etc/hosts (Local Testing)

```bash
# On your local machine
sudo nano /etc/hosts

# Add:
YOUR_SERVER_IP    testclient.com
YOUR_SERVER_IP    www.testclient.com
```

### Test Access

```bash
# Now you can test locally
curl https://testclient.com

# When ready, update actual DNS
```

**Result:**
- ✅ Test domain locally before DNS change
- ✅ No production impact
- ✅ Verify everything works

---

## Scenario 9: Emergency Domain Switch

**Goal:** Quickly switch tenant to different domain (DDoS, issues, etc.)

```bash
php artisan tinker
```

```php
$tenant = \App\Models\Tenant::find('acme');

// Deactivate current domain
$oldDomain = $tenant->domains()->where('is_primary', true)->first();
$oldDomain->update(['status' => 'inactive', 'is_primary' => false]);

// Activate backup domain
$backupDomain = $tenant->domains()->where('domain', 'acme-backup.taskcodigital.com')->first();

if (!$backupDomain) {
    // Create if doesn't exist
    $backupDomain = $tenant->domains()->create([
        'domain' => 'acme-backup.taskcodigital.com',
        'is_primary' => true,
        'is_custom' => false,
        'status' => 'active'
    ]);
}

$backupDomain->update(['status' => 'active', 'is_primary' => true]);

echo "Switched to backup domain: acme-backup.taskcodigital.com";
```

**Result:**
- ✅ Tenant switched to backup domain in seconds
- ✅ Service continues without interruption
- ✅ Can switch back when issue resolved

---

## Scenario 10: Bulk Tenant Import with Domains

**Goal:** Import 100 tenants from CSV

```bash
# tenants.csv:
# tenant_id,company_name,email,subdomain
# acme,ACME Corp,admin@acme.com,acme
# demo,Demo Co,admin@demo.com,demo
```

```php
// Import script
$csv = array_map('str_getcsv', file('tenants.csv'));
array_shift($csv); // Remove header

foreach ($csv as $row) {
    [$tenantId, $companyName, $email, $subdomain] = $row;
    
    // Create tenant
    $tenant = \App\Models\Tenant::create([
        'id' => $tenantId,
        'company_name' => $companyName,
        'email' => $email,
    ]);
    
    // Create related tables
    $tenant->subscription()->create(['plan' => 'basic', 'status' => 'trial']);
    $tenant->limits()->create(['max_users' => 10, 'max_storage_mb' => 1000]);
    $tenant->settings()->create(['timezone' => 'UTC', 'language' => 'en', 'currency' => 'USD']);
    
    // Create domain
    $tenant->domains()->create([
        'domain' => $subdomain . '.taskcodigital.com',
        'is_primary' => true,
        'is_custom' => false,
        'status' => 'active'
    ]);
    
    // Setup tenant database
    Artisan::call('tenant:full-setup', ['tenant' => $tenantId]);
    
    echo "Created: {$companyName} @ {$subdomain}.taskcodigital.com\n";
}

echo "Import complete!";
```

**Result:**
- ✅ 100 tenants created automatically
- ✅ All with subdomains on taskcodigital.com
- ✅ Databases and seeders set up

---

## Best Practices Summary

1. **Always use HTTPS** - Free with Let's Encrypt
2. **Wildcard SSL** - Covers all subdomains automatically
3. **Test DNS** - Use `nslookup` before going live
4. **Backup first** - Before any production changes
5. **Keep subdomains** - Even when using custom domains (fallback)
6. **Monitor SSL expiry** - Set up auto-renewal
7. **Log everything** - Check logs regularly
8. **Use staging** - Test on test.taskcodigital.com first

---

**Need more help?** See `Custom Domain Setup Guide.md` for detailed instructions.
