# Domain Dropdown - Auto Sync Guide

**Version:** 1.0.0
**Feature:** Automatic domain synchronization between Admin Dashboard and User Shortlink Form

---

## 🎯 How It Works

### Admin Side (Domain Management)

1. **Admin adds domain:**
   ```
   Admin Dashboard → Domains Tab → Add Domain
   Domain: example.com
   Status: active
   ```

2. **Domain saved to database:**
   ```sql
   INSERT INTO domains (domain, status) VALUES ('example.com', 'active');
   ```

### User Side (Shortlink Creation)

1. **User opens Shortlink Form**
2. **JavaScript auto-loads domains:**
   ```javascript
   loadDomains() → fetch('/ajax/get-domains.php?status=active')
   ```

3. **Dropdown populated:**
   ```
   🌐 Global Domain (Random)
   ──────────────────────
   example.com         ← Auto-loaded dari database
   example01.com       ← Auto-loaded dari database
   example02.com       ← Auto-loaded dari database
   ```

---

## ✅ Complete Flow Diagram

```
┌─────────────────────────────────────────────────────────────┐
│                     ADMIN DASHBOARD                         │
│  ┌───────────────────────────────────────────────────────┐  │
│  │ Domains Tab                                           │  │
│  │  [Add Domain] Button                                  │  │
│  │                                                        │  │
│  │  Domain: example.com                                  │  │
│  │  [Add] ───────────────────────┐                       │  │
│  └────────────────────────────────┼───────────────────────┘  │
└─────────────────────────────────┼─────────────────────────┘
                                  ▼
                        ┌──────────────────────┐
                        │   DATABASE TABLE     │
                        │     `domains`        │
                        │ ┌──────────────────┐ │
                        │ │ id | domain      │ │
                        │ ├────┼─────────────┤ │
                        │ │ 1  │ example.com │ │
                        │ │ 2  │ example01.. │ │
                        │ │ 3  │ example02.. │ │
                        │ └──────────────────┘ │
                        └──────────────────────┘
                                  ▲
                                  │ SELECT * WHERE status='active'
                                  │
┌─────────────────────────────────┼─────────────────────────┐
│                     USER DASHBOARD                          │
│  ┌───────────────────────────────┼───────────────────────┐  │
│  │ Shortlink Form                │                       │  │
│  │                               │                       │  │
│  │  Domain: [Dropdown] ◄─────────┘                       │  │
│  │   ┌────────────────────────────────────┐             │  │
│  │   │ 🌐 Global Domain (Random)         │             │  │
│  │   │ ──────────────────────────         │             │  │
│  │   │ example.com       ◄─ Auto loaded  │             │  │
│  │   │ example01.com     ◄─ Auto loaded  │             │  │
│  │   │ example02.com     ◄─ Auto loaded  │             │  │
│  │   └────────────────────────────────────┘             │  │
│  └───────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
```

---

## 🔧 Implementation Details

### 1. Database Query (Backend)

**File:** `public/ajax/get-domains.php`

```php
// Get domains from database
$domains = $domainService->getAllDomains();

// Filter only active domains
$activeDomains = array_filter($domains, function ($domain) {
    return $domain['status'] === 'active';
});

// Return JSON
echo json_encode([
    'success' => true,
    'domains' => $activeDomains,
]);
```

**SQL Query:**
```sql
SELECT * FROM domains WHERE status = 'active' ORDER BY created_at DESC;
```

---

### 2. AJAX Request (Frontend)

**File:** `public/components/shortlink-form.html`

```javascript
async function loadDomains() {
    try {
        // Fetch active domains
        const response = await fetch('/ajax/get-domains.php?status=active&limit=100');
        const result = await response.json();

        if (result.success && result.data.domains) {
            const select = document.getElementById('domainSelection');

            // Populate dropdown
            result.data.domains.forEach(domain => {
                const option = document.createElement('option');
                option.value = domain.id;           // Domain ID for database
                option.textContent = domain.domain;  // Display: example.com
                select.appendChild(option);
            });

            console.log(`✅ Loaded ${result.data.domains.length} domains`);
        }

    } catch (error) {
        console.error('Failed to load domains:', error);
    }
}

// Execute on page load
loadDomains();
```

---

### 3. Form Submission

When user creates shortlink:

```javascript
// Get selected domain
const domainSelection = formData.get('domain_selection');

if (domainSelection === 'global') {
    // Use global domain (random selection)
    use_global_domain = 1
    domain_id = NULL
} else {
    // Use specific domain (ID selected)
    use_global_domain = 0
    domain_id = domainSelection  // e.g., 3 (example02.com)
}
```

**Database Insert:**
```sql
INSERT INTO shortlinks (slug, subdomain, domain_id, use_global_domain, destination_url)
VALUES ('abc123', 'xy7k2m', 3, 0, 'https://example.com');
```

**Result URL:**
```
https://xy7k2m.example02.com/abc123
```

---

## 🧪 Testing Guide

### Test 1: Add Domain in Admin

1. Login as admin
2. Go to **Domains** tab
3. Click **Add Domain**
4. Enter:
   - Domain: `test-domain.com`
   - Status: `active`
5. Click **Add**

**Expected:** Domain saved to database

```sql
-- Verify
SELECT * FROM domains WHERE domain = 'test-domain.com';
```

---

### Test 2: Verify Domain in User Dropdown

1. Open **Shortlink Form**
2. Open Browser Console (F12)
3. Check logs:
   ```
   ✅ Loaded 4 domain(s)
   ```
4. Click **Domain Dropdown**
5. Verify `test-domain.com` appears:
   ```
   🌐 Global Domain (Random)
   ──────────────────────
   example.com
   example01.com
   example02.com
   test-domain.com     ← NEW!
   ```

---

### Test 3: Create Shortlink with Specific Domain

1. Fill form:
   - Destination URL: `https://google.com`
   - Domain: Select `test-domain.com`
   - Count: `1`
2. Click **Generate Shortlinks**
3. Check output:
   ```
   https://xy7k2m.test-domain.com/abc123
   ```
4. Verify in database:
   ```sql
   SELECT subdomain, domain_id, use_global_domain
   FROM shortlinks
   WHERE slug = 'abc123';

   -- Result:
   -- subdomain: xy7k2m
   -- domain_id: 4 (test-domain.com)
   -- use_global_domain: 0
   ```

---

### Test 4: Auto-Refresh After Adding Domain

**Current Behavior:**
- Dropdown loads on page load only
- New domains require page refresh

**Enhanced Behavior (Optional):**
- Add **Refresh** button next to dropdown
- Or auto-refresh every 30 seconds
- Or WebSocket real-time sync

---

## 🔄 Real-Time Sync (Optional Enhancement)

### Option 1: Manual Refresh Button

**Add to form:**
```html
<div class="mb-3">
    <label for="domainSelection" class="form-label">
        Domain
        <button type="button" class="btn btn-sm btn-link" onclick="loadDomains()">
            <i class="bi bi-arrow-clockwise"></i> Refresh
        </button>
    </label>
    <select class="form-select" id="domainSelection" name="domain_selection">
        <!-- ... -->
    </select>
</div>
```

---

### Option 2: Auto-Refresh Every 30 Seconds

```javascript
// Auto-refresh domains every 30 seconds
setInterval(() => {
    console.log('🔄 Auto-refreshing domains...');

    // Clear existing options (except Global and separator)
    const select = document.getElementById('domainSelection');
    while (select.options.length > 2) {
        select.remove(2);
    }

    // Reload domains
    loadDomains();
}, 30000); // 30 seconds
```

---

### Option 3: WebSocket Real-Time (Advanced)

```javascript
// Connect to WebSocket server
const ws = new WebSocket('wss://your-domain.com/ws');

// Listen for domain updates
ws.addEventListener('message', (event) => {
    const data = JSON.parse(event.data);

    if (data.type === 'domain_added') {
        // Add new domain to dropdown
        const select = document.getElementById('domainSelection');
        const option = document.createElement('option');
        option.value = data.domain.id;
        option.textContent = data.domain.domain;
        select.appendChild(option);

        showToast(`✅ New domain added: ${data.domain.domain}`, 'success');
    }
});
```

---

## 🐛 Troubleshooting

### Issue 1: Dropdown Empty (Only Global Domain)

**Symptoms:**
```
🌐 Global Domain (Random)
──────────────────────
(no domains)
```

**Causes:**
1. No active domains in database
2. JavaScript error
3. AJAX request failed

**Solutions:**

#### A. Check Database
```sql
-- Count active domains
SELECT COUNT(*) FROM domains WHERE status = 'active';

-- If 0, add sample domain
INSERT INTO domains (domain, subdomain, document_root, status)
VALUES ('example.com', 'example', '../redirect', 'active');
```

#### B. Check Console
1. Open F12 Console
2. Look for errors:
   ```
   Failed to load domains: [error message]
   ```

#### C. Check Network Tab
1. Open F12 → Network tab
2. Reload page
3. Find request: `get-domains.php`
4. Check:
   - Status Code: Should be `200`
   - Response: Should be JSON with domains array

---

### Issue 2: New Domain Not Appearing

**Cause:** Page not refreshed after adding domain

**Solution:**
1. **Manual:** Refresh page (F5)
2. **Auto:** Add refresh button (see Option 1 above)
3. **Best:** Implement auto-refresh (see Option 2 above)

---

### Issue 3: "Failed to load domains" Error

**Symptoms:**
```
❌ Failed to load domains
```

**Debug Steps:**

1. **Check endpoint manually:**
   ```bash
   curl http://localhost/ajax/get-domains.php?status=active
   ```

2. **Check response:**
   ```json
   {
     "success": true,
     "data": {
       "domains": [...]
     }
   }
   ```

3. **Check path in code:**
   ```javascript
   // Current path
   '/ajax/get-domains.php'

   // If not working, try absolute path
   window.location.origin + '/ajax/get-domains.php'
   ```

4. **Check CORS (if frontend on different domain):**
   ```php
   // Add to get-domains.php
   header('Access-Control-Allow-Origin: *');
   ```

---

## 📊 Monitoring & Analytics

### Track Domain Usage

```sql
-- Count shortlinks per domain
SELECT
    d.domain,
    COUNT(s.id) as shortlink_count
FROM domains d
LEFT JOIN shortlinks s ON d.id = s.domain_id
GROUP BY d.id, d.domain
ORDER BY shortlink_count DESC;
```

**Example Output:**
```
domain          | shortlink_count
----------------|----------------
example.com     | 1250
example01.com   | 890
example02.com   | 650
example03.com   | 420
```

---

### Track Global vs Specific Selection

```sql
-- Count by domain selection type
SELECT
    CASE
        WHEN use_global_domain = 1 THEN 'Global (Random)'
        ELSE 'Specific Domain'
    END as selection_type,
    COUNT(*) as count
FROM shortlinks
GROUP BY use_global_domain;
```

**Example Output:**
```
selection_type      | count
--------------------|-------
Global (Random)     | 1580
Specific Domain     | 1630
```

---

## 🎨 UI Enhancements (Optional)

### Add Domain Icons

```html
<select class="form-select" id="domainSelection">
    <option value="global">🌐 Global Domain (Random)</option>
    <option disabled>──────────────────────</option>
    <option value="1">🔗 example.com</option>
    <option value="2">🔗 example01.com</option>
    <option value="3">🔗 example02.com</option>
</select>
```

---

### Add Domain Status Indicators

```javascript
result.data.domains.forEach(domain => {
    const option = document.createElement('option');
    option.value = domain.id;

    // Add status indicator
    const status = domain.status === 'active' ? '🟢' : '🔴';
    option.textContent = `${status} ${domain.domain}`;

    select.appendChild(option);
});
```

---

### Add Domain Tooltips

```html
<option value="1" title="Cloudflare enabled, SSL active">example.com</option>
<option value="2" title="Standard domain">example01.com</option>
```

---

## ✅ Summary

**Current Implementation:**

✅ **Auto-sync:** Domains added in Admin Dashboard automatically appear in User dropdown
✅ **Filter:** Only `active` domains shown
✅ **Real-time:** Load on page load
✅ **Error handling:** Shows error if AJAX fails
✅ **User-friendly:** Loading indicator and retry button

**Enhancement Options:**

⏳ Manual refresh button
⏳ Auto-refresh every 30s
⏳ WebSocket real-time sync
⏳ Domain status indicators
⏳ Usage statistics per domain

---

**Domain sync is working! Admin adds domain → User sees it immediately (after page load).**

**Last Updated:** 2025-12-26
