# Custom Domains System - Overview

This document provides an overview of the custom domains feature implementation for the Multi-Store platform.

## 📋 Table of Contents

- [Overview](#overview)
- [Features](#features)
- [Architecture](#architecture)
- [Documentation](#documentation)
- [Quick Start](#quick-start)
- [Technical Implementation](#technical-implementation)
- [Future Enhancements](#future-enhancements)

---

## Overview

The custom domains system allows sellers to use their own domain names (e.g., `sellerdomain.com`) to display their sales pages, instead of using the platform's subdirectory structure.

**Before:**
```
https://platform.com/p/seller-name/product-page
```

**After:**
```
https://sellerdomain.com/product-page
```

---

## Features

### ✅ Implemented (Phase 1-4)

- **Multi-Domain Support**: Each seller can add multiple custom domains
- **Multiple Pages Per Domain**: All seller's pages accessible via custom domain
  - `sellerdomain.com/` → Default sales page
  - `sellerdomain.com/page-1` → Specific page
  - `sellerdomain.com/page-2` → Another page
- **Primary Domain**: Sellers can mark one domain as primary
- **Domain Verification**: Manual verification with detailed instructions
- **Backward Compatibility**: Original URLs continue to work
- **DNS Instructions**: Built-in guide for sellers
- **Cloudflare Integration**: SSL setup guide included
- **Admin Dashboard**: Full CRUD operations for domains
- **Role-Based Access**: Admin, Manager, and Seller views

### 🔄 Future Enhancements (Phase 5)

- **Cloudflare API Integration**: Automatic DNS record creation
- **Automated Verification**: Via TXT records or file upload
- **Domain Analytics**: Track performance per domain
- **Auto-SSL**: Automatic Let's Encrypt SSL for custom domains

---

## Architecture

### Database Schema

**Table: `seller_domains`**

| Column | Type | Description |
|--------|------|-------------|
| id | bigint | Primary key |
| user_id | bigint | Seller/user ID (FK) |
| domain | string | Domain name (unique) |
| is_primary | boolean | Primary domain flag |
| is_active | boolean | Active status |
| verification_token | string | Token for verification |
| verified_at | timestamp | Verification timestamp |
| default_sales_page_id | bigint | Default page (FK, nullable) |
| cloudflare_record_id | text | Cloudflare DNS record ID (nullable) |
| notes | text | Admin notes (nullable) |
| created_at | timestamp | Creation timestamp |
| updated_at | timestamp | Update timestamp |

**Indexes:**
- Unique index on `domain`
- Index on `user_id`
- Composite index on `user_id, is_primary`

### Request Flow

```
1. Request → https://sellerdomain.com/page-slug
                    ↓
2. DetectCustomDomain Middleware
   - Checks host against seller_domains table
   - Finds matching verified domain
   - Attaches SellerDomain to request
                    ↓
3. Route Handling
   - Root (/) → showBySellerDomain()
   - Slug (/page-slug) → showBySellerDomainSlug()
                    ↓
4. Controller Logic
   - Finds sales page by slug + user_id
   - Loads products
   - Returns view
                    ↓
5. Response → Sales page displayed
```

### Components

**Backend:**
- `app/Models/SellerDomain.php` - Domain model with relationships
- `app/Http/Controllers/SellerDomainController.php` - CRUD operations
- `app/Http/Middleware/DetectCustomDomain.php` - Domain detection
- `routes/web.php` - Custom domain routing

**Frontend:**
- `resources/views/seller-domains/index.blade.php` - Domain list
- `resources/views/seller-domains/create.blade.php` - Add domain
- `resources/views/seller-domains/edit.blade.php` - Edit domain
- `resources/views/seller-domains/show.blade.php` - Verification guide

**Configuration:**
- `bootstrap/app.php` - Middleware registration
- `.env` - APP_URL and domain configuration

---

## Documentation

Three comprehensive guides are available:

### 1. [CUSTOM_DOMAIN_SETUP.md](./CUSTOM_DOMAIN_SETUP.md)
**For**: System Administrators
**Contents**:
- Complete OpenLiteSpeed configuration
- DNS setup instructions
- Cloudflare SSL configuration
- Troubleshooting guide
- Performance optimization
- Security best practices

### 2. [SELLER_DOMAIN_GUIDE.md](./SELLER_DOMAIN_GUIDE.md)
**For**: Sellers/End Users
**Contents**:
- Simple step-by-step setup
- DNS configuration guide
- Cloudflare SSL tutorial
- FAQ section
- Common issues and solutions
- Quick reference card

### 3. [ADMIN_SETUP_GUIDE.md](./ADMIN_SETUP_GUIDE.md)
**For**: System Administrators
**Contents**:
- Quick setup checklist
- Server configuration
- Monitoring commands
- Database queries
- Troubleshooting scripts
- Performance tuning

---

## Quick Start

### For Administrators

**1. Run Migration:**
```bash
php artisan migrate
```

**2. Configure OpenLiteSpeed:**
```apache
# Edit vhconf.conf
vhDomain $VH_NAME, *

# Edit listener
map [your-site] *
```

**3. Restart Server:**
```bash
/usr/local/lsws/bin/lswsctrl restart
```

**4. Test:**
```bash
php artisan tinker
>>> \App\Models\SellerDomain::count();
```

### For Sellers

**1. Add Domain:**
- Navigate to: My Stores → View My Domains
- Click: + Add Custom Domain
- Enter domain name

**2. Configure DNS:**
```
Type: A
Name: @
Value: [SERVER_IP]
```

**3. Wait & Verify:**
- Wait 1-2 hours for DNS propagation
- Click "Verify Domain Now"
- Domain status changes to "Active"

**4. Access:**
```
https://yourdomain.com/page-slug
```

---

## Technical Implementation

### Phase 1: Database Setup ✅

- Created `seller_domains` migration
- Created `SellerDomain` model with relationships
- Updated `User` model with domain relationships
- Added proper indexes for performance

### Phase 2: Backend - Seller Dashboard ✅

- Created `SellerDomainController` with full CRUD
- Added resource routes for domain management
- Created all 4 blade views (index, create, edit, show)
- Added navigation links to all role menus

### Phase 3: Frontend Routing ✅

- Created `DetectCustomDomain` middleware
- Updated route handling for custom domains
- Added controller methods for domain routing
- Maintained backward compatibility

### Phase 4: Documentation ✅

- Created comprehensive setup guide
- Created seller-friendly guide
- Created admin quick reference
- Added troubleshooting sections

---

## How It Works

### Domain Detection

The `DetectCustomDomain` middleware runs on every web request:

```php
public function handle(Request $request, Closure $next): Response
{
    $host = $request->getHost();
    $mainDomain = parse_url(config('app.url'), PHP_URL_HOST);

    // Check if NOT main domain
    if ($host !== $mainDomain) {
        // Look for verified custom domain
        $sellerDomain = SellerDomain::where('domain', $host)
            ->where('is_active', true)
            ->whereNotNull('verified_at')
            ->first();

        if ($sellerDomain) {
            // Attach to request
            $request->attributes->set('sellerDomain', $sellerDomain);
            $request->attributes->set('isCustomDomain', true);
        }
    }

    return $next($request);
}
```

### Routing Logic

**Root Domain (`/`):**
```php
Route::get('/', function (Request $request) {
    $sellerDomain = $request->attributes->get('sellerDomain');

    if ($sellerDomain) {
        // Show default sales page
        return app(SalesPagePublicController::class)
            ->showBySellerDomain($sellerDomain);
    }

    // Normal homepage
    return view('welcome');
});
```

**Page Slugs (`/page-slug`):**
```php
Route::get('/{slug}', function(Request $request, $slug) {
    $sellerDomain = $request->attributes->get('sellerDomain');

    if ($sellerDomain) {
        // Show specific page
        return app(SalesPagePublicController::class)
            ->showBySellerDomainSlug($sellerDomain, $slug);
    }

    abort(404);
});
```

### Domain Verification

**Manual Process:**
1. Seller adds domain in dashboard
2. Domain created with `is_active=false`
3. Seller configures DNS
4. Seller clicks "Verify Domain Now"
5. System marks domain as verified:
   ```php
   $sellerDomain->update([
       'is_active' => true,
       'verified_at' => now(),
   ]);
   ```

---

## Security Considerations

### Implemented

✅ **Domain Uniqueness**: Database unique constraint on `domain` field
✅ **Ownership Verification**: Controller checks user_id matches
✅ **Input Sanitization**: `cleanDomainName()` removes malicious input
✅ **Authorization**: Ownership verified on all operations
✅ **HTTPS Ready**: SSL configuration via Cloudflare

### Recommended

⚠️ **Rate Limiting**: Consider implementing per-domain limits
⚠️ **Automated Verification**: Implement TXT record or file verification
⚠️ **Domain Monitoring**: Monitor for expired or invalid domains
⚠️ **Abuse Prevention**: Detect and block malicious domains

---

## Performance Considerations

### Optimizations Implemented

✅ **Database Indexes**: Fast lookups on `domain` field
✅ **Middleware Efficiency**: Single query per request
✅ **Query Scoping**: Proper WHERE clauses for filtering

### Recommended Optimizations

💡 **Caching**: Cache active domains in Redis
💡 **OPcache**: Enable PHP OPcache for better performance
💡 **CDN**: Use Cloudflare for asset caching
💡 **Database**: Consider read replicas for high traffic

### Caching Strategy Example

```php
// Cache active domains for 5 minutes
$activeDomains = Cache::remember('seller_domains_active', 300, function () {
    return SellerDomain::active()
        ->verified()
        ->pluck('user_id', 'domain')
        ->toArray();
});
```

---

## Testing

### Manual Testing Checklist

**Domain Management:**
- [ ] Can add new domain
- [ ] Can edit domain settings
- [ ] Can delete domain
- [ ] Can set primary domain
- [ ] Can set default sales page

**Verification:**
- [ ] DNS instructions displayed correctly
- [ ] Verification succeeds with correct DNS
- [ ] Verification fails without DNS
- [ ] Status badges show correctly

**Routing:**
- [ ] Root domain shows default page
- [ ] Slug URLs show correct pages
- [ ] 404 for non-existent slugs
- [ ] Original URLs still work

**Authorization:**
- [ ] Users can only manage their domains
- [ ] Cannot access other users' domains
- [ ] Admin can view all domains
- [ ] Manager can view sellers' domains

### Automated Testing (Future)

```php
// Feature test example
public function test_seller_can_add_domain()
{
    $user = User::factory()->create(['role' => 'seller']);

    $response = $this->actingAs($user)
        ->post('/seller-domains', [
            'domain' => 'testdomain.com',
            'is_primary' => true,
        ]);

    $response->assertRedirect();
    $this->assertDatabaseHas('seller_domains', [
        'domain' => 'testdomain.com',
        'user_id' => $user->id,
    ]);
}
```

---

## Monitoring

### Key Metrics to Track

**Domain Statistics:**
- Total domains added
- Verified vs unverified
- Domains per seller
- Primary domain distribution

**Performance:**
- Middleware execution time
- DNS resolution time
- Page load time per domain
- Database query performance

**Health:**
- SSL certificate expiry dates
- DNS propagation status
- Failed verification attempts
- Error rates

### Monitoring Commands

```bash
# Total domains
php artisan tinker
>>> \App\Models\SellerDomain::count();

# Verified domains
>>> \App\Models\SellerDomain::verified()->count();

# Pending verification
>>> \App\Models\SellerDomain::whereNull('verified_at')->count();

# Domains added today
>>> \App\Models\SellerDomain::whereDate('created_at', today())->count();
```

---

## Troubleshooting

### Common Issues

**Issue**: Domain not loading
**Solution**: Check DNS propagation, verify OpenLiteSpeed config

**Issue**: SSL errors
**Solution**: Configure Cloudflare SSL mode to "Full"

**Issue**: 404 on pages
**Solution**: Verify sales page belongs to domain owner, check is_active

**Issue**: Performance issues
**Solution**: Enable OPcache, implement caching, use CDN

See [CUSTOM_DOMAIN_SETUP.md](./CUSTOM_DOMAIN_SETUP.md) for detailed troubleshooting.

---

## Future Enhancements

### Phase 5: Cloudflare API Integration

**Goal**: Automate DNS record creation

**Features:**
- Admin settings page for Cloudflare API credentials
- Automatic DNS record creation when domain added
- Automatic SSL certificate management
- DNS record deletion when domain removed
- Bulk domain management

**Implementation:**
```php
// CloudflareService.php
public function createDnsRecord($domain, $serverIp)
{
    $response = Http::withHeaders([
        'Authorization' => 'Bearer ' . config('services.cloudflare.api_token'),
    ])->post("https://api.cloudflare.com/client/v4/zones/{$zoneId}/dns_records", [
        'type' => 'A',
        'name' => '@',
        'content' => $serverIp,
        'proxied' => true,
    ]);

    return $response->json();
}
```

### Phase 6: Advanced Features

**Domain Analytics:**
- Track views, conversions per domain
- Compare performance across domains
- Revenue attribution

**Auto-SSL:**
- Automatic Let's Encrypt SSL generation
- Certificate renewal automation
- Multi-domain certificate management

**Domain Aliases:**
- Support for multiple domains pointing to same page
- Redirect rules (301, 302)
- Canonical URL management

---

## Support & Contact

**Documentation Issues**: Open an issue or PR
**Implementation Questions**: Contact dev team
**Seller Support**: Refer to [SELLER_DOMAIN_GUIDE.md](./SELLER_DOMAIN_GUIDE.md)

---

## Changelog

**v1.0.0 - Initial Release**
- Phase 1: Database schema
- Phase 2: Backend dashboard
- Phase 3: Frontend routing
- Phase 4: Documentation

---

**Last Updated**: 2025-10-29
**Version**: 1.0.0
**License**: Proprietary
