# Quote & NDA Email and E-Signature Workflow

## Overview
This document describes the complete workflow for **Quote Approval** and **NDA Signature** processes, including email delivery, customer-facing signature pages, and integration with the Opportunities module.

---

## Table of Contents
1. [Quote Approval Workflow](#quote-approval-workflow)
2. [NDA Signature Workflow](#nda-signature-workflow)
3. [File Structure](#file-structure)
4. [Customization Guide](#customization-guide)
5. [Database Schema](#database-schema)
6. [API Endpoints](#api-endpoints)
7. [Security Features](#security-features)

---

## Quote Approval Workflow

### Process Flow

```
┌─────────────────┐
│ Create Quote    │
│ (Draft Status)  │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ Review Quote    │
│ Add Items/Terms │
└────────┬────────┘
         │
         ▼
┌─────────────────┐       ┌──────────────────────┐
│ Click "Email    │──────▶│ Modal Opens          │
│ Quote" Button   │       │ - Customer Email     │
└─────────────────┘       │ - Subject Line       │
                          │ - Pre-filled Message │
                          └──────────┬───────────┘
                                     │
                                     ▼
                          ┌──────────────────────┐
                          │ Server Generates:    │
                          │ - Public Token       │
                          │ - Signature Link     │
                          │ - Professional Email │
                          └──────────┬───────────┘
                                     │
                                     ▼
                          ┌──────────────────────┐
                          │ Email Sent via SMTP  │
                          │ Status: draft→sent   │
                          └──────────┬───────────┘
                                     │
                                     ▼
                          ┌──────────────────────┐
                          │ Customer Receives    │
                          │ Email with Link      │
                          └──────────┬───────────┘
                                     │
                   ┌─────────────────┴─────────────────┐
                   │                                   │
                   ▼                                   ▼
        ┌──────────────────┐              ┌──────────────────┐
        │ Customer Clicks  │              │ Ignores/Declines │
        │ "Review & Sign"  │              │ Email            │
        └────────┬─────────┘              └──────────────────┘
                 │
                 ▼
        ┌──────────────────┐
        │ Opens Public     │
        │ Signature Page   │
        │ (No Login)       │
        └────────┬─────────┘
                 │
                 ▼
        ┌──────────────────┐
        │ Reviews:         │
        │ - Quote Items    │
        │ - Pricing        │
        │ - Terms          │
        └────────┬─────────┘
                 │
       ┌─────────┴─────────┐
       │                   │
       ▼                   ▼
┌─────────────┐    ┌─────────────┐
│ Accept      │    │ Decline     │
│ - Fill info │    │ - Add reason│
│ - Sign      │    └─────┬───────┘
└──────┬──────┘          │
       │                 │
       ▼                 ▼
┌─────────────────────────────────┐
│ Status Updated in Database      │
│ - customer_response: accepted/  │
│   declined                      │
│ - Signature/decline details     │
│ - Auto-convert to Sales Order   │
│   (if enabled)                  │
└─────────────────────────────────┘
```

### Key Files

#### Backend Logic
| File | Purpose | Key Methods |
|------|---------|-------------|
| `controllers/QuoteController.php` | Quote management and email sending | `sendQuoteEmail()`, `publicView()`, `acceptQuote()`, `declineQuote()` |
| `models/Quote.php` | Quote database operations | `getById()`, `update()`, `getItems()` |
| `models/QuoteSignature.php` | Signature token management | `generatePublicToken()`, `validateQuoteForSignature()`, `recordAcceptance()` |
| `services/EmailService.php` | Email delivery service | `sendQuoteForApproval()`, `send()`, `getTemplate()` |

#### Frontend Views
| File | Purpose | Features |
|------|---------|----------|
| `views/quotes/general/show.php` | Internal quote detail page | Email modal with AJAX form submission |
| `views/quotes/signature/accept.php` | Customer-facing signature page | Quote review, signature canvas, accept/decline forms |
| `views/quotes/signature/error.php` | Error page for invalid tokens | Displays error messages |
| `views/quotes/signature/thank-you.php` | Confirmation page | Thank you message after acceptance |

#### Routes
```php
// Internal (requires auth)
POST /quotes/general/{id}/send-email        → QuoteController@sendQuoteEmail

// Public (no auth required)
GET  /quotes/accept/{token}                 → QuoteController@publicView
POST /quotes/accept/{token}/submit          → QuoteController@acceptQuote
POST /quotes/decline/{token}                → QuoteController@declineQuote
GET  /quotes/accept/{token}/thank-you       → QuoteController@thankYou
```

---

## NDA Signature Workflow

### Process Flow

```
┌─────────────────┐
│ Create          │
│ Opportunity     │
│ (CRM Module)    │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ Set NDA         │
│ Requirements:   │
│ - requires_nda  │
│ - block_quote   │
└────────┬────────┘
         │
         ▼
┌─────────────────┐       ┌──────────────────────┐
│ Navigate to     │──────▶│ Generate from        │
│ /ndas/create    │       │ Template:            │
└─────────────────┘       │ - Select opportunity │
                          │ - Choose template    │
                          │ - Merge fields       │
                          └──────────┬───────────┘
                                     │
                                     ▼
                          ┌──────────────────────┐
                          │ NDA Created          │
                          │ Status: draft        │
                          │ - Edit document      │
                          │ - Customize terms    │
                          └──────────┬───────────┘
                                     │
                                     ▼
                          ┌──────────────────────┐
                          │ Click "Email NDA"    │
                          │ - Enter email        │
                          │ - Customize message  │
                          └──────────┬───────────┘
                                     │
                                     ▼
                          ┌──────────────────────┐
                          │ Server Processes:    │
                          │ - Generate token     │
                          │ - Status: draft→sent │
                          │ - Opportunity status │
                          │   nda_status→sent    │
                          └──────────┬───────────┘
                                     │
                                     ▼
                          ┌──────────────────────┐
                          │ Email Sent           │
                          │ Professional template│
                          │ Legal document style │
                          └──────────┬───────────┘
                                     │
                                     ▼
                          ┌──────────────────────┐
                          │ Customer Receives    │
                          │ "NDA Signature       │
                          │ Required" Email      │
                          └──────────┬───────────┘
                                     │
                   ┌─────────────────┴─────────────────┐
                   │                                   │
                   ▼                                   ▼
        ┌──────────────────┐              ┌──────────────────┐
        │ Customer Clicks  │              │ Ignores Email    │
        │ "Review & Sign"  │              │ NDA Status:      │
        │                  │              │ - Expires after  │
        └────────┬─────────┘              │   90 days        │
                 │                        └──────────────────┘
                 ▼
        ┌──────────────────┐
        │ Opens NDA Page   │
        │ /ndas/sign/TOKEN │
        │ (No Login)       │
        └────────┬─────────┘
                 │
                 ▼
        ┌──────────────────┐
        │ Status: viewed   │
        │ Records:         │
        │ - View timestamp │
        └────────┬─────────┘
                 │
                 ▼
        ┌──────────────────┐
        │ Reads Full NDA:  │
        │ - Legal terms    │
        │ - Obligations    │
        │ - Duration       │
        │ - Scrollable doc │
        └────────┬─────────┘
                 │
       ┌─────────┴─────────┐
       │                   │
       ▼                   ▼
┌─────────────┐    ┌─────────────┐
│ Sign NDA    │    │ Decline NDA │
│ - Name      │    │ - Reason    │
│ - Email     │    └─────┬───────┘
│ - Title     │          │
│ - Company   │          │
│ - Signature │          │
│ - Agreement │          │
│   checkbox  │          │
└──────┬──────┘          │
       │                 │
       ▼                 ▼
┌─────────────────────────────────┐
│ Database Updates:               │
│                                 │
│ NDA Status:                     │
│ - signed or declined            │
│                                 │
│ Opportunity nda_status:         │
│ - signed or declined            │
│                                 │
│ Signature Record:               │
│ - Signature image (base64)      │
│ - Signer details                │
│ - IP address & user agent       │
│ - Timestamp                     │
│                                 │
│ Unblocks quote creation if      │
│ signed and was blocking         │
└─────────────────────────────────┘
```

### Key Files

#### Backend Logic
| File | Purpose | Key Methods |
|------|---------|-------------|
| `controllers/NDAController.php` | NDA management and email sending | `sendNDAEmail()`, `publicSign()`, `signNDA()`, `declineNDA()` |
| `models/NDA.php` | NDA database operations | `generateFromTemplate()`, `sendForSignature()`, `recordSignature()`, `validateForSignature()` |
| `models/Opportunity.php` | Opportunity integration | Links NDAs to sales opportunities |
| `services/EmailService.php` | Email delivery service | `sendNDAForSignature()`, `send()`, `getTemplate()` |

#### Frontend Views
| File | Purpose | Features |
|------|---------|----------|
| `views/ndas/signature/sign.php` | Customer-facing NDA signature page | Full document display, signature canvas, accept/decline forms |
| `views/ndas/signature/error.php` | Error page for invalid tokens | Displays error messages |

#### Routes
```php
// Internal (requires auth)
POST /ndas/{id}/send-email                  → NDAController@sendNDAEmail
GET  /ndas/{id}                             → NDAController@show
POST /ndas/generate                         → NDAController@generateFromTemplate

// Public (no auth required)
GET  /ndas/sign/{token}                     → NDAController@publicSign
POST /ndas/sign/{token}/submit              → NDAController@signNDA
POST /ndas/decline/{token}                  → NDAController@declineNDA

// API
GET  /api/opportunities/{id}/nda-status     → NDAController@checkStatus
```

---

## File Structure

### Complete File Map

```
m1_erp_web/
│
├── controllers/
│   ├── QuoteController.php          ← Quote email & acceptance logic
│   └── NDAController.php            ← NDA email & signature logic
│
├── models/
│   ├── Quote.php                    ← Quote database operations
│   ├── QuoteSignature.php           ← Quote signature & token management
│   ├── NDA.php                      ← NDA database operations
│   └── Opportunity.php              ← Links NDAs to opportunities
│
├── services/
│   └── EmailService.php             ← Centralized email service (SMTP/PHPMailer)
│                                       - sendQuoteForApproval()
│                                       - sendNDAForSignature()
│                                       - getTemplate() [email HTML]
│
├── views/
│   ├── quotes/
│   │   ├── general/
│   │   │   └── show.php             ← Internal quote page with email modal
│   │   └── signature/
│   │       ├── accept.php           ← 🌐 PUBLIC: Customer quote signature page
│   │       ├── error.php            ← Error page for invalid quote tokens
│   │       └── thank-you.php        ← Confirmation after quote acceptance
│   │
│   └── ndas/
│       └── signature/
│           ├── sign.php             ← 🌐 PUBLIC: Customer NDA signature page
│           └── error.php            ← Error page for invalid NDA tokens
│
├── public/
│   └── index.php                    ← Route definitions
│
└── database/
    └── migrations/
        ├── 024_quote_signatures.sql      ← Quote signature tables
        ├── 025_ndas.sql                  ← NDA tables
        └── 026_nda_signatures.sql        ← NDA signature tables
```

---

## Customization Guide

### 1. Branding & Styling

**Files to Edit for Consistent Branding:**

#### Quote Acceptance Page
**File:** `views/quotes/signature/accept.php`
- **Lines 9-174:** All CSS styles
- **Key Elements:**
  - Line 10: Background gradient color
  - Lines 25-26: Header gradient
  - Lines 64-67: Total amount text color
  - Lines 114-127: Button colors (success, danger)
  
**Customization Example:**
```css
/* Change from purple gradient to your brand colors */
body {
    background: linear-gradient(135deg, #YOUR_COLOR_1 0%, #YOUR_COLOR_2 100%);
}
```

#### NDA Signature Page
**File:** `views/ndas/signature/sign.php`
- **Lines 8-172:** All CSS styles
- **Same structure as quote page**
- Match colors to quote page for consistency

#### Email Templates
**File:** `services/EmailService.php`

**Common Email Wrapper** (Lines 149-186):
```php
$header = "
    <!DOCTYPE html>
    <html>
    <head>
        <style>
            /* Line 155: Body font and colors */
            body { font-family: Arial, sans-serif; }
            
            /* Line 157: Header background - CUSTOMIZE THIS */
            .header { background: #2c3e50; color: white; }
            
            /* Line 163: Button style - CUSTOMIZE THIS */
            .button { background: #3498db; color: white; }
        </style>
    </head>
```

**Quote Email Template** (Lines 270-289):
- Customize message text
- Adjust button text
- Modify layout

**NDA Email Template** (Lines 291-311):
- Legal-focused language
- Warning styling
- Professional tone

### 2. Company Information

**File:** `services/EmailService.php`

**Lines 21-22:**
```php
$this->from = $this->getSetting('company_email', 'erp_system@mavrix.one');
$this->fromName = $this->getSetting('company_name', 'Mavrix1');
```

These pull from `system_settings` table or use defaults.

**Update in Database:**
```sql
UPDATE system_settings 
SET setting_value = 'your-email@company.com' 
WHERE setting_key = 'company_email';

UPDATE system_settings 
SET setting_value = 'Your Company Name' 
WHERE setting_key = 'company_name';
```

### 3. Email Content Customization

**Quote Approval Email:**
```php
// File: services/EmailService.php, Line 272
$content = "
    <h2>Hello {$recipient_name},</h2>
    <p>We're pleased to share Quote <strong>{$quote_number}</strong>...</p>
    
    <!-- CUSTOMIZE THIS MESSAGE -->
    
    <p>Best regards,<br>{$sender_name}</p>
";
```

**NDA Signature Email:**
```php
// File: services/EmailService.php, Line 292
$content = "
    <h2>Hello {$recipient_name},</h2>
    <p>We are working together on the opportunity: <strong>{$opportunity_name}</strong>.</p>
    
    <!-- CUSTOMIZE THIS MESSAGE -->
    
    <p class='warning'>This is a legally binding agreement...</p>
";
```

### 4. Page Headers & Titles

**Quote Page:**
```php
// File: views/quotes/signature/accept.php, Line 179
<h1>📋 Quote Review & Acceptance</h1>
```

**NDA Page:**
```php
// File: views/ndas/signature/sign.php, Line 177
<h1>📜 Non-Disclosure Agreement</h1>
```

### 5. Adding Company Logo

**In Email Template** (`services/EmailService.php`):
```php
// Line ~172, add to header
<div class='header'>
    <img src='https://yoursite.com/logo.png' alt='Company Logo' style='max-height: 50px;'>
    <h1>{$company_name}</h1>
</div>
```

**In Signature Pages:**
```php
// Add to quote/NDA signature pages after line 177
<img src="<?= base_url('assets/images/logo.png') ?>" style="max-height: 60px; margin-bottom: 10px;">
```

---

## Database Schema

### Quote Signature Tables

#### `quotes` Table Extensions
```sql
ALTER TABLE quotes ADD COLUMN public_token VARCHAR(64) NULL;
ALTER TABLE quotes ADD COLUMN token_expires_at DATETIME NULL;
ALTER TABLE quotes ADD COLUMN customer_response ENUM('accepted', 'declined') NULL;
ALTER TABLE quotes ADD COLUMN accepted_at DATETIME NULL;
ALTER TABLE quotes ADD COLUMN accepted_by_name VARCHAR(255) NULL;
ALTER TABLE quotes ADD COLUMN accepted_by_email VARCHAR(255) NULL;
ALTER TABLE quotes ADD COLUMN declined_at DATETIME NULL;
ALTER TABLE quotes ADD COLUMN declined_by_name VARCHAR(255) NULL;
ALTER TABLE quotes ADD COLUMN declined_by_email VARCHAR(255) NULL;
ALTER TABLE quotes ADD COLUMN declined_reason TEXT NULL;
```

#### `quote_signatures` Table
```sql
CREATE TABLE quote_signatures (
    id INT AUTO_INCREMENT PRIMARY KEY,
    quote_id INT NOT NULL,
    signature_data TEXT NOT NULL,        -- Base64 image
    accepted_by_name VARCHAR(255) NOT NULL,
    accepted_by_email VARCHAR(255) NOT NULL,
    accepted_by_title VARCHAR(255) NULL,
    company_name VARCHAR(255) NULL,
    signed_at DATETIME NOT NULL,
    ip_address VARCHAR(45) NULL,
    user_agent TEXT NULL,
    FOREIGN KEY (quote_id) REFERENCES quotes(id)
);
```

### NDA Tables

#### `ndas` Table
```sql
CREATE TABLE ndas (
    id INT AUTO_INCREMENT PRIMARY KEY,
    nda_number VARCHAR(50) UNIQUE NOT NULL,
    opportunity_id INT NULL,
    template_id INT NULL,
    nda_type ENUM('unilateral', 'bilateral', 'multilateral'),
    company_name VARCHAR(255) NOT NULL,
    contact_name VARCHAR(255) NULL,
    contact_email VARCHAR(255) NULL,
    contact_title VARCHAR(100) NULL,
    effective_date DATE NOT NULL,
    expiration_date DATE NULL,
    term_months INT DEFAULT 12,
    document_content LONGTEXT NOT NULL,
    notes TEXT NULL,
    status ENUM('draft', 'sent', 'viewed', 'signed', 'declined', 'expired'),
    public_token VARCHAR(64) NULL,
    token_expires_at DATETIME NULL,
    sent_at DATETIME NULL,
    viewed_at DATETIME NULL,
    signed_at DATETIME NULL,
    declined_at DATETIME NULL,
    declined_reason TEXT NULL,
    created_by INT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (opportunity_id) REFERENCES opportunities(id),
    FOREIGN KEY (template_id) REFERENCES nda_templates(id),
    FOREIGN KEY (created_by) REFERENCES users(id)
);
```

#### `nda_signatures` Table
```sql
CREATE TABLE nda_signatures (
    id INT AUTO_INCREMENT PRIMARY KEY,
    nda_id INT NOT NULL,
    signature_data TEXT NOT NULL,        -- Base64 image
    signer_name VARCHAR(255) NOT NULL,
    signer_email VARCHAR(255) NOT NULL,
    signer_title VARCHAR(255) NULL,
    signer_company VARCHAR(255) NULL,
    acceptance_text TEXT NULL,
    signed_at DATETIME NOT NULL,
    ip_address VARCHAR(45) NULL,
    user_agent TEXT NULL,
    FOREIGN KEY (nda_id) REFERENCES ndas(id)
);
```

#### `nda_templates` Table
```sql
CREATE TABLE nda_templates (
    id INT AUTO_INCREMENT PRIMARY KEY,
    template_name VARCHAR(255) NOT NULL,
    template_type ENUM('unilateral', 'bilateral', 'multilateral'),
    template_content LONGTEXT NOT NULL,  -- HTML with merge fields
    is_default BOOLEAN DEFAULT 0,
    is_active BOOLEAN DEFAULT 1,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
```

#### `opportunities` Table Extensions
```sql
ALTER TABLE opportunities ADD COLUMN requires_nda BOOLEAN DEFAULT 0;
ALTER TABLE opportunities ADD COLUMN nda_status ENUM('not_required', 'sent', 'signed', 'declined') NULL;
ALTER TABLE opportunities ADD COLUMN block_quote_without_nda BOOLEAN DEFAULT 0;
```

---

## API Endpoints

### Quote Endpoints

#### Send Quote Email
```
POST /quotes/general/{id}/send-email

Headers:
  Content-Type: application/x-www-form-urlencoded

Body:
  to_email: customer@email.com
  subject: Quote {quote_number} - Please Review
  message: Custom message body
  csrf_token: {token}

Response:
{
  "success": true,
  "message": "Quote email sent successfully to customer@email.com"
}
```

#### View Quote (Public)
```
GET /quotes/accept/{token}

No authentication required
Returns HTML signature page
```

#### Accept Quote
```
POST /quotes/accept/{token}/submit

Body (FormData):
  signature_data: data:image/png;base64,...
  accepted_by_name: John Doe
  accepted_by_email: john@company.com
  accepted_by_title: CEO
  company_name: ACME Corp

Response:
{
  "success": true,
  "message": "Quote accepted successfully. Thank you!",
  "signature_id": 123
}
```

#### Decline Quote
```
POST /quotes/decline/{token}

Body (FormData):
  declined_by_name: John Doe
  declined_by_email: john@company.com
  declined_reason: Price too high

Response:
{
  "success": true,
  "message": "Quote declined. Thank you for your response."
}
```

### NDA Endpoints

#### Send NDA Email
```
POST /ndas/{id}/send-email

Headers:
  Content-Type: application/x-www-form-urlencoded

Body:
  to_email: customer@email.com
  subject: NDA {nda_number} - Signature Required
  message: Custom message body
  csrf_token: {token}

Response:
{
  "success": true,
  "message": "NDA email sent successfully to customer@email.com"
}
```

#### View NDA (Public)
```
GET /ndas/sign/{token}

No authentication required
Returns HTML signature page
```

#### Sign NDA
```
POST /ndas/sign/{token}/submit

Body (FormData):
  signature_data: data:image/png;base64,...
  signer_name: John Doe
  signer_email: john@company.com
  signer_title: CEO
  signer_company: ACME Corp
  acceptance_agreed: on
  acceptance_text: I agree to the terms

Response:
{
  "success": true,
  "message": "NDA signed successfully. Thank you!",
  "signature_id": 456
}
```

#### Decline NDA
```
POST /ndas/decline/{token}

Body (FormData):
  declined_reason: Cannot agree to terms

Response:
{
  "success": true,
  "message": "NDA declined. Thank you for your response."
}
```

#### Check NDA Status
```
GET /api/opportunities/{id}/nda-status

Response:
{
  "requires_nda": true,
  "nda_status": "signed",
  "block_without_nda": true,
  "can_proceed": true,
  "message": null
}
```

---

## Security Features

### 1. Token-Based Access
- **Public tokens:** 64-character random hex strings
- **Expiration:** 
  - Quotes: 30 days (configurable)
  - NDAs: 90 days (configurable)
- **One-time use:** Token invalidated after acceptance/decline
- **Validation:** Token checked before every action

### 2. CSRF Protection
- All POST endpoints require valid CSRF token
- Token generated per session
- Validated on every state-changing request

### 3. Authentication & Authorization
- Internal endpoints require authentication
- Permission checks: `sales.edit`, `ndas.send`
- Public signature pages accessible without auth

### 4. Audit Trail
Records for compliance:
- **IP Address:** Captured at signature time
- **User Agent:** Browser/device information
- **Timestamp:** Exact date/time of action
- **Signature Image:** Base64-encoded signature
- **Email verification:** Signer email captured

### 5. Input Validation
- Email address format validation
- Required field enforcement
- SQL injection prevention (prepared statements)
- XSS prevention (output escaping with `e()` helper)

### 6. Status Validation
- Prevents re-signing accepted quotes
- Prevents editing signed NDAs
- Blocks quote creation if NDA required and not signed
- Status transitions tracked in database

### 7. Data Sanitization
All user inputs sanitized:
```php
sanitize($_POST['field'])  // XSS prevention
e($variable)               // Output escaping
```

---

## Troubleshooting

### Email Not Sending

**Check SMTP Configuration:**
```php
// File: services/EmailService.php, Lines 34-40
$this->mailer->Host       = '172.104.216.9';
$this->mailer->SMTPAuth   = true;
$this->mailer->Username   = 'erp_system@mavrix.one';
$this->mailer->Password   = 'xyz8468RPMerkuri123!';
$this->mailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$this->mailer->Port       = 587;
```

**Check Error Logs:**
```bash
tail -f /path/to/php-error.log
# Look for "EmailService: Failed to send email"
```

**Test Email Function:**
```php
// Create test file: test_email.php
require_once 'services/EmailService.php';
$emailService = new EmailService();
$result = $emailService->sendQuoteForApproval(
    'test@example.com',
    'Test User',
    'Q-2024-00001',
    'http://localhost/quotes/accept/testtoken',
    1500.00,
    'Sales Team',
    '2024-12-31'
);
var_dump($result);
```

### Signature Page Not Loading

1. **Check token validity:**
   ```sql
   SELECT public_token, token_expires_at, customer_response 
   FROM quotes WHERE id = ?;
   ```

2. **Verify route exists:**
   ```bash
   grep "quotes/accept" public/index.php
   ```

3. **Check Apache/Nginx rewrite rules**

### Signature Not Saving

**Check browser console for JavaScript errors:**
- Canvas drawing issues
- AJAX request failures
- Form validation errors

**Verify database fields exist:**
```sql
DESCRIBE quotes;
DESCRIBE quote_signatures;
```

### NDA Not Linking to Opportunity

**Check foreign key:**
```sql
SELECT o.id, o.name, n.id, n.nda_number, o.nda_status
FROM opportunities o
LEFT JOIN ndas n ON n.opportunity_id = o.id
WHERE o.id = ?;
```

**Update opportunity NDA status:**
```php
// In NDA model after signature
$this->db->update('opportunities', [
    'nda_status' => 'signed'
], 'id = ?', [$nda['opportunity_id']]);
```

---

## Maintenance Tasks

### Weekly
- [ ] Review email send logs
- [ ] Check for expired tokens
- [ ] Monitor signature page access logs

### Monthly
- [ ] Clean up old signatures (if needed)
- [ ] Review accepted/declined ratios
- [ ] Update email templates based on feedback
- [ ] Test email deliverability

### Quarterly
- [ ] Review SMTP credentials/expiration
- [ ] Update legal language in NDA templates
- [ ] Audit security features
- [ ] Performance optimization

---

## Future Enhancements

### Planned Features
- [ ] PDF attachment of quote/NDA in email
- [ ] Reminder emails for unsigned documents
- [ ] Mobile-responsive improvements
- [ ] Bulk email sending
- [ ] Email open tracking
- [ ] Template builder UI
- [ ] Multi-language support
- [ ] SMS notifications
- [ ] Electronic notarization
- [ ] Integration with DocuSign/HelloSign

---

## Support & Documentation

### Related Documentation
- `EMAIL_INTEGRATION.md` - Detailed email service documentation
- `WARP.md` - General development guidelines
- `OPPORTUNITIES_ENHANCEMENTS.md` - CRM opportunities features
- `database/README.md` - Database migration guide

### Questions?
Refer to inline code comments in:
- `services/EmailService.php`
- `controllers/QuoteController.php`
- `controllers/NDAController.php`
- `models/QuoteSignature.php`
- `models/NDA.php`
