# Email Notifications Implementation

## Overview
This document describes the implementation of email notifications in the ERP system. When new emails arrive, users receive:
1. Real-time notifications in the top bar bell icon
2. Badge counter on the Email menu item showing unread count

## Implementation Date
November 27, 2025

## Components Modified

### 1. Notification Model (`models/Notification.php`)
**Added Method:**
- `createEmailNotification($userId, $emailId, $fromName, $fromEmail, $subject, $bodyPreview = null)`
  - Creates a notification when a new email arrives
  - Links to the email view page
  - Uses `bi-envelope` icon
  - Shows sender name and email preview/subject

### 2. Email Webhook Controller (`controllers/EmailWebhookController.php`)
**Modified:**
- Added `Notification` model instantiation
- Added notification creation after email is received and saved
- Notifications are created for each recipient when email arrives via webhook

**Notification Trigger:**
- Location: After email is added to inbox folder (line ~161-175)
- Creates notification with sender info and preview text

### 3. Email Menu Badge Counter
**Database Migration:** `030_add_email_badge_counter.sql`
- Updates/creates Email menu item with badge query
- Badge query counts unread emails in inbox folder per user
- Badge color: `primary` (blue)

**Badge Query:**
```sql
SELECT COUNT(*) 
FROM emails e 
INNER JOIN email_folder_map efm ON e.id = efm.email_id 
INNER JOIN email_folders f ON efm.folder_id = f.id 
WHERE e.user_id = {user_id} 
  AND e.is_read = 0 
  AND f.folder_type = "inbox"
```

## Features

### Bell Icon Notifications
- **What:** Push notifications appear in the top bar bell icon dropdown
- **When:** Immediately when new email arrives (via webhook)
- **Content:** 
  - Sender name
  - Email subject or preview text (first 100 chars)
  - Timestamp
- **Icon:** Envelope icon (`bi-envelope`)
- **Action:** Clicking notification navigates to email view page

### Email Menu Badge
- **What:** Numeric badge on sidebar Email menu item
- **Shows:** Count of unread emails in inbox
- **Color:** Blue (primary)
- **Updates:** Automatically when emails are read/unread

## User Experience

### When Email Arrives:
1. User receives notification in bell icon (red badge appears)
2. Email menu item shows updated unread count
3. User clicks bell icon to see notification details
4. User clicks notification to view email
5. Email is marked as read, badge counts update

### Notification Polling:
- Notifications are polled every 30 seconds (existing system)
- Email badge updates on page navigation/refresh
- No additional polling needed - uses existing notification infrastructure

## Database Tables

### Used Tables:
- `notifications` - Stores email notifications
- `emails` - Email records
- `email_folders` - Folder structure (inbox, sent, etc.)
- `email_folder_map` - Maps emails to folders
- `menu_items` - Stores menu with badge query

## API Endpoints

### Existing (No Changes Required):
- `GET /api/notifications/unread` - Fetches unread notifications (includes email)
- `POST /api/notifications/{id}/read` - Marks notification as read
- `POST /api/notifications/read-all` - Marks all notifications as read

### Email Webhook (Modified):
- `POST /webhook/email/receive` - Now creates notifications for recipients

## Installation

### Apply Migration:
```bash
mysql -u root -p brickwal_m1_ds < database/migrations/030_add_email_badge_counter.sql
```

### Verify Email Menu Item:
```sql
SELECT id, label, url, badge_query, badge_color 
FROM menu_items 
WHERE url LIKE '%email%';
```

## Configuration

### Webhook Secret (Optional):
Set in `system_settings` table:
```sql
UPDATE system_settings 
SET setting_value = 'your-webhook-secret' 
WHERE setting_key = 'email_webhook_secret';
```

### Notification Polling Interval:
Located in `views/layouts/app.php` (line ~389):
- Default: 30 seconds
- Adjust `pollIntervalMs` if needed

## Testing

### Test Email Notification:
1. Send test email to user's IMAP address
2. Or trigger webhook: `POST /webhook/email/receive` with JSON payload:
```json
{
  "from": "sender@example.com",
  "to": "user@yourdomain.com",
  "subject": "Test Email",
  "text": "This is a test email body",
  "html": "<p>This is a test email body</p>",
  "date": "2025-11-27 13:00:00",
  "message_id": "<test123@example.com>"
}
```

3. Verify:
   - Notification appears in bell icon
   - Email menu badge increments
   - Clicking notification opens email
   - Reading email decrements badge

### Test Badge Counter:
1. Navigate to Email section
2. Check unread count in inbox
3. Verify badge matches unread count
4. Read an email
5. Verify badge decrements

## Troubleshooting

### Notifications Not Appearing:
- Check notification polling is active (console logs)
- Verify webhook is receiving emails
- Check `notifications` table for new records
- Review error logs for exceptions

### Badge Not Updating:
- Verify migration was applied
- Check `menu_items` table has `badge_query`
- Test badge query manually in SQL
- Clear browser cache
- Check user has inbox folder created

### Common Issues:
1. **Webhook not working:** Verify webhook secret matches
2. **Badge shows wrong count:** Check query syntax in migration
3. **Notifications not linking:** Verify email ID in notification metadata

## Future Enhancements
- Email notification preferences (enable/disable per user)
- Desktop push notifications (browser API)
- Email notification grouping (multiple emails from same sender)
- Smart notifications (VIP senders, urgent emails)
- Email filters for notification creation

## Related Files
- `models/Notification.php`
- `models/Email.php`
- `controllers/EmailWebhookController.php`
- `views/layouts/app.php` (notification polling)
- `views/layouts/sidebar_dynamic.php` (badge rendering)
- `database/migrations/030_add_email_badge_counter.sql`
