# 04 — Follow Up Boss Replacement (CRM)

## Context
Fogbreak replaces Follow Up Boss as the CRM. The existing `admin.php` has basic CRUD, `lead-scoring.js` has a scoring algorithm, and `drips.php` handles campaigns. This instruction upgrades the CRM to full FUB parity plus AI capabilities FUB doesn't have.

## What Follow Up Boss Does (Full Feature Set to Replicate)
- Smart lead routing (round-robin, by zip, by source, by price range)
- Lead scoring with behavioral signals
- Speed-to-lead automation (instant response to new leads)
- Action plans (multi-step follow-up sequences with calls, texts, emails)
- Smart lists (dynamic contact segments based on rules)
- Contact timeline (complete interaction history)
- Lead source tracking with ROI attribution
- Pond system (unresponsive leads go to shared pool for re-engagement)
- Team inbox (shared email/text conversations)
- Calling/texting from within platform
- Website visitor tracking (pixel-based lead identification)
- API for 200+ integrations
- Reporting (lead flow, conversion, response time)

## What Already Exists in Fogbreak
- `admin.php`: Client CRUD, phase tracking, interaction logging
- `lead-scoring.js`: 0-100 scoring algorithm
- `drips.php`: 4 campaign templates, enrollment, execution
- `email.php`: Full inbox, compose, Fair Housing audit
- `clients` table: Lifecycle tracking (lead → active → closed → repeat)

## What to Build

### 1. Smart Lead Routing
Add to `admin.php`:
```php
case 'route_lead':
    // Routing rules stored in DB, not code
    // Rules: round_robin, zip_code, price_range, lead_source, random, specific_agent
    // Each rule has priority, conditions (JSONB), and target agent(s)
    // Fall through rules until one matches
    // Log routing decision for attribution
```

Create `lead_routing_rules` table:
```sql
CREATE TABLE lead_routing_rules (
    id SERIAL PRIMARY KEY,
    tenant_id INT NOT NULL,
    name VARCHAR(255),
    priority INT DEFAULT 0,
    rule_type VARCHAR(30) CHECK (rule_type IN ('round_robin','zip_code','price_range','lead_source','property_type','random','specific_agent')),
    conditions JSONB NOT NULL DEFAULT '{}',
    target_agents JSONB NOT NULL DEFAULT '[]',
    is_active BOOLEAN DEFAULT TRUE,
    last_assigned_agent_id INT,
    created_at TIMESTAMPTZ DEFAULT NOW()
);
```

### 2. AI Lead Scoring (upgrade lead-scoring.js)
Replace the static algorithm with AI-powered scoring:
- Call `/api/ai.php?action=score_lead` with full lead context
- AI considers: interaction frequency, email engagement, property views, showing attendance, price range alignment, timeline urgency, behavioral signals
- Score recalculates on every interaction
- Add `lead_score_history` table to track score changes over time

### 3. Speed-to-Lead Automation
Add to `cron.php` or create real-time webhook handler:
- When new lead arrives: instantly trigger AI-generated personalized response
- Response sent via email or SMS within 60 seconds
- Personalized based on lead source, property interest, and market
- Auto-enroll in appropriate drip campaign
- Alert assigned agent via push notification

### 4. Action Plans (upgrade drips.php)
Extend drip campaigns into full action plans:
- Multi-channel steps: email, SMS, call reminder, task
- Branching logic: if client opens email → path A, if no open → path B
- AI-generated content per step (not static templates)
- Trigger-based enrollment: new lead, price reduction, listing match, inactivity

### 5. Smart Lists
Create dynamic contact segments:
```sql
CREATE TABLE smart_lists (
    id SERIAL PRIMARY KEY,
    tenant_id INT NOT NULL,
    name VARCHAR(255),
    rules JSONB NOT NULL,
    auto_refresh BOOLEAN DEFAULT TRUE,
    last_refreshed_at TIMESTAMPTZ,
    contact_count INT DEFAULT 0,
    created_at TIMESTAMPTZ DEFAULT NOW()
);
```
Rules are JSONB conditions: `{"field": "last_contact", "operator": "older_than", "value": "30d"}`

### 6. Lead Pond
Unresponsive leads after X days auto-move to shared pond:
- Any agent can claim leads from pond
- AI recommends which agents should get which pond leads based on expertise
- Pond leads get re-engagement drip campaign

### 7. Lead Source Tracking & ROI
Track every lead's original source through to closing:
- Source attribution on every contact
- Cost-per-lead by source
- Conversion rate by source
- Revenue attribution (commission tracked back to source)
- ROI dashboard per source

### 8. Contact Timeline Enhancement
Upgrade interaction logging to show EVERYTHING:
- Emails sent/received
- SMS sent/received
- Calls made (duration, outcome)
- Showings attended
- Properties viewed
- Documents signed
- Drip campaign steps delivered
- AI interactions
- Score changes

## Frontend Changes (fogbreak.html)
- Add smart routing config panel in Settings
- Add lead pond view
- Add smart lists sidebar
- Upgrade contact detail view with full timeline
- Add speed-to-lead response preview
- Add lead source ROI chart

## Acceptance Criteria
- [ ] Smart lead routing with configurable rules
- [ ] AI lead scoring replaces static algorithm
- [ ] Speed-to-lead: new leads get AI response within 60 seconds
- [ ] Action plans support multi-channel branching sequences
- [ ] Smart lists with dynamic rules and auto-refresh
- [ ] Lead pond system for re-engagement
- [ ] Full lead source tracking with ROI attribution
- [ ] Contact timeline shows every interaction across all channels
- [ ] All features are tenant-aware and market-aware
