1843:        case 'sync_thread':
1844-            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
1845-                jsonError('POST required', 405);
1846-            }
1847-
1848-            $contentType = $_SERVER['CONTENT_TYPE'] ?? '';
1849-            if (strpos($contentType, 'application/json') !== false) {
1850-                $jsonData = json_decode(file_get_contents('php://input'), true);
1851-                $threadId = $jsonData['thread_id'] ?? '';
1852-                $subject = $jsonData['subject'] ?? '';
1853-                $messageId = $jsonData['message_id'] ?? '';  / NEW: Accept message_id for reliable resolution
1854-            } else {
1855-                $threadId = $_POST['thread_id'] ?? '';
1856-                $subject = $_POST['subject'] ?? '';
1857-                $messageId = $_POST['message_id'] ?? '';
1858-            }
1859-
1860-            if (!$threadId && !$messageId) {
1861-                jsonError('thread_id or message_id required');
1862-            }
1863-
1864-            // Initialize thread ID cache
1865-            $threadCache = ThreadIdCache::getInstance();
1866-
1867-            // Store original URL-style thread ID for caching
1868-            $originalThreadId = $threadId;
1869-
1870-            / PRIORITY 0: Check cache for URL-style thread ID
1871-            if ($threadId && $threadCache->isUrlStyleThreadId($threadId)) {
1872-                $cachedId = $threadCache->get($threadId);
1873-                if ($cachedId) {

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.


545:    public function getThread(string $threadId): array
546-    {
547-        try {
548-            $service = $this->getService();
549-            $thread = $service->users_threads->get('me', $threadId, ['format' => 'full']);
550-
551-            $messages = [];
552-            foreach ($thread->getMessages() as $message) {
553-                $messages[] = $this->parseMessage($message);
554-            }
555-

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.


TodoWrite

Explore codebase for all 10 tasks

Design complete implementation plan

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.


Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable

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.


<ide_opened_file>The user opened the file /var/www/mssql.danmarcrm.com/dev1/extension2v1/src/QueryAdapter.php in the IDE. This may or may not be related to the current task.</ide_opened_file>

contacts tab not showing any contact and not returning any after search


Let me investigate the contacts API to see what's going wrong.


Bash

curl -s "https://mssql.danmarcrm.com/dev1/extension2v1/public/api.php?action=contacts&page=1&limit=10&sort=last_contact&order=DESC" 2>&1 | head -c 2000

Test contacts API endpoint


288 total contacts but empty array returned. The issue is likely in the `getContactsWithProfilesMongo()` method — the `last_contact` sort with the `$lookup` to emails is probably causing the pipeline to return empty results. Let me check.


Total is 288 but contacts array is empty. The issue is in the `last_contact` sort pipeline. Let me check:


curl -s "https://mssql.danmarcrm.com/dev1/extension2v1/public/api.php?action=contacts&page=1&limit=10&sort=name&order=ASC" 2>&1 | head -c 500

Test contacts with name sort (no lookup)


{
    "contacts": [
        {
            "_id": "6942810214400b3b979fe0fa",
            "email": "",
            "_created_at": "2025-12-17 10:08:02",
            "_migrated_at": "2025-12-17 12:08:30",
            "_source": "mysql_migration",
            "_updated_at": "2025-12-17 10:08:30",
            "company": null,
            "created_at": "2025-12-15 20:28:08",
            "first_contact": "2024-03-22 09:39:25",
            "gmail_account_id": null,
            "id": 55,
            "is


Name sort works fine. The problem is the `$lookup` pipeline for `last_contact` sort. Let me read the code I wrote:


   155→
   156→        if (!empty($filter)) {
   157→            $pipeline[] = ['$match' => $filter];
   158→        }
   159→
   160→        $pipeline[] = ['$lookup' => [
   161→            'from' => 'contact_profiles',
   162→            'localField' => 'id',
   163→            'foreignField' => 'contact_id',
   164→            'as' => 'profile'
   165→        ]];
   166→
   167→        $pipeline[] = ['$unwind' => [
   168→            'path' => '$profile',
   169→            'preserveNullAndEmptyArrays' => true
   170→        ]];
   171→
   172→        // For last_contact sort or date filters, lookup latest email date
   173→        if ($sortColumn === 'last_contact' || $dateFrom || $dateTo) {
   174→            $pipeline[] = ['$lookup' => [
   175→                'from' => 'emails',
   176→                'localField' => 'id',
   177→                'foreignField' => 'contact_id',
   178→                'pipeline' => [
   179→                    ['$group' => ['_id' => null, 'max_date' => ['$max' => '$date']]]
   180→                ],
   181→                'as' => 'email_stats'
   182→            ]];
   183→            $pipeline[] = ['$addFields' => [
   184→                'last_contact' => ['$ifNull' => [
   185→                    ['$arrayElemAt' => ['$email_stats.max_date', 0]],
   186→                    null
   187→                ]]
   188→            ]];
   189→            $pipeline[] = ['$project' => ['email_stats' => 0]];
   190→
   191→            // Apply date range filter on last_contact
   192→            if ($dateFrom || $dateTo) {
   193→                $dateFilter = [];
   194→                if ($dateFrom) $dateFilter['$gte'] = $dateFrom;
   195→                if ($dateTo) $dateFilter['$lte'] = $dateTo . ' 23:59:59';
   196→                $pipeline[] = ['$match' => ['last_contact' => $dateFilter]];
   197→            }
   198→        }
   199→

        if (!empty($filter)) {
            $pipeline[] = ['$match' => $filter];
        }

        $pipeline[] = ['$lookup' => [
            'from' => 'contact_profiles',
            'localField' => 'id',
            'foreignField' => 'contact_id',
            'as' => 'profile'
        ]];

        $pipeline[] = ['$unwind' => [
            'path' => '$profile',
            'preserveNullAndEmptyArrays' => true
        ]];

        // For last_contact sort or date filters, lookup latest email date
        if ($sortColumn === 'last_contact' || $dateFrom || $dateTo) {
            $pipeline[] = ['$lookup' => [
                'from' => 'emails',
                'localField' => 'id',
                'foreignField' => 'contact_id',
                'pipeline' => [
                    ['$group' => ['_id' => null, 'max_date' => ['$max' => '$date']]]
                ],
                'as' => 'email_stats'
            ]];
            $pipeline[] = ['$addFields' => [
                'last_contact' => ['$ifNull' => [
                    ['$arrayElemAt' => ['$email_stats.max_date', 0]],
                    null
                ]]
            ]];
            $pipeline[] = ['$project' => ['email_stats' => 0]];

            // Apply date range filter on last_contact
            if ($dateFrom || $dateTo) {
                $dateFilter = [];
                if ($dateFrom) $dateFilter['$gte'] = $dateFrom;
                if ($dateTo) $dateFilter['$lte'] = $dateTo . ' 23:59:59';
                $pipeline[] = ['$match' => ['last_contact' => $dateFilter]];
            }
        }


The issue is likely the `$lookup` with a sub-pipeline using `localField`/`foreignField` combined with `pipeline` — that's not valid syntax. When using a sub-pipeline, you need `let` + `$expr` instead. Also, contacts with no emails would get `null` for `last_contact` and sorting on `null` could push them all to one end. Let me fix this:


Edit

        // For last_contact sort or date filters, lookup latest email date
        if ($sortColumn === 'last_contact' || $dateFrom || $dateTo) {
            $pipeline[] = ['$lookup' => [
                'from' => 'emails',
                'localField' => 'id',
                'foreignField' => 'contact_id',
                'pipeline' => [
                    ['$group' => ['_id' => null, 'max_date' => ['$max' => '$date']]]
                ],
                'as' => 'email_stats'
            ]];
            $pipeline[] = ['$addFields' => [
                'last_contact' => ['$ifNull' => [
                    ['$arrayElemAt' => ['$email_stats.max_date', 0]],
                    null
                ]]
            ]];
            $pipeline[] = ['$project' => ['email_stats' => 0]];

            // Apply date range filter on last_contact
            if ($dateFrom || $dateTo) {
                $dateFilter = [];
                if ($dateFrom) $dateFilter['$gte'] = $dateFrom;
                if ($dateTo) $dateFilter['$lte'] = $dateTo . ' 23:59:59';
                $pipeline[] = ['$match' => ['last_contact' => $dateFilter]];
            }
        }

        // For last_contact sort or date filters, lookup latest email date
        if ($sortColumn === 'last_contact' || $dateFrom || $dateTo) {
            $pipeline[] = ['$lookup' => [
                'from' => 'emails',
                'let' => ['cid' => '$id'],
                'pipeline' => [
                    ['$match' => ['$expr' => ['$eq' => ['$contact_id', '$$cid']]]],
                    ['$group' => ['_id' => null, 'max_date' => ['$max' => '$date']]]
                ],
                'as' => 'email_stats'
            ]];
            $pipeline[] = ['$addFields' => [
                'last_contact' => ['$ifNull' => [
                    ['$arrayElemAt' => ['$email_stats.max_date', 0]],
                    '1970-01-01'
                ]]
            ]];
            $pipeline[] = ['$project' => ['email_stats' => 0]];

            // Apply date range filter on last_contact
            if ($dateFrom || $dateTo) {
                $dateFilter = [];
                if ($dateFrom) $dateFilter['$gte'] = $dateFrom;
                if ($dateTo) $dateFilter['$lte'] = $dateTo . ' 23:59:59';
                $pipeline[] = ['$match' => ['last_contact' => $dateFilter]];
            }
        }