# Client Intelligence - Integration Examples

## 3 Ways to Add "View Intelligence" Button to Your UI

### Option 1: Add to Dashboard Client Table (EASIEST)

**Location**: `templates/dashboard.html`, around line 1925

**Current code:**
```javascript
function populateTableClientRef(data) {
    const tbody = document.getElementById('tableBodyClientRef');
    
    if (data.length === 0) {
        tbody.innerHTML = '<tr><td colspan="6" style="text-align: center; padding: 30px;"><em>No data found</em></td></tr>';
        return;
    }
    
    tbody.innerHTML = data.map((row, index) => `
        <tr class="clickable-row" data-client="${escapeHtml(row.Cliente || '')}" data-index="${index}">
            <td>${escapeHtml(row.Cliente || '')}</td>
            <td><strong>${escapeHtml(row.Referencia || '')}</strong></td>
            <td>${escapeHtml(row.Código || '')}</td>
            <td>${escapeHtml(row.Familia || '')}</td>
            <td style="text-align: right; font-weight: bold; color: #667eea;">${parseInt(row.Quant || 0)}</td>
            <td style="text-align: right;">€ ${parseFloat(row.Faturaçao || 0).toFixed(2)}</td>
        </tr>
    `).join('');
    // ... rest of code
}
```

**Replace with:**
```javascript
function populateTableClientRef(data) {
    const tbody = document.getElementById('tableBodyClientRef');
    
    if (data.length === 0) {
        tbody.innerHTML = '<tr><td colspan="7" style="text-align: center; padding: 30px;"><em>No data found</em></td></tr>';
        return;
    }
    
    tbody.innerHTML = data.map((row, index) => `
        <tr class="clickable-row" data-client="${escapeHtml(row.Cliente || '')}" data-index="${index}">
            <td>${escapeHtml(row.Cliente || '')}</td>
            <td><strong>${escapeHtml(row.Referencia || '')}</strong></td>
            <td>${escapeHtml(row.Código || '')}</td>
            <td>${escapeHtml(row.Familia || '')}</td>
            <td style="text-align: right; font-weight: bold; color: #667eea;">${parseInt(row.Quant || 0)}</td>
            <td style="text-align: right;">€ ${parseFloat(row.Faturaçao || 0).toFixed(2)}</td>
            <td style="text-align: center;">
                <a href="/client-intelligence?cliente=${encodeURIComponent(row.Cliente)}" 
                   class="btn btn-sm btn-info" 
                   title="View Client Intelligence">
                    <i class="fas fa-chart-line"></i> Análise
                </a>
            </td>
        </tr>
    `).join('');
    // ... rest of code
}
```

**Also update table header** (search for `<thead>` in by-client-ref section):
```html
<tr>
    <th>Cliente</th>
    <th>Referencia</th>
    <th>Código</th>
    <th>Familia</th>
    <th>Quantity</th>
    <th>Faturação</th>
    <th>Ações</th>                  <!-- ADD THIS -->
</tr>
```

---

### Option 2: Add to Client Details Modal (ELEGANT)

**Location**: `templates/dashboard.html`, in the `openClientDetail` function around line 1975

**Find this section:**
```html
<div class="modal-header">
    <h5 class="modal-title" id="modalClientName">Client Details</h5>
    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
```

**Add buttons to modal footer. Search for existing modal footer or add:**
```html
<div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fechar</button>
    
    <!-- ADD THIS BUTTON -->
    <a href="#" id="intelligenceLink" class="btn btn-primary" target="_blank">
        <i class="fas fa-chart-line"></i> Ver Inteligência
    </a>
    
    <!-- Existing button if present -->
    <a href="#" id="detailsLink" class="btn btn-info">Ver Detalhes Completos</a>
</div>
```

**Then, in `openClientDetail` function, add:**
```javascript
function openClientDetail(clientName) {
    console.log('Opening detail for client:', clientName);
    
    // ... existing code ...
    
    // ADD THESE LINES (after modal title is set):
    const intelligenceLink = document.getElementById('intelligenceLink');
    if (intelligenceLink) {
        intelligenceLink.href = `/client-intelligence?cliente=${encodeURIComponent(clientName)}`;
    }
    
    // ... rest of existing code ...
}
```

---

### Option 3: Add Context Menu / Dropdown (ADVANCED)

**Location**: Create in dashboard.html script section

**Add this function:**
```javascript
function openClientMenu(clientName, event) {
    event.preventDefault();
    
    // Close any existing menu
    document.querySelectorAll('.client-menu').forEach(m => m.remove());
    
    const menu = document.createElement('div');
    menu.className = 'client-menu';
    menu.innerHTML = `
        <div style="position: fixed; top: ${event.pageY}px; left: ${event.pageX}px; 
                    background: white; border: 1px solid #ddd; border-radius: 4px; 
                    box-shadow: 0 2px 8px rgba(0,0,0,0.15); z-index: 1000; min-width: 200px;">
            <a href="/client-details?cliente=${encodeURIComponent(clientName)}" 
               style="display: block; padding: 10px 15px; text-decoration: none; color: #333; 
                      border-bottom: 1px solid #f0f0f0; hover: background: #f9f9f9;">
                <i class="fas fa-details"></i> Ver Detalhes
            </a>
            <a href="/client-intelligence?cliente=${encodeURIComponent(clientName)}" 
               style="display: block; padding: 10px 15px; text-decoration: none; color: #333; 
                      border-bottom: 1px solid #f0f0f0; hover: background: #f9f9f9;">
                <i class="fas fa-chart-line"></i> Inteligência
            </a>
            <a href="/visit-report?cliente=${encodeURIComponent(clientName)}" 
               style="display: block; padding: 10px 15px; text-decoration: none; color: #333;">
                <i class="fas fa-calendar"></i> Registar Visita
            </a>
        </div>
    `;
    
    document.body.appendChild(menu);
    
    // Close menu when clicking elsewhere
    setTimeout(() => {
        document.addEventListener('click', function closeMenu() {
            menu.remove();
            document.removeEventListener('click', closeMenu);
        });
    }, 100);
}
```

**Update row click handler:**
```javascript
document.querySelectorAll('#tableBodyClientRef .clickable-row').forEach(row => {
    row.addEventListener('contextmenu', function(e) {
        e.preventDefault();
        const clientName = this.getAttribute('data-client');
        openClientMenu(clientName, e);
    });
    
    // Keep existing click behavior
    row.addEventListener('click', function() {
        const clientName = this.getAttribute('data-client');
        console.log('Clicked client:', clientName);
        openClientDetail(clientName);
    });
});
```

---

## Quick Reference: HTML Button Examples

### Standalone Button
```html
<a href="/client-intelligence?cliente={{ client_name | urlencode }}" 
   class="btn btn-primary">
    <i class="fas fa-chart-line"></i> Ver Inteligência
</a>
```

### Button with Badge (showing new feature)
```html
<a href="/client-intelligence?cliente={{ client_name | urlencode }}" 
   class="btn btn-primary">
    <i class="fas fa-chart-line"></i> Inteligência
    <span class="badge badge-success">NOVO</span>
</a>
```

### Simple Link
```html
<a href="/client-intelligence?cliente={{ client_name | urlencode }}">
    📊 Analytics
</a>
```

### Icon Button (compact)
```html
<a href="/client-intelligence?cliente={{ client_name | urlencode }}" 
   class="btn btn-sm btn-info"
   title="View Client Intelligence">
    <i class="fas fa-chart-line"></i>
</a>
```

### Button with Dropdown
```html
<div class="dropdown">
    <button class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">
        {{ client_name }}
    </button>
    <ul class="dropdown-menu">
        <li>
            <a class="dropdown-item" href="/client-details?cliente={{ client_name | urlencode }}">
                <i class="fas fa-list"></i> Detalhes Completos
            </a>
        </li>
        <li>
            <a class="dropdown-item" href="/client-intelligence?cliente={{ client_name | urlencode }}">
                <i class="fas fa-chart-line"></i> Inteligência
            </a>
        </li>
        <li><hr class="dropdown-divider"></li>
        <li>
            <a class="dropdown-item" href="/visit-report?cliente={{ client_name | urlencode }}">
                <i class="fas fa-calendar-check"></i> Registar Visita
            </a>
        </li>
    </ul>
</div>
```

---

## JavaScript Code to Auto-Generate URL

If client names have special characters, use this helper:

```javascript
function getIntelligenceUrl(clientName) {
    return `/client-intelligence?cliente=${encodeURIComponent(clientName)}`;
}

// Usage:
const url = getIntelligenceUrl("José Silva");
// Returns: /client-intelligence?cliente=Jos%C3%A9%20Silva

// Then create link:
const link = document.createElement('a');
link.href = url;
link.textContent = 'View Intelligence';
link.className = 'btn btn-info';
```

---

## Testing Your Integration

After making changes:

1. **Save the file** (`templates/dashboard.html`)
2. **Refresh Flask** (press Ctrl+C and run `.\run_dev.ps1`)
3. **Load dashboard**: `http://localhost:5000/dashboard`
4. **Click your new button** → Should open Client Intelligence Panel
5. **Check**: Verify client name is loaded correctly

---

## Common Issues & Solutions

| Issue | Solution |
|-------|----------|
| Button appears but does nothing | Check browser console (F12) for JS errors |
| Character encoding issues | Use `encodeURIComponent()` in JavaScript or `\| urlencode` in Jinja2 |
| Link goes to wrong page | Verify route `/client-intelligence` exists in app.py |
| Access denied error | Check if user has permission for that client |
| Button not styling correctly | Add CSS classes: `btn btn-primary` |

---

## Styling Tips

### Match dashboard buttons
```html
<a href="/client-intelligence?cliente=..." 
   class="btn btn-sm btn-primary">
    <i class="fas fa-chart-line"></i> Intelligence
</a>
```

### Compact inline link
```html
<a href="/client-intelligence?cliente=..." 
   style="color: #667eea; text-decoration: none; font-weight: 600;">
    📊 Análise
</a>
```

### With hover effect
```css
.intelligence-link {
    display: inline-block;
    padding: 6px 12px;
    background: #f0f4ff;
    color: #667eea;
    border-radius: 4px;
    text-decoration: none;
    transition: all 0.3s;
}

.intelligence-link:hover {
    background: #667eea;
    color: white;
    transform: translateY(-2px);
}
```

---

## Mobile Responsive Button

```html
<a href="/client-intelligence?cliente=..." 
   class="btn btn-sm btn-info d-md-inline d-lg-inline">
    <i class="fas fa-chart-line d-none d-md-inline"></i>
    <span class="d-md-none">Análise</span>
    <span class="d-none d-md-inline">Ver Análise</span>
</a>
```

---

## Recommended: Option 1 (Dashboard Table)

**Why?** 
- ✅ Simplest to implement
- ✅ Most visible to users
- ✅ Works with existing table structure
- ✅ Easy to remove if needed

**Steps:**
1. Find `populateTableClientRef` function (line ~1925)
2. Add `, <th>Ações</th>` to table header
3. Add `, <td><a href="/client-intelligence?...">Análise</a></td>` to each row
4. Save and refresh

Done! 🎉
