19:use EmailIntelligence\Database;
37:    $db = Database::getInstance();
163:
164:

165:            <button class="tab-btn active" data-tab="contacts">Contacts</button>
166:            <button class="tab-btn" data-tab="emails">Threads</button>
167:            <button class="tab-btn" data-tab="products">🛒 Products</button>
168:            <button class="tab-btn" data-tab="gmail-accounts">📧 Gmail Accounts</button>
169:            <button class="tab-btn" data-tab="enrichment">🔬 Enrichment</button>
170:            <button class="tab-btn" data-tab="patterns">📊 Patterns</button>
171:            <button class="tab-btn" data-tab="business">💼 Business</button>
172:            <button class="tab-btn" data-tab="alerts">⚠ Alerts</button>
173:            <button class="tab-btn" data-tab="search">🔍 AI Search</button>
174:            <button class="tab-btn" data-tab="quotes">Quotes</button>
175:            <button class="tab-btn" data-tab="filters">Filters</button>
176:            <button class="tab-btn" data-tab="business-ideas">💡 Business Ideas</button>
179:
180:

197:
198:

209:
210:

213:
Search products from Amazon & AliExpress with advanced filters and AI recommendations

284:
285:

343:
344:

422:
423:

438:
439:

471:
472:

504:
505:

548:
549:

565:
566:

581:
582:

604:                            <input type="text" id="owner-growth-objectives" placeholder="e.g., Expand to new markets, diversify products" style="width: 100%; padding: 10px; border: 1px solid #d1d5db; border-radius: 6px; box-sizing: border-box;">
841:            // Set up tab switching
842:            document.querySelectorAll('.tab-btn').forEach(btn => {
844:                    switchTab(this.dataset.tab);

Prompt:
Design a detailed implementation plan for the following tasks in the Email Intelligence System at /var/www/mssql.danmarcrm.com/dev1/extension2v1/

## Context
This is a PHP/MongoDB web app with a dashboard (index.php + app.js), API (api.php), data layer (QueryAdapter.php), and a thread view page (thread_view.php). Chrome extension syncs Gmail threads. AI proxy at aiapi/api_opus/.

## Tasks (in priority order)

### TASK 1: Delete Functionality
Add ability to delete:
- **Contacts**: Already has a Delete button in dashboard UI. Need API endpoint `delete_contact` in api.php + QueryAdapter method. Must also delete associated emails, thread_analysis, contact_profiles, ai_contact_memory for that contact.
- **Email Threads**: Add delete button to threads list. API endpoint `delete_thread` + QueryAdapter. Must delete all emails with that thread_id, thread_analysis, ai_query_responses referencing that thread.
- **AI Responses**: Add delete button next to saved AI responses in thread_view.php. API endpoint `delete_ai_response`. Delete from ai_query_responses collection.

Files: api.php, QueryAdapter.php, app.js, index.php, thread_view.php

### TASK 2: Sorting by Last Activity
- Contacts list: Add sort by `last_contact` date (from contact profiles or max email date)
- Threads list: Add sort by `last_date` (already tracked in thread aggregation)
- Add sort dropdown/buttons in the UI for both tabs

Files: app.js, index.php, api.php (may need sort param support), QueryAdapter.php

### TASK 3: Filters
- **Contacts tab**: Add filters for contact type (client/supplier/other), search by name/email, last activity date range
- **Threads tab**: Add filters for contact name, date range, email count range, analysis status
- **Last Activity date filter**: Date range picker for both tabs
- Add filter UI section above each table

Files: app.js, index.php

### TASK 4: Fix "Etienne Turner" Thread Linkage
The contact name resolution was fixed in QueryAdapter.php but may still have issues:
- MongoDB `getThreadsMongo()` collects all_contacts, weights inbound 2x, picks most frequent
- But if contact_id is NULL or email matches user, it skips — edge case: if ALL emails in thread are from user (outbound only), falls back to first contact
- Need to verify the fix works and potentially handle edge cases

Files: QueryAdapter.php

### TASK 5: Sync by Domain/Email Address
New feature: Dashboard UI panel where user enters a domain (e.g. delta-engineering.be) or email address. System queries Gmail API to find all threads involving that domain/email, then imports them.

Implementation:
- New UI section in dashboard or modal
- New API endpoint `sync_by_domain` that:
  1. Uses GmailClient to search: `from:@domain.com OR to:@domain.com` (or specific email)
  2. Lists matching threads with preview (subject, date, count)
  3. User selects which to import (or "Import All")
  4. Imports selected threads using existing sync_thread logic
- Need two-step flow: search → preview → import

Files: api.php, index.php, app.js, GmailClient.php (may need search method)

### TASK 6: Bulk Delete Threads by Email Address
- Add ability to delete all threads for a specific email/domain
- UI: In contacts list or a cleanup tool
- API: `delete_threads_by_email` — finds all emails from that address, gets unique thread_ids, deletes all data

Files: api.php, QueryAdapter.php, app.js, index.php

### TASK 7: Chrome Extension Manual-Only Mode
- Add toggle in Chrome extension popup/options for "Auto-sync" vs "Manual sync only"
- In manual mode, show a "Sync this thread" button overlay in Gmail
- Store preference in chrome.storage.local
- Extension files are at /Users/dan/Documents/extension2/extension2v1/chrome-extension (local Mac) — we can only prepare the code changes

NOTE: Chrome extension is on user's local Mac, not this server. We should note what needs to change but can't edit those files directly.

### TASK 8: Two-Round AI D3.js Chart
- After Round 2 (or any AI response), add "Generate Chart" button
- AI generates structured JSON (entities, relationships, events)
- D3.js force-directed graph renders: nodes as balloons (color-coded by type), arrows showing relationships, labels
- Interactive: drag, zoom, pan, click for details

Files: thread_view.php (inline JS + D3.js CDN)

### TASK 9: Hide Products Tab
- Remove Products tab from navigation in index.php
- Keep product_search.php file intact

Files: index.php

### TASK 10: Update AI Model Versions
Update to latest models:
- Claude: Add `claude-opus-4-6`, `claude-sonnet-4-6` (current has claude-sonnet-4-5-20250929)
- Other providers: verify current versions

Files to update:
- /extension2v1/aiapi/api_opus/config/api_keys.php — provider models list + defaults
- /extension2v1/public/thread_view.php — MODEL_LIMITS constant
- /extension2v1/config/config.php — CLAUDE_MODEL constant
- Also check /extension2/aiapi/api_opus/config/api_keys.php

Current model config in api_keys.php uses arrays like:
```php
'claude' => [
    'default_model' => 'claude-sonnet-4-5-20250929',
    'models' => ['claude-sonnet-4-5-20250929', 'claude-3-5-sonnet-20241022', ...]
]
```

## Architecture Patterns to Follow
- Use `MongoDatabase::insertOrUpdate()` for upserts (NOT `upsert()`)
- Use `QueryAdapter` for all data access (NOT raw SQL)
- AI proxy models keyed by provider: `[$provider => $model]`
- MongoDB `delete()` method available on MongoDatabase class
- Node.js on server is v10.19 — can't use for JS syntax checks
- `ThreadAnalyzer::stripQuotedContent()` for email body processing

## Available MongoDB Methods (MongoDatabase.php)
- `insert($collection, $data)`
- `insertOrUpdate($collection, $filter, $data)`
- `update($collection, $filter, $data)`
- `delete($collection, $filter)`
- `findAll($collection, $filter, $options)`
- `findOne($collection, $filter)`
- `count($collection, $filter)`
- `aggregate($collection, $pipeline)`

## Existing API patterns
- JSON responses via `jsonResponse(['success' => true, ...])`
- Error handling via `jsonResponse(['success' => false, 'error' => '...'])`
- POST data via `$input = json_decode(file_get_contents('php://input'), true)`
- GET params via `$_GET['param']`

Please design a detailed, step-by-step plan with specific code changes needed for each task. Group related changes by file to minimize edits. Prioritize the tasks that are quickest wins first.


Prompt:
Design a detailed implementation plan for the following tasks in the Email Intelligence System at /var/www/mssql.danmarcrm.com/dev1/extension2v1/

## Context
This is a PHP/MongoDB web app with a dashboard (index.php + app.js), API (api.php), data layer (QueryAdapter.php), and a thread view page (thread_view.php). Chrome extension syncs Gmail threads. AI proxy at aiapi/api_opus/.

## Tasks (in priority order)

### TASK 1: Delete Functionality
Add ability to delete:
- **Contacts**: Already has a Delete button in dashboard UI. Need API endpoint `delete_contact` in api.php + QueryAdapter method. Must also delete associated emails, thread_analysis, contact_profiles, ai_contact_memory for that contact.
- **Email Threads**: Add delete button to threads list. API endpoint `delete_thread` + QueryAdapter. Must delete all emails with that thread_id, thread_analysis, ai_query_responses referencing that thread.
- **AI Responses**: Add delete button next to saved AI responses in thread_view.php. API endpoint `delete_ai_response`. Delete from ai_query_responses collection.

Files: api.php, QueryAdapter.php, app.js, index.php, thread_view.php

### TASK 2: Sorting by Last Activity
- Contacts list: Add sort by `last_contact` date (from contact profiles or max email date)
- Threads list: Add sort by `last_date` (already tracked in thread aggregation)
- Add sort dropdown/buttons in the UI for both tabs

Files: app.js, index.php, api.php (may need sort param support), QueryAdapter.php

### TASK 3: Filters
- **Contacts tab**: Add filters for contact type (client/supplier/other), search by name/email, last activity date range
- **Threads tab**: Add filters for contact name, date range, email count range, analysis status
- **Last Activity date filter**: Date range picker for both tabs
- Add filter UI section above each table

Files: app.js, index.php

### TASK 4: Fix "Etienne Turner" Thread Linkage
The contact name resolution was fixed in QueryAdapter.php but may still have issues:
- MongoDB `getThreadsMongo()` collects all_contacts, weights inbound 2x, picks most frequent
- But if contact_id is NULL or email matches user, it skips — edge case: if ALL emails in thread are from user (outbound only), falls back to first contact
- Need to verify the fix works and potentially handle edge cases

Files: QueryAdapter.php

### TASK 5: Sync by Domain/Email Address
New feature: Dashboard UI panel where user enters a domain (e.g. delta-engineering.be) or email address. System queries Gmail API to find all threads involving that domain/email, then imports them.

Implementation:
- New UI section in dashboard or modal
- New API endpoint `sync_by_domain` that:
  1. Uses GmailClient to search: `from:@domain.com OR to:@domain.com` (or specific email)
  2. Lists matching threads with preview (subject, date, count)
  3. User selects which to import (or "Import All")
  4. Imports selected threads using existing sync_thread logic
- Need two-step flow: search → preview → import

Files: api.php, index.php, app.js, GmailClient.php (may need search method)

### TASK 6: Bulk Delete Threads by Email Address
- Add ability to delete all threads for a specific email/domain
- UI: In contacts list or a cleanup tool
- API: `delete_threads_by_email` — finds all emails from that address, gets unique thread_ids, deletes all data

Files: api.php, QueryAdapter.php, app.js, index.php

### TASK 7: Chrome Extension Manual-Only Mode
- Add toggle in Chrome extension popup/options for "Auto-sync" vs "Manual sync only"
- In manual mode, show a "Sync this thread" button overlay in Gmail
- Store preference in chrome.storage.local
- Extension files are at /Users/dan/Documents/extension2/extension2v1/chrome-extension (local Mac) — we can only prepare the code changes

NOTE: Chrome extension is on user's local Mac, not this server. We should note what needs to change but can't edit those files directly.

### TASK 8: Two-Round AI D3.js Chart
- After Round 2 (or any AI response), add "Generate Chart" button
- AI generates structured JSON (entities, relationships, events)
- D3.js force-directed graph renders: nodes as balloons (color-coded by type), arrows showing relationships, labels
- Interactive: drag, zoom, pan, click for details

Files: thread_view.php (inline JS + D3.js CDN)

### TASK 9: Hide Products Tab
- Remove Products tab from navigation in index.php
- Keep product_search.php file intact

Files: index.php

### TASK 10: Update AI Model Versions
Update to latest models:
- Claude: Add `claude-opus-4-6`, `claude-sonnet-4-6` (current has claude-sonnet-4-5-20250929)
- Other providers: verify current versions

Files to update:
- /extension2v1/aiapi/api_opus/config/api_keys.php — provider models list + defaults
- /extension2v1/public/thread_view.php — MODEL_LIMITS constant
- /extension2v1/config/config.php — CLAUDE_MODEL constant
- Also check /extension2/aiapi/api_opus/config/api_keys.php

Current model config in api_keys.php uses arrays like:
```php
'claude' => [
    'default_model' => 'claude-sonnet-4-5-20250929',
    'models' => ['claude-sonnet-4-5-20250929', 'claude-3-5-sonnet-20241022', ...]
]
```

## Architecture Patterns to Follow
- Use `MongoDatabase::insertOrUpdate()` for upserts (NOT `upsert()`)
- Use `QueryAdapter` for all data access (NOT raw SQL)
- AI proxy models keyed by provider: `[$provider => $model]`
- MongoDB `delete()` method available on MongoDatabase class
- Node.js on server is v10.19 — can't use for JS syntax checks
- `ThreadAnalyzer::stripQuotedContent()` for email body processing

## Available MongoDB Methods (MongoDatabase.php)
- `insert($collection, $data)`
- `insertOrUpdate($collection, $filter, $data)`
- `update($collection, $filter, $data)`
- `delete($collection, $filter)`
- `findAll($collection, $filter, $options)`
- `findOne($collection, $filter)`
- `count($collection, $filter)`
- `aggregate($collection, $pipeline)`

## Existing API patterns
- JSON responses via `jsonResponse(['success' => true, ...])`
- Error handling via `jsonResponse(['success' => false, 'error' => '...'])`
- POST data via `$input = json_decode(file_get_contents('php://input'), true)`
- GET params via `$_GET['param']`

Please design a detailed, step-by-step plan with specific code changes needed for each task. Group related changes by file to minimize edits. Prioritize the tasks that are quickest wins first.


     1→/**
     2→ * Email Intelligence Dashboard JavaScript
     3→ *
     4→ * Handles all frontend interactions including:
     5→ * - Tab switching
     6→ * - Data loading via API
     7→ * - Modal management
     8→ * - Filter management
     9→ * - Sync/Analysis triggers
    10→ *
    11→ * CALLING MAP:
    12→ * - Loaded by: index.php
    13→ * - Calls: api.php for all data operations
    14→ *
    15→ * @package EmailIntelligence
    16→ */
    17→
    18→// ============================================
    19→// Global State
    20→// ============================================
    21→const state = {
    22→    contacts: {
    23→        page: 1,
    24→        search: '',
    25→        type: ''
    26→    },
    27→    emails: {
    28→        page: 1,
    29→        contactId: null
    30→    }
    31→};
    32→
    33→// ============================================
    34→// Utility Functions (defined early for global access)
    35→// ============================================
    36→/**
    37→ * Format number with commas
    38→ * Defined in global scope for early access
    39→ */
    40→window.formatNumber = function(num) {
    41→    if (num === null || num === undefined) return '0';
    42→    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    43→};
    44→
    45→// Also define as regular function for compatibility
    46→function formatNumber(num) {
    47→    if (num === null || num === undefined) return '0';
    48→    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    49→}
    50→
    51→/**
    52→ * Escape HTML to prevent XSS
    53→ */
    54→function escapeHtml(text) {
    55→    if (!text) return '';
    56→    const div = document.createElement('div');
    57→    div.textContent = text;
    58→    return div.innerHTML;
    59→}
    60→
    61→// ============================================
    62→// Tab Management
    63→// ============================================
    64→function switchTab(tabName) {
    65→    // Update tab buttons
    66→    document.querySelectorAll('.tab-btn').forEach(btn => {
    67→        btn.classList.toggle('active', btn.dataset.tab === tabName);
    68→    });
    69→
    70→    // Update tab content
    71→    document.querySelectorAll('.tab-content').forEach(content => {
    72→        content.classList.toggle('active', content.id === 'tab-' + tabName);
    73→    });
    74→
    75→    // Load data for the tab
    76→    switch(tabName) {
    77→        case 'contacts':
    78→            loadContacts();
    79→            break;
    80→        case 'emails':
    81→            loadEmails();
    82→            break;
    83→        case 'gmail-accounts':
    84→            loadGmailAccounts();
    85→            break;
    86→        case 'patterns':
    87→            loadPatternStats();
    88→            break;
    89→        case 'business':
    90→            loadBusinessOpportunities();
    91→            break;
    92→        case 'alerts':
    93→            loadAlerts();
    94→            break;
    95→        case 'quotes':
    96→            loadQuotes();
    97→            break;
    98→        case 'filters':
    99→            loadFilters();
   100→            break;

Prompt:
Design a detailed implementation plan for the following tasks in the Email Intelligence System at /var/www/mssql.danmarcrm.com/dev1/extension2v1/

## Context
This is a PHP/MongoDB web app with a dashboard (index.php + app.js), API (api.php), data layer (QueryAdapter.php), and a thread view page (thread_view.php). Chrome extension syncs Gmail threads. AI proxy at aiapi/api_opus/.

## Tasks (in priority order)

### TASK 1: Delete Functionality
Add ability to delete:
- **Contacts**: Already has a Delete button in dashboard UI. Need API endpoint `delete_contact` in api.php + QueryAdapter method. Must also delete associated emails, thread_analysis, contact_profiles, ai_contact_memory for that contact.
- **Email Threads**: Add delete button to threads list. API endpoint `delete_thread` + QueryAdapter. Must delete all emails with that thread_id, thread_analysis, ai_query_responses referencing that thread.
- **AI Responses**: Add delete button next to saved AI responses in thread_view.php. API endpoint `delete_ai_response`. Delete from ai_query_responses collection.

Files: api.php, QueryAdapter.php, app.js, index.php, thread_view.php

### TASK 2: Sorting by Last Activity
- Contacts list: Add sort by `last_contact` date (from contact profiles or max email date)
- Threads list: Add sort by `last_date` (already tracked in thread aggregation)
- Add sort dropdown/buttons in the UI for both tabs

Files: app.js, index.php, api.php (may need sort param support), QueryAdapter.php

### TASK 3: Filters
- **Contacts tab**: Add filters for contact type (client/supplier/other), search by name/email, last activity date range
- **Threads tab**: Add filters for contact name, date range, email count range, analysis status
- **Last Activity date filter**: Date range picker for both tabs
- Add filter UI section above each table

Files: app.js, index.php

### TASK 4: Fix "Etienne Turner" Thread Linkage
The contact name resolution was fixed in QueryAdapter.php but may still have issues:
- MongoDB `getThreadsMongo()` collects all_contacts, weights inbound 2x, picks most frequent
- But if contact_id is NULL or email matches user, it skips — edge case: if ALL emails in thread are from user (outbound only), falls back to first contact
- Need to verify the fix works and potentially handle edge cases

Files: QueryAdapter.php

### TASK 5: Sync by Domain/Email Address
New feature: Dashboard UI panel where user enters a domain (e.g. delta-engineering.be) or email address. System queries Gmail API to find all threads involving that domain/email, then imports them.

Implementation:
- New UI section in dashboard or modal
- New API endpoint `sync_by_domain` that:
  1. Uses GmailClient to search: `from:@domain.com OR to:@domain.com` (or specific email)
  2. Lists matching threads with preview (subject, date, count)
  3. User selects which to import (or "Import All")
  4. Imports selected threads using existing sync_thread logic
- Need two-step flow: search → preview → import

Files: api.php, index.php, app.js, GmailClient.php (may need search method)

### TASK 6: Bulk Delete Threads by Email Address
- Add ability to delete all threads for a specific email/domain
- UI: In contacts list or a cleanup tool
- API: `delete_threads_by_email` — finds all emails from that address, gets unique thread_ids, deletes all data

Files: api.php, QueryAdapter.php, app.js, index.php

### TASK 7: Chrome Extension Manual-Only Mode
- Add toggle in Chrome extension popup/options for "Auto-sync" vs "Manual sync only"
- In manual mode, show a "Sync this thread" button overlay in Gmail
- Store preference in chrome.storage.local
- Extension files are at /Users/dan/Documents/extension2/extension2v1/chrome-extension (local Mac) — we can only prepare the code changes

NOTE: Chrome extension is on user's local Mac, not this server. We should note what needs to change but can't edit those files directly.

### TASK 8: Two-Round AI D3.js Chart
- After Round 2 (or any AI response), add "Generate Chart" button
- AI generates structured JSON (entities, relationships, events)
- D3.js force-directed graph renders: nodes as balloons (color-coded by type), arrows showing relationships, labels
- Interactive: drag, zoom, pan, click for details

Files: thread_view.php (inline JS + D3.js CDN)

### TASK 9: Hide Products Tab
- Remove Products tab from navigation in index.php
- Keep product_search.php file intact

Files: index.php

### TASK 10: Update AI Model Versions
Update to latest models:
- Claude: Add `claude-opus-4-6`, `claude-sonnet-4-6` (current has claude-sonnet-4-5-20250929)
- Other providers: verify current versions

Files to update:
- /extension2v1/aiapi/api_opus/config/api_keys.php — provider models list + defaults
- /extension2v1/public/thread_view.php — MODEL_LIMITS constant
- /extension2v1/config/config.php — CLAUDE_MODEL constant
- Also check /extension2/aiapi/api_opus/config/api_keys.php

Current model config in api_keys.php uses arrays like:
```php
'claude' => [
    'default_model' => 'claude-sonnet-4-5-20250929',
    'models' => ['claude-sonnet-4-5-20250929', 'claude-3-5-sonnet-20241022', ...]
]
```

## Architecture Patterns to Follow
- Use `MongoDatabase::insertOrUpdate()` for upserts (NOT `upsert()`)
- Use `QueryAdapter` for all data access (NOT raw SQL)
- AI proxy models keyed by provider: `[$provider => $model]`
- MongoDB `delete()` method available on MongoDatabase class
- Node.js on server is v10.19 — can't use for JS syntax checks
- `ThreadAnalyzer::stripQuotedContent()` for email body processing

## Available MongoDB Methods (MongoDatabase.php)
- `insert($collection, $data)`
- `insertOrUpdate($collection, $filter, $data)`
- `update($collection, $filter, $data)`
- `delete($collection, $filter)`
- `findAll($collection, $filter, $options)`
- `findOne($collection, $filter)`
- `count($collection, $filter)`
- `aggregate($collection, $pipeline)`

## Existing API patterns
- JSON responses via `jsonResponse(['success' => true, ...])`
- Error handling via `jsonResponse(['success' => false, 'error' => '...'])`
- POST data via `$input = json_decode(file_get_contents('php://input'), true)`
- GET params via `$_GET['param']`

Please design a detailed, step-by-step plan with specific code changes needed for each task. Group related changes by file to minimize edits. Prioritize the tasks that are quickest wins first.


Prompt:
Design a detailed implementation plan for the following tasks in the Email Intelligence System at /var/www/mssql.danmarcrm.com/dev1/extension2v1/

## Context
This is a PHP/MongoDB web app with a dashboard (index.php + app.js), API (api.php), data layer (QueryAdapter.php), and a thread view page (thread_view.php). Chrome extension syncs Gmail threads. AI proxy at aiapi/api_opus/.

## Tasks (in priority order)

### TASK 1: Delete Functionality
Add ability to delete:
- **Contacts**: Already has a Delete button in dashboard UI. Need API endpoint `delete_contact` in api.php + QueryAdapter method. Must also delete associated emails, thread_analysis, contact_profiles, ai_contact_memory for that contact.
- **Email Threads**: Add delete button to threads list. API endpoint `delete_thread` + QueryAdapter. Must delete all emails with that thread_id, thread_analysis, ai_query_responses referencing that thread.
- **AI Responses**: Add delete button next to saved AI responses in thread_view.php. API endpoint `delete_ai_response`. Delete from ai_query_responses collection.

Files: api.php, QueryAdapter.php, app.js, index.php, thread_view.php

### TASK 2: Sorting by Last Activity
- Contacts list: Add sort by `last_contact` date (from contact profiles or max email date)
- Threads list: Add sort by `last_date` (already tracked in thread aggregation)
- Add sort dropdown/buttons in the UI for both tabs

Files: app.js, index.php, api.php (may need sort param support), QueryAdapter.php

### TASK 3: Filters
- **Contacts tab**: Add filters for contact type (client/supplier/other), search by name/email, last activity date range
- **Threads tab**: Add filters for contact name, date range, email count range, analysis status
- **Last Activity date filter**: Date range picker for both tabs
- Add filter UI section above each table

Files: app.js, index.php

### TASK 4: Fix "Etienne Turner" Thread Linkage
The contact name resolution was fixed in QueryAdapter.php but may still have issues:
- MongoDB `getThreadsMongo()` collects all_contacts, weights inbound 2x, picks most frequent
- But if contact_id is NULL or email matches user, it skips — edge case: if ALL emails in thread are from user (outbound only), falls back to first contact
- Need to verify the fix works and potentially handle edge cases

Files: QueryAdapter.php

### TASK 5: Sync by Domain/Email Address
New feature: Dashboard UI panel where user enters a domain (e.g. delta-engineering.be) or email address. System queries Gmail API to find all threads involving that domain/email, then imports them.

Implementation:
- New UI section in dashboard or modal
- New API endpoint `sync_by_domain` that:
  1. Uses GmailClient to search: `from:@domain.com OR to:@domain.com` (or specific email)
  2. Lists matching threads with preview (subject, date, count)
  3. User selects which to import (or "Import All")
  4. Imports selected threads using existing sync_thread logic
- Need two-step flow: search → preview → import

Files: api.php, index.php, app.js, GmailClient.php (may need search method)

### TASK 6: Bulk Delete Threads by Email Address
- Add ability to delete all threads for a specific email/domain
- UI: In contacts list or a cleanup tool
- API: `delete_threads_by_email` — finds all emails from that address, gets unique thread_ids, deletes all data

Files: api.php, QueryAdapter.php, app.js, index.php

### TASK 7: Chrome Extension Manual-Only Mode
- Add toggle in Chrome extension popup/options for "Auto-sync" vs "Manual sync only"
- In manual mode, show a "Sync this thread" button overlay in Gmail
- Store preference in chrome.storage.local
- Extension files are at /Users/dan/Documents/extension2/extension2v1/chrome-extension (local Mac) — we can only prepare the code changes

NOTE: Chrome extension is on user's local Mac, not this server. We should note what needs to change but can't edit those files directly.

### TASK 8: Two-Round AI D3.js Chart
- After Round 2 (or any AI response), add "Generate Chart" button
- AI generates structured JSON (entities, relationships, events)
- D3.js force-directed graph renders: nodes as balloons (color-coded by type), arrows showing relationships, labels
- Interactive: drag, zoom, pan, click for details

Files: thread_view.php (inline JS + D3.js CDN)

### TASK 9: Hide Products Tab
- Remove Products tab from navigation in index.php
- Keep product_search.php file intact

Files: index.php

### TASK 10: Update AI Model Versions
Update to latest models:
- Claude: Add `claude-opus-4-6`, `claude-sonnet-4-6` (current has claude-sonnet-4-5-20250929)
- Other providers: verify current versions

Files to update:
- /extension2v1/aiapi/api_opus/config/api_keys.php — provider models list + defaults
- /extension2v1/public/thread_view.php — MODEL_LIMITS constant
- /extension2v1/config/config.php — CLAUDE_MODEL constant
- Also check /extension2/aiapi/api_opus/config/api_keys.php

Current model config in api_keys.php uses arrays like:
```php
'claude' => [
    'default_model' => 'claude-sonnet-4-5-20250929',
    'models' => ['claude-sonnet-4-5-20250929', 'claude-3-5-sonnet-20241022', ...]
]
```

## Architecture Patterns to Follow
- Use `MongoDatabase::insertOrUpdate()` for upserts (NOT `upsert()`)
- Use `QueryAdapter` for all data access (NOT raw SQL)
- AI proxy models keyed by provider: `[$provider => $model]`
- MongoDB `delete()` method available on MongoDatabase class
- Node.js on server is v10.19 — can't use for JS syntax checks
- `ThreadAnalyzer::stripQuotedContent()` for email body processing

## Available MongoDB Methods (MongoDatabase.php)
- `insert($collection, $data)`
- `insertOrUpdate($collection, $filter, $data)`
- `update($collection, $filter, $data)`
- `delete($collection, $filter)`
- `findAll($collection, $filter, $options)`
- `findOne($collection, $filter)`
- `count($collection, $filter)`
- `aggregate($collection, $pipeline)`

## Existing API patterns
- JSON responses via `jsonResponse(['success' => true, ...])`
- Error handling via `jsonResponse(['success' => false, 'error' => '...'])`
- POST data via `$input = json_decode(file_get_contents('php://input'), true)`
- GET params via `$_GET['param']`

Please design a detailed, step-by-step plan with specific code changes needed for each task. Group related changes by file to minimize edits. Prioritize the tasks that are quickest wins first.


78:            loadContacts();
163:async function loadContacts(page = 1) {
230:        renderPagination('contacts-pagination', data.pagination, loadContacts);
1574:            searchTimeout = setTimeout(() => loadContacts(1), 300);
1580:        typeFilter.addEventListener('change', () => loadContacts(1));
2574:            setTimeout(() => loadContacts(state.contacts.page), 2000);
3642:                    ' <button onclick="deleteContactMemory(\'' + m.id + '\')" style="background:none;border:none;color:#f87171;cursor:pointer;font-size:1em;padding:0;line-height:1;">\u00D7</button>' +
3662:function deleteContactMemory(memoryId) {

Prompt:
Design a detailed implementation plan for the following tasks in the Email Intelligence System at /var/www/mssql.danmarcrm.com/dev1/extension2v1/

## Context
This is a PHP/MongoDB web app with a dashboard (index.php + app.js), API (api.php), data layer (QueryAdapter.php), and a thread view page (thread_view.php). Chrome extension syncs Gmail threads. AI proxy at aiapi/api_opus/.

## Tasks (in priority order)

### TASK 1: Delete Functionality
Add ability to delete:
- **Contacts**: Already has a Delete button in dashboard UI. Need API endpoint `delete_contact` in api.php + QueryAdapter method. Must also delete associated emails, thread_analysis, contact_profiles, ai_contact_memory for that contact.
- **Email Threads**: Add delete button to threads list. API endpoint `delete_thread` + QueryAdapter. Must delete all emails with that thread_id, thread_analysis, ai_query_responses referencing that thread.
- **AI Responses**: Add delete button next to saved AI responses in thread_view.php. API endpoint `delete_ai_response`. Delete from ai_query_responses collection.

Files: api.php, QueryAdapter.php, app.js, index.php, thread_view.php

### TASK 2: Sorting by Last Activity
- Contacts list: Add sort by `last_contact` date (from contact profiles or max email date)
- Threads list: Add sort by `last_date` (already tracked in thread aggregation)
- Add sort dropdown/buttons in the UI for both tabs

Files: app.js, index.php, api.php (may need sort param support), QueryAdapter.php

### TASK 3: Filters
- **Contacts tab**: Add filters for contact type (client/supplier/other), search by name/email, last activity date range
- **Threads tab**: Add filters for contact name, date range, email count range, analysis status
- **Last Activity date filter**: Date range picker for both tabs
- Add filter UI section above each table

Files: app.js, index.php

### TASK 4: Fix "Etienne Turner" Thread Linkage
The contact name resolution was fixed in QueryAdapter.php but may still have issues:
- MongoDB `getThreadsMongo()` collects all_contacts, weights inbound 2x, picks most frequent
- But if contact_id is NULL or email matches user, it skips — edge case: if ALL emails in thread are from user (outbound only), falls back to first contact
- Need to verify the fix works and potentially handle edge cases

Files: QueryAdapter.php

### TASK 5: Sync by Domain/Email Address
New feature: Dashboard UI panel where user enters a domain (e.g. delta-engineering.be) or email address. System queries Gmail API to find all threads involving that domain/email, then imports them.

Implementation:
- New UI section in dashboard or modal
- New API endpoint `sync_by_domain` that:
  1. Uses GmailClient to search: `from:@domain.com OR to:@domain.com` (or specific email)
  2. Lists matching threads with preview (subject, date, count)
  3. User selects which to import (or "Import All")
  4. Imports selected threads using existing sync_thread logic
- Need two-step flow: search → preview → import

Files: api.php, index.php, app.js, GmailClient.php (may need search method)

### TASK 6: Bulk Delete Threads by Email Address
- Add ability to delete all threads for a specific email/domain
- UI: In contacts list or a cleanup tool
- API: `delete_threads_by_email` — finds all emails from that address, gets unique thread_ids, deletes all data

Files: api.php, QueryAdapter.php, app.js, index.php

### TASK 7: Chrome Extension Manual-Only Mode
- Add toggle in Chrome extension popup/options for "Auto-sync" vs "Manual sync only"
- In manual mode, show a "Sync this thread" button overlay in Gmail
- Store preference in chrome.storage.local
- Extension files are at /Users/dan/Documents/extension2/extension2v1/chrome-extension (local Mac) — we can only prepare the code changes

NOTE: Chrome extension is on user's local Mac, not this server. We should note what needs to change but can't edit those files directly.

### TASK 8: Two-Round AI D3.js Chart
- After Round 2 (or any AI response), add "Generate Chart" button
- AI generates structured JSON (entities, relationships, events)
- D3.js force-directed graph renders: nodes as balloons (color-coded by type), arrows showing relationships, labels
- Interactive: drag, zoom, pan, click for details

Files: thread_view.php (inline JS + D3.js CDN)

### TASK 9: Hide Products Tab
- Remove Products tab from navigation in index.php
- Keep product_search.php file intact

Files: index.php

### TASK 10: Update AI Model Versions
Update to latest models:
- Claude: Add `claude-opus-4-6`, `claude-sonnet-4-6` (current has claude-sonnet-4-5-20250929)
- Other providers: verify current versions

Files to update:
- /extension2v1/aiapi/api_opus/config/api_keys.php — provider models list + defaults
- /extension2v1/public/thread_view.php — MODEL_LIMITS constant
- /extension2v1/config/config.php — CLAUDE_MODEL constant
- Also check /extension2/aiapi/api_opus/config/api_keys.php

Current model config in api_keys.php uses arrays like:
```php
'claude' => [
    'default_model' => 'claude-sonnet-4-5-20250929',
    'models' => ['claude-sonnet-4-5-20250929', 'claude-3-5-sonnet-20241022', ...]
]
```

## Architecture Patterns to Follow
- Use `MongoDatabase::insertOrUpdate()` for upserts (NOT `upsert()`)
- Use `QueryAdapter` for all data access (NOT raw SQL)
- AI proxy models keyed by provider: `[$provider => $model]`
- MongoDB `delete()` method available on MongoDatabase class
- Node.js on server is v10.19 — can't use for JS syntax checks
- `ThreadAnalyzer::stripQuotedContent()` for email body processing

## Available MongoDB Methods (MongoDatabase.php)
- `insert($collection, $data)`
- `insertOrUpdate($collection, $filter, $data)`
- `update($collection, $filter, $data)`
- `delete($collection, $filter)`
- `findAll($collection, $filter, $options)`
- `findOne($collection, $filter)`
- `count($collection, $filter)`
- `aggregate($collection, $pipeline)`

## Existing API patterns
- JSON responses via `jsonResponse(['success' => true, ...])`
- Error handling via `jsonResponse(['success' => false, 'error' => '...'])`
- POST data via `$input = json_decode(file_get_contents('php://input'), true)`
- GET params via `$_GET['param']`

Please design a detailed, step-by-step plan with specific code changes needed for each task. Group related changes by file to minimize edits. Prioritize the tasks that are quickest wins first.


Prompt:
Design a detailed implementation plan for the following tasks in the Email Intelligence System at /var/www/mssql.danmarcrm.com/dev1/extension2v1/

## Context
This is a PHP/MongoDB web app with a dashboard (index.php + app.js), API (api.php), data layer (QueryAdapter.php), and a thread view page (thread_view.php). Chrome extension syncs Gmail threads. AI proxy at aiapi/api_opus/.

## Tasks (in priority order)

### TASK 1: Delete Functionality
Add ability to delete:
- **Contacts**: Already has a Delete button in dashboard UI. Need API endpoint `delete_contact` in api.php + QueryAdapter method. Must also delete associated emails, thread_analysis, contact_profiles, ai_contact_memory for that contact.
- **Email Threads**: Add delete button to threads list. API endpoint `delete_thread` + QueryAdapter. Must delete all emails with that thread_id, thread_analysis, ai_query_responses referencing that thread.
- **AI Responses**: Add delete button next to saved AI responses in thread_view.php. API endpoint `delete_ai_response`. Delete from ai_query_responses collection.

Files: api.php, QueryAdapter.php, app.js, index.php, thread_view.php

### TASK 2: Sorting by Last Activity
- Contacts list: Add sort by `last_contact` date (from contact profiles or max email date)
- Threads list: Add sort by `last_date` (already tracked in thread aggregation)
- Add sort dropdown/buttons in the UI for both tabs

Files: app.js, index.php, api.php (may need sort param support), QueryAdapter.php

### TASK 3: Filters
- **Contacts tab**: Add filters for contact type (client/supplier/other), search by name/email, last activity date range
- **Threads tab**: Add filters for contact name, date range, email count range, analysis status
- **Last Activity date filter**: Date range picker for both tabs
- Add filter UI section above each table

Files: app.js, index.php

### TASK 4: Fix "Etienne Turner" Thread Linkage
The contact name resolution was fixed in QueryAdapter.php but may still have issues:
- MongoDB `getThreadsMongo()` collects all_contacts, weights inbound 2x, picks most frequent
- But if contact_id is NULL or email matches user, it skips — edge case: if ALL emails in thread are from user (outbound only), falls back to first contact
- Need to verify the fix works and potentially handle edge cases

Files: QueryAdapter.php

### TASK 5: Sync by Domain/Email Address
New feature: Dashboard UI panel where user enters a domain (e.g. delta-engineering.be) or email address. System queries Gmail API to find all threads involving that domain/email, then imports them.

Implementation:
- New UI section in dashboard or modal
- New API endpoint `sync_by_domain` that:
  1. Uses GmailClient to search: `from:@domain.com OR to:@domain.com` (or specific email)
  2. Lists matching threads with preview (subject, date, count)
  3. User selects which to import (or "Import All")
  4. Imports selected threads using existing sync_thread logic
- Need two-step flow: search → preview → import

Files: api.php, index.php, app.js, GmailClient.php (may need search method)

### TASK 6: Bulk Delete Threads by Email Address
- Add ability to delete all threads for a specific email/domain
- UI: In contacts list or a cleanup tool
- API: `delete_threads_by_email` — finds all emails from that address, gets unique thread_ids, deletes all data

Files: api.php, QueryAdapter.php, app.js, index.php

### TASK 7: Chrome Extension Manual-Only Mode
- Add toggle in Chrome extension popup/options for "Auto-sync" vs "Manual sync only"
- In manual mode, show a "Sync this thread" button overlay in Gmail
- Store preference in chrome.storage.local
- Extension files are at /Users/dan/Documents/extension2/extension2v1/chrome-extension (local Mac) — we can only prepare the code changes

NOTE: Chrome extension is on user's local Mac, not this server. We should note what needs to change but can't edit those files directly.

### TASK 8: Two-Round AI D3.js Chart
- After Round 2 (or any AI response), add "Generate Chart" button
- AI generates structured JSON (entities, relationships, events)
- D3.js force-directed graph renders: nodes as balloons (color-coded by type), arrows showing relationships, labels
- Interactive: drag, zoom, pan, click for details

Files: thread_view.php (inline JS + D3.js CDN)

### TASK 9: Hide Products Tab
- Remove Products tab from navigation in index.php
- Keep product_search.php file intact

Files: index.php

### TASK 10: Update AI Model Versions
Update to latest models:
- Claude: Add `claude-opus-4-6`, `claude-sonnet-4-6` (current has claude-sonnet-4-5-20250929)
- Other providers: verify current versions

Files to update:
- /extension2v1/aiapi/api_opus/config/api_keys.php — provider models list + defaults
- /extension2v1/public/thread_view.php — MODEL_LIMITS constant
- /extension2v1/config/config.php — CLAUDE_MODEL constant
- Also check /extension2/aiapi/api_opus/config/api_keys.php

Current model config in api_keys.php uses arrays like:
```php
'claude' => [
    'default_model' => 'claude-sonnet-4-5-20250929',
    'models' => ['claude-sonnet-4-5-20250929', 'claude-3-5-sonnet-20241022', ...]
]
```

## Architecture Patterns to Follow
- Use `MongoDatabase::insertOrUpdate()` for upserts (NOT `upsert()`)
- Use `QueryAdapter` for all data access (NOT raw SQL)
- AI proxy models keyed by provider: `[$provider => $model]`
- MongoDB `delete()` method available on MongoDatabase class
- Node.js on server is v10.19 — can't use for JS syntax checks
- `ThreadAnalyzer::stripQuotedContent()` for email body processing

## Available MongoDB Methods (MongoDatabase.php)
- `insert($collection, $data)`
- `insertOrUpdate($collection, $filter, $data)`
- `update($collection, $filter, $data)`
- `delete($collection, $filter)`
- `findAll($collection, $filter, $options)`
- `findOne($collection, $filter)`
- `count($collection, $filter)`
- `aggregate($collection, $pipeline)`

## Existing API patterns
- JSON responses via `jsonResponse(['success' => true, ...])`
- Error handling via `jsonResponse(['success' => false, 'error' => '...'])`
- POST data via `$input = json_decode(file_get_contents('php://input'), true)`
- GET params via `$_GET['param']`

Please design a detailed, step-by-step plan with specific code changes needed for each task. Group related changes by file to minimize edits. Prioritize the tasks that are quickest wins first.


163:async function loadContacts(page = 1) {
164-    const container = document.getElementById('contacts-list');
165-    container.innerHTML = '
Loading contacts...
';
166-
167-    try {
168-        state.contacts.page = page;
169-        state.contacts.search = document.getElementById('contact-search')?.value || '';
170-        state.contacts.type = document.getElementById('contact-type-filter')?.value || '';
171-
172-        const data = await apiCall('contacts', {
173-            page: page,
174-            search: state.contacts.search,
175-            type: state.contacts.type,
176-            limit: 10
177-        });
178-
179-        if (data.contacts.length === 0) {
180-            container.innerHTML = '
No contacts found
';
181-            return;
182-        }
183-
184-        let html = `
185-

186-

187-

188-                        Contact
189-                        Type
190-                        Emails
191-                        Relationship
192-                        Risk
193-                        Last Contact
194-                        Actions
195-

196-

197-

198-        `;
199-
200-        data.contacts.forEach(contact => {
201-            const riskClass = contact.risk_level ? 'badge-' + contact.risk_level : 'badge-low';
202-            const relClass = contact.relationship_health ? 'badge-' + contact.relationship_health.replace('_', '-') : 'badge-new';
203-            const enrichedBadge = contact.enrichment_status === 'complete' ? '✓' : '';
204-
205-            html += `
206-

207-
208-                        ${escapeHtml(contact.name || contact.email)} ${enrichedBadge}
209-                        ${contact.name ? '
' + escapeHtml(contact.email) + '' : ''}
210-                        ${contact.company ? '
' + escapeHtml(contact.company) + '' : ''}
211-
212-                    ${contact.type}
213-                    ${contact.total_emails || 0}
214-                    ${contact.relationship_health || 'new'}
215-                    ${contact.risk_level || 'low'}
216-                    ${contact.last_contact ? formatDate(contact.last_contact) : '-'}
217-
218-                        <button class="btn btn-sm btn-enrich" data-email="${escapeHtml(contact.email)}" data-contact-id="${contact.id}" onclick="event.stopPropagation(); enrichContactFromList(this);">
219-                            🔬 Enrich
220-                        </button>
221-
222-

223-            `;
224-        });
225-
226-        html += '

';
227-        container.innerHTML = html;
228-
229-        // Pagination
230-        renderPagination('contacts-pagination', data.pagination, loadContacts);
231-
232-    } catch (error) {
233-        container.innerHTML = '
Error loading contacts: ' + escapeHtml(error.message) + '
';
234-    }
235-}
236-
237-async function showContact(contactId) {
238-    showLoading('Loading contact...');
239-
240-    try {
241-        const data = await apiCall('contact', { id: contactId });
242-        const contact = data.contact;
243-

Prompt:
Design a detailed implementation plan for the following tasks in the Email Intelligence System at /var/www/mssql.danmarcrm.com/dev1/extension2v1/

## Context
This is a PHP/MongoDB web app with a dashboard (index.php + app.js), API (api.php), data layer (QueryAdapter.php), and a thread view page (thread_view.php). Chrome extension syncs Gmail threads. AI proxy at aiapi/api_opus/.

## Tasks (in priority order)

### TASK 1: Delete Functionality
Add ability to delete:
- **Contacts**: Already has a Delete button in dashboard UI. Need API endpoint `delete_contact` in api.php + QueryAdapter method. Must also delete associated emails, thread_analysis, contact_profiles, ai_contact_memory for that contact.
- **Email Threads**: Add delete button to threads list. API endpoint `delete_thread` + QueryAdapter. Must delete all emails with that thread_id, thread_analysis, ai_query_responses referencing that thread.
- **AI Responses**: Add delete button next to saved AI responses in thread_view.php. API endpoint `delete_ai_response`. Delete from ai_query_responses collection.

Files: api.php, QueryAdapter.php, app.js, index.php, thread_view.php

### TASK 2: Sorting by Last Activity
- Contacts list: Add sort by `last_contact` date (from contact profiles or max email date)
- Threads list: Add sort by `last_date` (already tracked in thread aggregation)
- Add sort dropdown/buttons in the UI for both tabs

Files: app.js, index.php, api.php (may need sort param support), QueryAdapter.php

### TASK 3: Filters
- **Contacts tab**: Add filters for contact type (client/supplier/other), search by name/email, last activity date range
- **Threads tab**: Add filters for contact name, date range, email count range, analysis status
- **Last Activity date filter**: Date range picker for both tabs
- Add filter UI section above each table

Files: app.js, index.php

### TASK 4: Fix "Etienne Turner" Thread Linkage
The contact name resolution was fixed in QueryAdapter.php but may still have issues:
- MongoDB `getThreadsMongo()` collects all_contacts, weights inbound 2x, picks most frequent
- But if contact_id is NULL or email matches user, it skips — edge case: if ALL emails in thread are from user (outbound only), falls back to first contact
- Need to verify the fix works and potentially handle edge cases

Files: QueryAdapter.php

### TASK 5: Sync by Domain/Email Address
New feature: Dashboard UI panel where user enters a domain (e.g. delta-engineering.be) or email address. System queries Gmail API to find all threads involving that domain/email, then imports them.

Implementation:
- New UI section in dashboard or modal
- New API endpoint `sync_by_domain` that:
  1. Uses GmailClient to search: `from:@domain.com OR to:@domain.com` (or specific email)
  2. Lists matching threads with preview (subject, date, count)
  3. User selects which to import (or "Import All")
  4. Imports selected threads using existing sync_thread logic
- Need two-step flow: search → preview → import

Files: api.php, index.php, app.js, GmailClient.php (may need search method)

### TASK 6: Bulk Delete Threads by Email Address
- Add ability to delete all threads for a specific email/domain
- UI: In contacts list or a cleanup tool
- API: `delete_threads_by_email` — finds all emails from that address, gets unique thread_ids, deletes all data

Files: api.php, QueryAdapter.php, app.js, index.php

### TASK 7: Chrome Extension Manual-Only Mode
- Add toggle in Chrome extension popup/options for "Auto-sync" vs "Manual sync only"
- In manual mode, show a "Sync this thread" button overlay in Gmail
- Store preference in chrome.storage.local
- Extension files are at /Users/dan/Documents/extension2/extension2v1/chrome-extension (local Mac) — we can only prepare the code changes

NOTE: Chrome extension is on user's local Mac, not this server. We should note what needs to change but can't edit those files directly.

### TASK 8: Two-Round AI D3.js Chart
- After Round 2 (or any AI response), add "Generate Chart" button
- AI generates structured JSON (entities, relationships, events)
- D3.js force-directed graph renders: nodes as balloons (color-coded by type), arrows showing relationships, labels
- Interactive: drag, zoom, pan, click for details

Files: thread_view.php (inline JS + D3.js CDN)

### TASK 9: Hide Products Tab
- Remove Products tab from navigation in index.php
- Keep product_search.php file intact

Files: index.php

### TASK 10: Update AI Model Versions
Update to latest models:
- Claude: Add `claude-opus-4-6`, `claude-sonnet-4-6` (current has claude-sonnet-4-5-20250929)
- Other providers: verify current versions

Files to update:
- /extension2v1/aiapi/api_opus/config/api_keys.php — provider models list + defaults
- /extension2v1/public/thread_view.php — MODEL_LIMITS constant
- /extension2v1/config/config.php — CLAUDE_MODEL constant
- Also check /extension2/aiapi/api_opus/config/api_keys.php

Current model config in api_keys.php uses arrays like:
```php
'claude' => [
    'default_model' => 'claude-sonnet-4-5-20250929',
    'models' => ['claude-sonnet-4-5-20250929', 'claude-3-5-sonnet-20241022', ...]
]
```

## Architecture Patterns to Follow
- Use `MongoDatabase::insertOrUpdate()` for upserts (NOT `upsert()`)
- Use `QueryAdapter` for all data access (NOT raw SQL)
- AI proxy models keyed by provider: `[$provider => $model]`
- MongoDB `delete()` method available on MongoDatabase class
- Node.js on server is v10.19 — can't use for JS syntax checks
- `ThreadAnalyzer::stripQuotedContent()` for email body processing

## Available MongoDB Methods (MongoDatabase.php)
- `insert($collection, $data)`
- `insertOrUpdate($collection, $filter, $data)`
- `update($collection, $filter, $data)`
- `delete($collection, $filter)`
- `findAll($collection, $filter, $options)`
- `findOne($collection, $filter)`
- `count($collection, $filter)`
- `aggregate($collection, $pipeline)`

## Existing API patterns
- JSON responses via `jsonResponse(['success' => true, ...])`
- Error handling via `jsonResponse(['success' => false, 'error' => '...'])`
- POST data via `$input = json_decode(file_get_contents('php://input'), true)`
- GET params via `$_GET['param']`

Please design a detailed, step-by-step plan with specific code changes needed for each task. Group related changes by file to minimize edits. Prioritize the tasks that are quickest wins first.


Prompt:
Design a detailed implementation plan for the following tasks in the Email Intelligence System at /var/www/mssql.danmarcrm.com/dev1/extension2v1/

## Context
This is a PHP/MongoDB web app with a dashboard (index.php + app.js), API (api.php), data layer (QueryAdapter.php), and a thread view page (thread_view.php). Chrome extension syncs Gmail threads. AI proxy at aiapi/api_opus/.

## Tasks (in priority order)

### TASK 1: Delete Functionality
Add ability to delete:
- **Contacts**: Already has a Delete button in dashboard UI. Need API endpoint `delete_contact` in api.php + QueryAdapter method. Must also delete associated emails, thread_analysis, contact_profiles, ai_contact_memory for that contact.
- **Email Threads**: Add delete button to threads list. API endpoint `delete_thread` + QueryAdapter. Must delete all emails with that thread_id, thread_analysis, ai_query_responses referencing that thread.
- **AI Responses**: Add delete button next to saved AI responses in thread_view.php. API endpoint `delete_ai_response`. Delete from ai_query_responses collection.

Files: api.php, QueryAdapter.php, app.js, index.php, thread_view.php

### TASK 2: Sorting by Last Activity
- Contacts list: Add sort by `last_contact` date (from contact profiles or max email date)
- Threads list: Add sort by `last_date` (already tracked in thread aggregation)
- Add sort dropdown/buttons in the UI for both tabs

Files: app.js, index.php, api.php (may need sort param support), QueryAdapter.php

### TASK 3: Filters
- **Contacts tab**: Add filters for contact type (client/supplier/other), search by name/email, last activity date range
- **Threads tab**: Add filters for contact name, date range, email count range, analysis status
- **Last Activity date filter**: Date range picker for both tabs
- Add filter UI section above each table

Files: app.js, index.php

### TASK 4: Fix "Etienne Turner" Thread Linkage
The contact name resolution was fixed in QueryAdapter.php but may still have issues:
- MongoDB `getThreadsMongo()` collects all_contacts, weights inbound 2x, picks most frequent
- But if contact_id is NULL or email matches user, it skips — edge case: if ALL emails in thread are from user (outbound only), falls back to first contact
- Need to verify the fix works and potentially handle edge cases

Files: QueryAdapter.php

### TASK 5: Sync by Domain/Email Address
New feature: Dashboard UI panel where user enters a domain (e.g. delta-engineering.be) or email address. System queries Gmail API to find all threads involving that domain/email, then imports them.

Implementation:
- New UI section in dashboard or modal
- New API endpoint `sync_by_domain` that:
  1. Uses GmailClient to search: `from:@domain.com OR to:@domain.com` (or specific email)
  2. Lists matching threads with preview (subject, date, count)
  3. User selects which to import (or "Import All")
  4. Imports selected threads using existing sync_thread logic
- Need two-step flow: search → preview → import

Files: api.php, index.php, app.js, GmailClient.php (may need search method)

### TASK 6: Bulk Delete Threads by Email Address
- Add ability to delete all threads for a specific email/domain
- UI: In contacts list or a cleanup tool
- API: `delete_threads_by_email` — finds all emails from that address, gets unique thread_ids, deletes all data

Files: api.php, QueryAdapter.php, app.js, index.php

### TASK 7: Chrome Extension Manual-Only Mode
- Add toggle in Chrome extension popup/options for "Auto-sync" vs "Manual sync only"
- In manual mode, show a "Sync this thread" button overlay in Gmail
- Store preference in chrome.storage.local
- Extension files are at /Users/dan/Documents/extension2/extension2v1/chrome-extension (local Mac) — we can only prepare the code changes

NOTE: Chrome extension is on user's local Mac, not this server. We should note what needs to change but can't edit those files directly.

### TASK 8: Two-Round AI D3.js Chart
- After Round 2 (or any AI response), add "Generate Chart" button
- AI generates structured JSON (entities, relationships, events)
- D3.js force-directed graph renders: nodes as balloons (color-coded by type), arrows showing relationships, labels
- Interactive: drag, zoom, pan, click for details

Files: thread_view.php (inline JS + D3.js CDN)

### TASK 9: Hide Products Tab
- Remove Products tab from navigation in index.php
- Keep product_search.php file intact

Files: index.php

### TASK 10: Update AI Model Versions
Update to latest models:
- Claude: Add `claude-opus-4-6`, `claude-sonnet-4-6` (current has claude-sonnet-4-5-20250929)
- Other providers: verify current versions

Files to update:
- /extension2v1/aiapi/api_opus/config/api_keys.php — provider models list + defaults
- /extension2v1/public/thread_view.php — MODEL_LIMITS constant
- /extension2v1/config/config.php — CLAUDE_MODEL constant
- Also check /extension2/aiapi/api_opus/config/api_keys.php

Current model config in api_keys.php uses arrays like:
```php
'claude' => [
    'default_model' => 'claude-sonnet-4-5-20250929',
    'models' => ['claude-sonnet-4-5-20250929', 'claude-3-5-sonnet-20241022', ...]
]
```

## Architecture Patterns to Follow
- Use `MongoDatabase::insertOrUpdate()` for upserts (NOT `upsert()`)
- Use `QueryAdapter` for all data access (NOT raw SQL)
- AI proxy models keyed by provider: `[$provider => $model]`
- MongoDB `delete()` method available on MongoDatabase class
- Node.js on server is v10.19 — can't use for JS syntax checks
- `ThreadAnalyzer::stripQuotedContent()` for email body processing

## Available MongoDB Methods (MongoDatabase.php)
- `insert($collection, $data)`
- `insertOrUpdate($collection, $filter, $data)`
- `update($collection, $filter, $data)`
- `delete($collection, $filter)`
- `findAll($collection, $filter, $options)`
- `findOne($collection, $filter)`
- `count($collection, $filter)`
- `aggregate($collection, $pipeline)`

## Existing API patterns
- JSON responses via `jsonResponse(['success' => true, ...])`
- Error handling via `jsonResponse(['success' => false, 'error' => '...'])`
- POST data via `$input = json_decode(file_get_contents('php://input'), true)`
- GET params via `$_GET['param']`

Please design a detailed, step-by-step plan with specific code changes needed for each task. Group related changes by file to minimize edits. Prioritize the tasks that are quickest wins first.


642:async function loadEmails(page = 1, contactId = null) {
643-    const container = document.getElementById('emails-list');
644-    container.innerHTML = '
Loading threads...
';
645-
646-    try {
647-        state.emails.page = page;
648-        if (contactId !== null) state.emails.contactId = contactId;
649-
650-        const params = { page: page, limit: 10 };
651-        if (state.emails.contactId) params.contact = state.emails.contactId;
652-
653-        const data = await apiCall('threads', params);
654-
655-        if (data.threads.length === 0) {
656-            container.innerHTML = '
No threads found
';
657-            return;
658-        }
659-
660-        let html = `
661-

662-                💡 Thread View: Each row is a complete conversation (all back-and-forth emails grouped together).
663-                Click to see what Claude will analyze.
664-

665-

666-

667-

668-                        Subject
669-                        Contact
670-                        Emails
671-                        Status
672-                        Last Activity
673-

674-

675-

676-        `;
677-
678-        data.threads.forEach(thread => {
679-            const statusBadge = thread.is_analyzed
680-                ? (thread.needs_reanalysis ? 'Needs Re-analysis' : 'Analyzed')
681-                : 'Not Analyzed';
682-
683-            const emailInfo = `${thread.email_count} (↓${thread.inbound_count} ↑${thread.outbound_count})`;
684-
685-            html += `
686-

687-
688-                        ${escapeHtml(thread.subject || '(No Subject)')}
689-
Started: ${formatDate(thread.first_date)}
690-
691-                    ${escapeHtml(thread.contact_name || 'Unknown')}
692-                    ${emailInfo}
693-                    ${statusBadge}
694-                    ${formatDate(thread.last_date)}
695-

696-            `;
697-        });
698-
699-        html += '

';
700-        container.innerHTML = html;
701-
702-        renderPagination('emails-pagination', data.pagination, (p) => loadEmails(p));
703-
704-    } catch (error) {
705-        container.innerHTML = '
Error loading threads: ' + escapeHtml(error.message) + '
';
706-    }
707-}
708-
709-async function showThread(threadId) {
710-    // Redirect to dedicated thread view page with AI capabilities
711-    window.location.href = 'thread_view.php?thread_id=' + encodeURIComponent(threadId);
712-}
713-
714-// Legacy modal-based thread view (kept for reference, no longer used)
715-async function showThreadModal(threadId) {
716-    showLoading('Loading thread...');
717-
718-    try {
719-        const data = await apiCall('thread', { thread_id: threadId });
720-
721-        let html = `
722-

Prompt:
Design a detailed implementation plan for the following tasks in the Email Intelligence System at /var/www/mssql.danmarcrm.com/dev1/extension2v1/

## Context
This is a PHP/MongoDB web app with a dashboard (index.php + app.js), API (api.php), data layer (QueryAdapter.php), and a thread view page (thread_view.php). Chrome extension syncs Gmail threads. AI proxy at aiapi/api_opus/.

## Tasks (in priority order)

### TASK 1: Delete Functionality
Add ability to delete:
- **Contacts**: Already has a Delete button in dashboard UI. Need API endpoint `delete_contact` in api.php + QueryAdapter method. Must also delete associated emails, thread_analysis, contact_profiles, ai_contact_memory for that contact.
- **Email Threads**: Add delete button to threads list. API endpoint `delete_thread` + QueryAdapter. Must delete all emails with that thread_id, thread_analysis, ai_query_responses referencing that thread.
- **AI Responses**: Add delete button next to saved AI responses in thread_view.php. API endpoint `delete_ai_response`. Delete from ai_query_responses collection.

Files: api.php, QueryAdapter.php, app.js, index.php, thread_view.php

### TASK 2: Sorting by Last Activity
- Contacts list: Add sort by `last_contact` date (from contact profiles or max email date)
- Threads list: Add sort by `last_date` (already tracked in thread aggregation)
- Add sort dropdown/buttons in the UI for both tabs

Files: app.js, index.php, api.php (may need sort param support), QueryAdapter.php

### TASK 3: Filters
- **Contacts tab**: Add filters for contact type (client/supplier/other), search by name/email, last activity date range
- **Threads tab**: Add filters for contact name, date range, email count range, analysis status
- **Last Activity date filter**: Date range picker for both tabs
- Add filter UI section above each table

Files: app.js, index.php

### TASK 4: Fix "Etienne Turner" Thread Linkage
The contact name resolution was fixed in QueryAdapter.php but may still have issues:
- MongoDB `getThreadsMongo()` collects all_contacts, weights inbound 2x, picks most frequent
- But if contact_id is NULL or email matches user, it skips — edge case: if ALL emails in thread are from user (outbound only), falls back to first contact
- Need to verify the fix works and potentially handle edge cases

Files: QueryAdapter.php

### TASK 5: Sync by Domain/Email Address
New feature: Dashboard UI panel where user enters a domain (e.g. delta-engineering.be) or email address. System queries Gmail API to find all threads involving that domain/email, then imports them.

Implementation:
- New UI section in dashboard or modal
- New API endpoint `sync_by_domain` that:
  1. Uses GmailClient to search: `from:@domain.com OR to:@domain.com` (or specific email)
  2. Lists matching threads with preview (subject, date, count)
  3. User selects which to import (or "Import All")
  4. Imports selected threads using existing sync_thread logic
- Need two-step flow: search → preview → import

Files: api.php, index.php, app.js, GmailClient.php (may need search method)

### TASK 6: Bulk Delete Threads by Email Address
- Add ability to delete all threads for a specific email/domain
- UI: In contacts list or a cleanup tool
- API: `delete_threads_by_email` — finds all emails from that address, gets unique thread_ids, deletes all data

Files: api.php, QueryAdapter.php, app.js, index.php

### TASK 7: Chrome Extension Manual-Only Mode
- Add toggle in Chrome extension popup/options for "Auto-sync" vs "Manual sync only"
- In manual mode, show a "Sync this thread" button overlay in Gmail
- Store preference in chrome.storage.local
- Extension files are at /Users/dan/Documents/extension2/extension2v1/chrome-extension (local Mac) — we can only prepare the code changes

NOTE: Chrome extension is on user's local Mac, not this server. We should note what needs to change but can't edit those files directly.

### TASK 8: Two-Round AI D3.js Chart
- After Round 2 (or any AI response), add "Generate Chart" button
- AI generates structured JSON (entities, relationships, events)
- D3.js force-directed graph renders: nodes as balloons (color-coded by type), arrows showing relationships, labels
- Interactive: drag, zoom, pan, click for details

Files: thread_view.php (inline JS + D3.js CDN)

### TASK 9: Hide Products Tab
- Remove Products tab from navigation in index.php
- Keep product_search.php file intact

Files: index.php

### TASK 10: Update AI Model Versions
Update to latest models:
- Claude: Add `claude-opus-4-6`, `claude-sonnet-4-6` (current has claude-sonnet-4-5-20250929)
- Other providers: verify current versions

Files to update:
- /extension2v1/aiapi/api_opus/config/api_keys.php — provider models list + defaults
- /extension2v1/public/thread_view.php — MODEL_LIMITS constant
- /extension2v1/config/config.php — CLAUDE_MODEL constant
- Also check /extension2/aiapi/api_opus/config/api_keys.php

Current model config in api_keys.php uses arrays like:
```php
'claude' => [
    'default_model' => 'claude-sonnet-4-5-20250929',
    'models' => ['claude-sonnet-4-5-20250929', 'claude-3-5-sonnet-20241022', ...]
]
```

## Architecture Patterns to Follow
- Use `MongoDatabase::insertOrUpdate()` for upserts (NOT `upsert()`)
- Use `QueryAdapter` for all data access (NOT raw SQL)
- AI proxy models keyed by provider: `[$provider => $model]`
- MongoDB `delete()` method available on MongoDatabase class
- Node.js on server is v10.19 — can't use for JS syntax checks
- `ThreadAnalyzer::stripQuotedContent()` for email body processing

## Available MongoDB Methods (MongoDatabase.php)
- `insert($collection, $data)`
- `insertOrUpdate($collection, $filter, $data)`
- `update($collection, $filter, $data)`
- `delete($collection, $filter)`
- `findAll($collection, $filter, $options)`
- `findOne($collection, $filter)`
- `count($collection, $filter)`
- `aggregate($collection, $pipeline)`

## Existing API patterns
- JSON responses via `jsonResponse(['success' => true, ...])`
- Error handling via `jsonResponse(['success' => false, 'error' => '...'])`
- POST data via `$input = json_decode(file_get_contents('php://input'), true)`
- GET params via `$_GET['param']`

Please design a detailed, step-by-step plan with specific code changes needed for each task. Group related changes by file to minimize edits. Prioritize the tasks that are quickest wins first.


Prompt:
Design a detailed implementation plan for the following tasks in the Email Intelligence System at /var/www/mssql.danmarcrm.com/dev1/extension2v1/

## Context
This is a PHP/MongoDB web app with a dashboard (index.php + app.js), API (api.php), data layer (QueryAdapter.php), and a thread view page (thread_view.php). Chrome extension syncs Gmail threads. AI proxy at aiapi/api_opus/.

## Tasks (in priority order)

### TASK 1: Delete Functionality
Add ability to delete:
- **Contacts**: Already has a Delete button in dashboard UI. Need API endpoint `delete_contact` in api.php + QueryAdapter method. Must also delete associated emails, thread_analysis, contact_profiles, ai_contact_memory for that contact.
- **Email Threads**: Add delete button to threads list. API endpoint `delete_thread` + QueryAdapter. Must delete all emails with that thread_id, thread_analysis, ai_query_responses referencing that thread.
- **AI Responses**: Add delete button next to saved AI responses in thread_view.php. API endpoint `delete_ai_response`. Delete from ai_query_responses collection.

Files: api.php, QueryAdapter.php, app.js, index.php, thread_view.php

### TASK 2: Sorting by Last Activity
- Contacts list: Add sort by `last_contact` date (from contact profiles or max email date)
- Threads list: Add sort by `last_date` (already tracked in thread aggregation)
- Add sort dropdown/buttons in the UI for both tabs

Files: app.js, index.php, api.php (may need sort param support), QueryAdapter.php

### TASK 3: Filters
- **Contacts tab**: Add filters for contact type (client/supplier/other), search by name/email, last activity date range
- **Threads tab**: Add filters for contact name, date range, email count range, analysis status
- **Last Activity date filter**: Date range picker for both tabs
- Add filter UI section above each table

Files: app.js, index.php

### TASK 4: Fix "Etienne Turner" Thread Linkage
The contact name resolution was fixed in QueryAdapter.php but may still have issues:
- MongoDB `getThreadsMongo()` collects all_contacts, weights inbound 2x, picks most frequent
- But if contact_id is NULL or email matches user, it skips — edge case: if ALL emails in thread are from user (outbound only), falls back to first contact
- Need to verify the fix works and potentially handle edge cases

Files: QueryAdapter.php

### TASK 5: Sync by Domain/Email Address
New feature: Dashboard UI panel where user enters a domain (e.g. delta-engineering.be) or email address. System queries Gmail API to find all threads involving that domain/email, then imports them.

Implementation:
- New UI section in dashboard or modal
- New API endpoint `sync_by_domain` that:
  1. Uses GmailClient to search: `from:@domain.com OR to:@domain.com` (or specific email)
  2. Lists matching threads with preview (subject, date, count)
  3. User selects which to import (or "Import All")
  4. Imports selected threads using existing sync_thread logic
- Need two-step flow: search → preview → import

Files: api.php, index.php, app.js, GmailClient.php (may need search method)

### TASK 6: Bulk Delete Threads by Email Address
- Add ability to delete all threads for a specific email/domain
- UI: In contacts list or a cleanup tool
- API: `delete_threads_by_email` — finds all emails from that address, gets unique thread_ids, deletes all data

Files: api.php, QueryAdapter.php, app.js, index.php

### TASK 7: Chrome Extension Manual-Only Mode
- Add toggle in Chrome extension popup/options for "Auto-sync" vs "Manual sync only"
- In manual mode, show a "Sync this thread" button overlay in Gmail
- Store preference in chrome.storage.local
- Extension files are at /Users/dan/Documents/extension2/extension2v1/chrome-extension (local Mac) — we can only prepare the code changes

NOTE: Chrome extension is on user's local Mac, not this server. We should note what needs to change but can't edit those files directly.

### TASK 8: Two-Round AI D3.js Chart
- After Round 2 (or any AI response), add "Generate Chart" button
- AI generates structured JSON (entities, relationships, events)
- D3.js force-directed graph renders: nodes as balloons (color-coded by type), arrows showing relationships, labels
- Interactive: drag, zoom, pan, click for details

Files: thread_view.php (inline JS + D3.js CDN)

### TASK 9: Hide Products Tab
- Remove Products tab from navigation in index.php
- Keep product_search.php file intact

Files: index.php

### TASK 10: Update AI Model Versions
Update to latest models:
- Claude: Add `claude-opus-4-6`, `claude-sonnet-4-6` (current has claude-sonnet-4-5-20250929)
- Other providers: verify current versions

Files to update:
- /extension2v1/aiapi/api_opus/config/api_keys.php — provider models list + defaults
- /extension2v1/public/thread_view.php — MODEL_LIMITS constant
- /extension2v1/config/config.php — CLAUDE_MODEL constant
- Also check /extension2/aiapi/api_opus/config/api_keys.php

Current model config in api_keys.php uses arrays like:
```php
'claude' => [
    'default_model' => 'claude-sonnet-4-5-20250929',
    'models' => ['claude-sonnet-4-5-20250929', 'claude-3-5-sonnet-20241022', ...]
]
```

## Architecture Patterns to Follow
- Use `MongoDatabase::insertOrUpdate()` for upserts (NOT `upsert()`)
- Use `QueryAdapter` for all data access (NOT raw SQL)
- AI proxy models keyed by provider: `[$provider => $model]`
- MongoDB `delete()` method available on MongoDatabase class
- Node.js on server is v10.19 — can't use for JS syntax checks
- `ThreadAnalyzer::stripQuotedContent()` for email body processing

## Available MongoDB Methods (MongoDatabase.php)
- `insert($collection, $data)`
- `insertOrUpdate($collection, $filter, $data)`
- `update($collection, $filter, $data)`
- `delete($collection, $filter)`
- `findAll($collection, $filter, $options)`
- `findOne($collection, $filter)`
- `count($collection, $filter)`
- `aggregate($collection, $pipeline)`

## Existing API patterns
- JSON responses via `jsonResponse(['success' => true, ...])`
- Error handling via `jsonResponse(['success' => false, 'error' => '...'])`
- POST data via `$input = json_decode(file_get_contents('php://input'), true)`
- GET params via `$_GET['param']`

Please design a detailed, step-by-step plan with specific code changes needed for each task. Group related changes by file to minimize edits. Prioritize the tasks that are quickest wins first.


294:        case 'contacts':
295-            $page = max(1, (int)($_GET['page'] ?? 1));
296-            $limit = min(100, max(1, (int)($_GET['limit'] ?? 20)));
297-            $offset = ($page - 1) * $limit;
298-            $search = $_GET['search'] ?? '';
299-            $sort = $_GET['sort'] ?? 'name';
300-            $order = strtoupper($_GET['order'] ?? 'DESC') === 'ASC' ? 'ASC' : 'DESC';
301-
302-            / Convert wildcards: * and % to regex-friendly for QueryAdapter
303-            $cleanSearch = $search;
304-            if ($cleanSearch) {
305-                // Strip wildcard chars — QueryAdapter already does LIKE %search% / regex
306-                $cleanSearch = str_replace(['*', '%'], '', $cleanSearch);
307-                $cleanSearch = trim($cleanSearch);
308-            }
309-
310-            // Use QueryAdapter for automatic MySQL/MongoDB routing
311-            $adapter = QueryAdapter::getInstance();
312-            $result = $adapter->getContactsWithProfiles($cleanSearch, $limit, $offset, $sort, $order);
313-
314-            jsonResponse([
315-                'contacts' => $result['contacts'] ?? [],
316-                'pagination' => [
317-                    'page' => $page,
318-                    'limit' => $limit,
319-                    'total' => (int)($result['total'] ?? 0),
320-                    'pages' => ceil(($result['total'] ?? 0) / $limit)
321-                ]
322-            ]);
323-            break;
324-
325-        // ==========================================
326-        // Single Contact with Full Profile
327-        // ==========================================
328-        case 'contact':
329-            $id = (int)($_GET['id'] ?? 0);
330-            if (!$id) jsonError('Contact ID required');
331-
332-            // Use QueryAdapter for automatic MySQL/MongoDB routing
333-            $adapter = QueryAdapter::getInstance();
334-            $data = $adapter->getContactWithDetails($id);

Prompt:
Design a detailed implementation plan for the following tasks in the Email Intelligence System at /var/www/mssql.danmarcrm.com/dev1/extension2v1/

## Context
This is a PHP/MongoDB web app with a dashboard (index.php + app.js), API (api.php), data layer (QueryAdapter.php), and a thread view page (thread_view.php). Chrome extension syncs Gmail threads. AI proxy at aiapi/api_opus/.

## Tasks (in priority order)

### TASK 1: Delete Functionality
Add ability to delete:
- **Contacts**: Already has a Delete button in dashboard UI. Need API endpoint `delete_contact` in api.php + QueryAdapter method. Must also delete associated emails, thread_analysis, contact_profiles, ai_contact_memory for that contact.
- **Email Threads**: Add delete button to threads list. API endpoint `delete_thread` + QueryAdapter. Must delete all emails with that thread_id, thread_analysis, ai_query_responses referencing that thread.
- **AI Responses**: Add delete button next to saved AI responses in thread_view.php. API endpoint `delete_ai_response`. Delete from ai_query_responses collection.

Files: api.php, QueryAdapter.php, app.js, index.php, thread_view.php

### TASK 2: Sorting by Last Activity
- Contacts list: Add sort by `last_contact` date (from contact profiles or max email date)
- Threads list: Add sort by `last_date` (already tracked in thread aggregation)
- Add sort dropdown/buttons in the UI for both tabs

Files: app.js, index.php, api.php (may need sort param support), QueryAdapter.php

### TASK 3: Filters
- **Contacts tab**: Add filters for contact type (client/supplier/other), search by name/email, last activity date range
- **Threads tab**: Add filters for contact name, date range, email count range, analysis status
- **Last Activity date filter**: Date range picker for both tabs
- Add filter UI section above each table

Files: app.js, index.php

### TASK 4: Fix "Etienne Turner" Thread Linkage
The contact name resolution was fixed in QueryAdapter.php but may still have issues:
- MongoDB `getThreadsMongo()` collects all_contacts, weights inbound 2x, picks most frequent
- But if contact_id is NULL or email matches user, it skips — edge case: if ALL emails in thread are from user (outbound only), falls back to first contact
- Need to verify the fix works and potentially handle edge cases

Files: QueryAdapter.php

### TASK 5: Sync by Domain/Email Address
New feature: Dashboard UI panel where user enters a domain (e.g. delta-engineering.be) or email address. System queries Gmail API to find all threads involving that domain/email, then imports them.

Implementation:
- New UI section in dashboard or modal
- New API endpoint `sync_by_domain` that:
  1. Uses GmailClient to search: `from:@domain.com OR to:@domain.com` (or specific email)
  2. Lists matching threads with preview (subject, date, count)
  3. User selects which to import (or "Import All")
  4. Imports selected threads using existing sync_thread logic
- Need two-step flow: search → preview → import

Files: api.php, index.php, app.js, GmailClient.php (may need search method)

### TASK 6: Bulk Delete Threads by Email Address
- Add ability to delete all threads for a specific email/domain
- UI: In contacts list or a cleanup tool
- API: `delete_threads_by_email` — finds all emails from that address, gets unique thread_ids, deletes all data

Files: api.php, QueryAdapter.php, app.js, index.php

### TASK 7: Chrome Extension Manual-Only Mode
- Add toggle in Chrome extension popup/options for "Auto-sync" vs "Manual sync only"
- In manual mode, show a "Sync this thread" button overlay in Gmail
- Store preference in chrome.storage.local
- Extension files are at /Users/dan/Documents/extension2/extension2v1/chrome-extension (local Mac) — we can only prepare the code changes

NOTE: Chrome extension is on user's local Mac, not this server. We should note what needs to change but can't edit those files directly.

### TASK 8: Two-Round AI D3.js Chart
- After Round 2 (or any AI response), add "Generate Chart" button
- AI generates structured JSON (entities, relationships, events)
- D3.js force-directed graph renders: nodes as balloons (color-coded by type), arrows showing relationships, labels
- Interactive: drag, zoom, pan, click for details

Files: thread_view.php (inline JS + D3.js CDN)

### TASK 9: Hide Products Tab
- Remove Products tab from navigation in index.php
- Keep product_search.php file intact

Files: index.php

### TASK 10: Update AI Model Versions
Update to latest models:
- Claude: Add `claude-opus-4-6`, `claude-sonnet-4-6` (current has claude-sonnet-4-5-20250929)
- Other providers: verify current versions

Files to update:
- /extension2v1/aiapi/api_opus/config/api_keys.php — provider models list + defaults
- /extension2v1/public/thread_view.php — MODEL_LIMITS constant
- /extension2v1/config/config.php — CLAUDE_MODEL constant
- Also check /extension2/aiapi/api_opus/config/api_keys.php

Current model config in api_keys.php uses arrays like:
```php
'claude' => [
    'default_model' => 'claude-sonnet-4-5-20250929',
    'models' => ['claude-sonnet-4-5-20250929', 'claude-3-5-sonnet-20241022', ...]
]
```

## Architecture Patterns to Follow
- Use `MongoDatabase::insertOrUpdate()` for upserts (NOT `upsert()`)
- Use `QueryAdapter` for all data access (NOT raw SQL)
- AI proxy models keyed by provider: `[$provider => $model]`
- MongoDB `delete()` method available on MongoDatabase class
- Node.js on server is v10.19 — can't use for JS syntax checks
- `ThreadAnalyzer::stripQuotedContent()` for email body processing

## Available MongoDB Methods (MongoDatabase.php)
- `insert($collection, $data)`
- `insertOrUpdate($collection, $filter, $data)`
- `update($collection, $filter, $data)`
- `delete($collection, $filter)`
- `findAll($collection, $filter, $options)`
- `findOne($collection, $filter)`
- `count($collection, $filter)`
- `aggregate($collection, $pipeline)`

## Existing API patterns
- JSON responses via `jsonResponse(['success' => true, ...])`
- Error handling via `jsonResponse(['success' => false, 'error' => '...'])`
- POST data via `$input = json_decode(file_get_contents('php://input'), true)`
- GET params via `$_GET['param']`

Please design a detailed, step-by-step plan with specific code changes needed for each task. Group related changes by file to minimize edits. Prioritize the tasks that are quickest wins first.


Prompt:
Design a detailed implementation plan for the following tasks in the Email Intelligence System at /var/www/mssql.danmarcrm.com/dev1/extension2v1/

## Context
This is a PHP/MongoDB web app with a dashboard (index.php + app.js), API (api.php), data layer (QueryAdapter.php), and a thread view page (thread_view.php). Chrome extension syncs Gmail threads. AI proxy at aiapi/api_opus/.

## Tasks (in priority order)

### TASK 1: Delete Functionality
Add ability to delete:
- **Contacts**: Already has a Delete button in dashboard UI. Need API endpoint `delete_contact` in api.php + QueryAdapter method. Must also delete associated emails, thread_analysis, contact_profiles, ai_contact_memory for that contact.
- **Email Threads**: Add delete button to threads list. API endpoint `delete_thread` + QueryAdapter. Must delete all emails with that thread_id, thread_analysis, ai_query_responses referencing that thread.
- **AI Responses**: Add delete button next to saved AI responses in thread_view.php. API endpoint `delete_ai_response`. Delete from ai_query_responses collection.

Files: api.php, QueryAdapter.php, app.js, index.php, thread_view.php

### TASK 2: Sorting by Last Activity
- Contacts list: Add sort by `last_contact` date (from contact profiles or max email date)
- Threads list: Add sort by `last_date` (already tracked in thread aggregation)
- Add sort dropdown/buttons in the UI for both tabs

Files: app.js, index.php, api.php (may need sort param support), QueryAdapter.php

### TASK 3: Filters
- **Contacts tab**: Add filters for contact type (client/supplier/other), search by name/email, last activity date range
- **Threads tab**: Add filters for contact name, date range, email count range, analysis status
- **Last Activity date filter**: Date range picker for both tabs
- Add filter UI section above each table

Files: app.js, index.php

### TASK 4: Fix "Etienne Turner" Thread Linkage
The contact name resolution was fixed in QueryAdapter.php but may still have issues:
- MongoDB `getThreadsMongo()` collects all_contacts, weights inbound 2x, picks most frequent
- But if contact_id is NULL or email matches user, it skips — edge case: if ALL emails in thread are from user (outbound only), falls back to first contact
- Need to verify the fix works and potentially handle edge cases

Files: QueryAdapter.php

### TASK 5: Sync by Domain/Email Address
New feature: Dashboard UI panel where user enters a domain (e.g. delta-engineering.be) or email address. System queries Gmail API to find all threads involving that domain/email, then imports them.

Implementation:
- New UI section in dashboard or modal
- New API endpoint `sync_by_domain` that:
  1. Uses GmailClient to search: `from:@domain.com OR to:@domain.com` (or specific email)
  2. Lists matching threads with preview (subject, date, count)
  3. User selects which to import (or "Import All")
  4. Imports selected threads using existing sync_thread logic
- Need two-step flow: search → preview → import

Files: api.php, index.php, app.js, GmailClient.php (may need search method)

### TASK 6: Bulk Delete Threads by Email Address
- Add ability to delete all threads for a specific email/domain
- UI: In contacts list or a cleanup tool
- API: `delete_threads_by_email` — finds all emails from that address, gets unique thread_ids, deletes all data

Files: api.php, QueryAdapter.php, app.js, index.php

### TASK 7: Chrome Extension Manual-Only Mode
- Add toggle in Chrome extension popup/options for "Auto-sync" vs "Manual sync only"
- In manual mode, show a "Sync this thread" button overlay in Gmail
- Store preference in chrome.storage.local
- Extension files are at /Users/dan/Documents/extension2/extension2v1/chrome-extension (local Mac) — we can only prepare the code changes

NOTE: Chrome extension is on user's local Mac, not this server. We should note what needs to change but can't edit those files directly.

### TASK 8: Two-Round AI D3.js Chart
- After Round 2 (or any AI response), add "Generate Chart" button
- AI generates structured JSON (entities, relationships, events)
- D3.js force-directed graph renders: nodes as balloons (color-coded by type), arrows showing relationships, labels
- Interactive: drag, zoom, pan, click for details

Files: thread_view.php (inline JS + D3.js CDN)

### TASK 9: Hide Products Tab
- Remove Products tab from navigation in index.php
- Keep product_search.php file intact

Files: index.php

### TASK 10: Update AI Model Versions
Update to latest models:
- Claude: Add `claude-opus-4-6`, `claude-sonnet-4-6` (current has claude-sonnet-4-5-20250929)
- Other providers: verify current versions

Files to update:
- /extension2v1/aiapi/api_opus/config/api_keys.php — provider models list + defaults
- /extension2v1/public/thread_view.php — MODEL_LIMITS constant
- /extension2v1/config/config.php — CLAUDE_MODEL constant
- Also check /extension2/aiapi/api_opus/config/api_keys.php

Current model config in api_keys.php uses arrays like:
```php
'claude' => [
    'default_model' => 'claude-sonnet-4-5-20250929',
    'models' => ['claude-sonnet-4-5-20250929', 'claude-3-5-sonnet-20241022', ...]
]
```

## Architecture Patterns to Follow
- Use `MongoDatabase::insertOrUpdate()` for upserts (NOT `upsert()`)
- Use `QueryAdapter` for all data access (NOT raw SQL)
- AI proxy models keyed by provider: `[$provider => $model]`
- MongoDB `delete()` method available on MongoDatabase class
- Node.js on server is v10.19 — can't use for JS syntax checks
- `ThreadAnalyzer::stripQuotedContent()` for email body processing

## Available MongoDB Methods (MongoDatabase.php)
- `insert($collection, $data)`
- `insertOrUpdate($collection, $filter, $data)`
- `update($collection, $filter, $data)`
- `delete($collection, $filter)`
- `findAll($collection, $filter, $options)`
- `findOne($collection, $filter)`
- `count($collection, $filter)`
- `aggregate($collection, $pipeline)`

## Existing API patterns
- JSON responses via `jsonResponse(['success' => true, ...])`
- Error handling via `jsonResponse(['success' => false, 'error' => '...'])`
- POST data via `$input = json_decode(file_get_contents('php://input'), true)`
- GET params via `$_GET['param']`

Please design a detailed, step-by-step plan with specific code changes needed for each task. Group related changes by file to minimize edits. Prioritize the tasks that are quickest wins first.


355:        case 'threads':
356-            $contactId = (int)($_GET['contact'] ?? 0);
357-            $search = trim($_GET['search'] ?? '');
358-            $page = max(1, (int)($_GET['page'] ?? 1));
359-            $limit = min(100, max(1, (int)($_GET['limit'] ?? 20)));
360-            $offset = ($page - 1) * $limit;
361-            $hasBusiness = isset($_GET['has_business']) && $_GET['has_business'];
362-
363-            // Use QueryAdapter for automatic MySQL/MongoDB routing
364-            $adapter = QueryAdapter::getInstance();
365-            $result = $adapter->getThreads(
366-                $contactId ?: null,
367-                $search,
368-                $limit,
369-                $offset
370-            );
371-
372-            / Note: has_business filtering is handled by frontend due to raw_analysis being stored as JSON string
373-            / Future: migrate raw_analysis to proper BSON objects for better querying
374-
375-            jsonResponse([
376-                'threads' => $result['threads'],
377-                'pagination' => [
378-                    'page' => $page,
379-                    'limit' => $limit,
380-                    'total' => $result['total'],
381-                    'pages' => ceil($result['total'] / $limit)
382-                ]
383-            ]);
384-            break;
385-
386-        // ==========================================
387-        // Single Thread with All Emails
388-        // ==========================================
389-        case 'thread':
390-            $threadId = $_GET['thread_id'] ?? '';
391-            if (!$threadId) jsonError('Thread ID required');
392-
393-            // Auto-resolve long URL thread ID to short hex ID from cache
394-            $threadId = resolveThreadId($threadId);
395-

Prompt:
Design a detailed implementation plan for the following tasks in the Email Intelligence System at /var/www/mssql.danmarcrm.com/dev1/extension2v1/

## Context
This is a PHP/MongoDB web app with a dashboard (index.php + app.js), API (api.php), data layer (QueryAdapter.php), and a thread view page (thread_view.php). Chrome extension syncs Gmail threads. AI proxy at aiapi/api_opus/.

## Tasks (in priority order)

### TASK 1: Delete Functionality
Add ability to delete:
- **Contacts**: Already has a Delete button in dashboard UI. Need API endpoint `delete_contact` in api.php + QueryAdapter method. Must also delete associated emails, thread_analysis, contact_profiles, ai_contact_memory for that contact.
- **Email Threads**: Add delete button to threads list. API endpoint `delete_thread` + QueryAdapter. Must delete all emails with that thread_id, thread_analysis, ai_query_responses referencing that thread.
- **AI Responses**: Add delete button next to saved AI responses in thread_view.php. API endpoint `delete_ai_response`. Delete from ai_query_responses collection.

Files: api.php, QueryAdapter.php, app.js, index.php, thread_view.php

### TASK 2: Sorting by Last Activity
- Contacts list: Add sort by `last_contact` date (from contact profiles or max email date)
- Threads list: Add sort by `last_date` (already tracked in thread aggregation)
- Add sort dropdown/buttons in the UI for both tabs

Files: app.js, index.php, api.php (may need sort param support), QueryAdapter.php

### TASK 3: Filters
- **Contacts tab**: Add filters for contact type (client/supplier/other), search by name/email, last activity date range
- **Threads tab**: Add filters for contact name, date range, email count range, analysis status
- **Last Activity date filter**: Date range picker for both tabs
- Add filter UI section above each table

Files: app.js, index.php

### TASK 4: Fix "Etienne Turner" Thread Linkage
The contact name resolution was fixed in QueryAdapter.php but may still have issues:
- MongoDB `getThreadsMongo()` collects all_contacts, weights inbound 2x, picks most frequent
- But if contact_id is NULL or email matches user, it skips — edge case: if ALL emails in thread are from user (outbound only), falls back to first contact
- Need to verify the fix works and potentially handle edge cases

Files: QueryAdapter.php

### TASK 5: Sync by Domain/Email Address
New feature: Dashboard UI panel where user enters a domain (e.g. delta-engineering.be) or email address. System queries Gmail API to find all threads involving that domain/email, then imports them.

Implementation:
- New UI section in dashboard or modal
- New API endpoint `sync_by_domain` that:
  1. Uses GmailClient to search: `from:@domain.com OR to:@domain.com` (or specific email)
  2. Lists matching threads with preview (subject, date, count)
  3. User selects which to import (or "Import All")
  4. Imports selected threads using existing sync_thread logic
- Need two-step flow: search → preview → import

Files: api.php, index.php, app.js, GmailClient.php (may need search method)

### TASK 6: Bulk Delete Threads by Email Address
- Add ability to delete all threads for a specific email/domain
- UI: In contacts list or a cleanup tool
- API: `delete_threads_by_email` — finds all emails from that address, gets unique thread_ids, deletes all data

Files: api.php, QueryAdapter.php, app.js, index.php

### TASK 7: Chrome Extension Manual-Only Mode
- Add toggle in Chrome extension popup/options for "Auto-sync" vs "Manual sync only"
- In manual mode, show a "Sync this thread" button overlay in Gmail
- Store preference in chrome.storage.local
- Extension files are at /Users/dan/Documents/extension2/extension2v1/chrome-extension (local Mac) — we can only prepare the code changes

NOTE: Chrome extension is on user's local Mac, not this server. We should note what needs to change but can't edit those files directly.

### TASK 8: Two-Round AI D3.js Chart
- After Round 2 (or any AI response), add "Generate Chart" button
- AI generates structured JSON (entities, relationships, events)
- D3.js force-directed graph renders: nodes as balloons (color-coded by type), arrows showing relationships, labels
- Interactive: drag, zoom, pan, click for details

Files: thread_view.php (inline JS + D3.js CDN)

### TASK 9: Hide Products Tab
- Remove Products tab from navigation in index.php
- Keep product_search.php file intact

Files: index.php

### TASK 10: Update AI Model Versions
Update to latest models:
- Claude: Add `claude-opus-4-6`, `claude-sonnet-4-6` (current has claude-sonnet-4-5-20250929)
- Other providers: verify current versions

Files to update:
- /extension2v1/aiapi/api_opus/config/api_keys.php — provider models list + defaults
- /extension2v1/public/thread_view.php — MODEL_LIMITS constant
- /extension2v1/config/config.php — CLAUDE_MODEL constant
- Also check /extension2/aiapi/api_opus/config/api_keys.php

Current model config in api_keys.php uses arrays like:
```php
'claude' => [
    'default_model' => 'claude-sonnet-4-5-20250929',
    'models' => ['claude-sonnet-4-5-20250929', 'claude-3-5-sonnet-20241022', ...]
]
```

## Architecture Patterns to Follow
- Use `MongoDatabase::insertOrUpdate()` for upserts (NOT `upsert()`)
- Use `QueryAdapter` for all data access (NOT raw SQL)
- AI proxy models keyed by provider: `[$provider => $model]`
- MongoDB `delete()` method available on MongoDatabase class
- Node.js on server is v10.19 — can't use for JS syntax checks
- `ThreadAnalyzer::stripQuotedContent()` for email body processing

## Available MongoDB Methods (MongoDatabase.php)
- `insert($collection, $data)`
- `insertOrUpdate($collection, $filter, $data)`
- `update($collection, $filter, $data)`
- `delete($collection, $filter)`
- `findAll($collection, $filter, $options)`
- `findOne($collection, $filter)`
- `count($collection, $filter)`
- `aggregate($collection, $pipeline)`

## Existing API patterns
- JSON responses via `jsonResponse(['success' => true, ...])`
- Error handling via `jsonResponse(['success' => false, 'error' => '...'])`
- POST data via `$input = json_decode(file_get_contents('php://input'), true)`
- GET params via `$_GET['param']`

Please design a detailed, step-by-step plan with specific code changes needed for each task. Group related changes by file to minimize edits. Prioritize the tasks that are quickest wins first.