# WhatsApp Error Handling Implementation Guide

## Overview
This guide explains the comprehensive error handling system for WhatsApp and Email messaging in ChefSHub. All errors are properly categorized, logged on the backend, and displayed clearly to users on the frontend.

---

## Backend Error Handling (MailController.php)

### Error Types Handled

#### 1. **Invalid Number** (`invalid_number`)
- **Message**: "Invalid number: Phone number format validation fails"
- **Cause**: Phone number fails format validation
- **Validation Rules**:
  - Minimum 7 digits
  - Maximum 15 digits (E.164 standard)
  - Must contain only numeric characters (spaces, dashes, parentheses removed)
- **Example Error**: "+1-23" → "Invalid number: Phone number too short"

#### 2. **Number Not on WhatsApp** (`not_on_whatsapp`)
- **Message**: "Number not on WhatsApp"
- **Cause**: Valid phone number but user is not registered on WhatsApp
- **Status Code**: 400
- **Why it happens**: User has the correct phone number but hasn't installed WhatsApp

#### 3. **Network Errors** (`network_error`)
- **Message**: "Network error: Connection issues with WhatsApp service"
- **Types**:
  - Connection timeout
  - Connection refused
  - Failed to connect to WhatsApp API
- **Status Code**: 503 (Service Unavailable) or 500
- **Why it happens**: WhatsApp service endpoint unavailable or network unreachable

#### 4. **Authentication Errors** (`authentication_error`)
- **Message**: "Unauthorized/Forbidden"
- **Cause**: Invalid API credentials or insufficient permissions
- **Status Code**: 400 or 500

#### 5. **Exception Errors** (`exception`)
- **Message**: "Unexpected error: [detailed error message]"
- **Cause**: Unexpected runtime exceptions
- **Logging**: Full stack trace is logged for debugging

#### 6. **No Bookings** (`no_bookings`)
- **Message**: "No confirmed paid bookings found for this session"
- **Cause**: Session has no students with payment_status='paid' AND status='confirmed'
- **Status Code**: 404

#### 7. **Session Not Found** (`session_not_found`)
- **Message**: "Session not found"
- **Cause**: Session ID doesn't exist in database
- **Status Code**: 404

#### 8. **Invalid Email** (`invalid_email`) - Email only
- **Message**: "Invalid email address"
- **Cause**: Email field is empty or invalid format
- **Status Code**: 200 (included in partial failure response)

---

## Error Response Format

### Single Message Send
```json
{
  "success": false,
  "message": "Invalid number: Phone number format validation fails",
  "error_type": "invalid_number"
}
```

### Bulk Message Send (Partial Failure)
```json
{
  "success": false,
  "message": "✅ WhatsApp messages sent to 2 student(s) (2 failed)",
  "session_id": 1,
  "statistics": {
    "total_students": 4,
    "sent_count": 2,
    "failed_count": 2
  },
  "sent_to": [
    {
      "student_id": 1,
      "student_name": "John Doe",
      "phone": "+1234567890"
    }
  ],
  "failed": [
    {
      "student_id": 2,
      "student_name": "Jane Smith",
      "phone": "+1987654321",
      "reason": "Invalid number: Phone number format validation fails",
      "error_type": "invalid_number"
    },
    {
      "student_id": 3,
      "student_name": "Bob Wilson",
      "phone": "+1555555555",
      "reason": "Number not on WhatsApp",
      "error_type": "not_on_whatsapp"
    }
  ],
  "failure_details": "Failure Details:\nJane Smith (+1987654321): Invalid number: Phone number format validation fails\nBob Wilson (+1555555555): Number not on WhatsApp"
}
```

---

## Backend Methods

### 1. `sendWhatsapp(Request $request)` - Single Message
Sends WhatsApp to a single phone number with comprehensive error handling.

**Request**:
```json
{
  "phoneNumber": "+1234567890",
  "message": "Your course details...",
  "countryCode": "US"
}
```

**Error Handling**:
- Validates phone number format
- Categorizes API errors
- Catches network exceptions
- Returns structured error response

**Response**:
- Success: `{ "success": true, "message": "WhatsApp sent successfully" }`
- Failure: `{ "success": false, "message": "...", "error_type": "..." }`

---

### 2. `getSessionDetails(Request $request)`
Retrieves session with confirmed paid bookings.

**Request**:
```json
{
  "session_id": 1
}
```

**Error Handling**:
- Checks if session exists
- Filters only paid AND confirmed bookings
- Returns error if no bookings found
- Logs all warnings and errors

---

### 3. `sendEmail(Request $request)` - Bulk Email
Sends email to all confirmed paid students in a session.

**Request**:
```json
{
  "session_id": 1
}
```

**Error Handling**:
- Session validation
- Per-student email validation
- Catches notification exceptions
- Builds detailed failure report
- Returns success/partial failure/complete failure response

---

### 4. Helper Methods

#### `validatePhoneNumber($phoneNumber)`
Validates phone number format.

```php
private function validatePhoneNumber($phoneNumber)
{
    // Removes formatting, checks length (7-15 digits)
    // Returns: ['valid' => bool, 'reason' => string|null]
}
```

#### `categorizeError($errorMessage)`
Categorizes error message to determine error type.

```php
private function categorizeError($errorMessage)
{
    // Checks error message keywords to categorize
    // Returns: string (error_type)
}
```

---

## Frontend Error Handling (TableShow.vue)

### Methods

#### 1. `sendWhatsapp(sessionId)`
Sends WhatsApp to all students in a session.

**Flow**:
1. Call API with session_id
2. Receive response with statistics and failures
3. Show appropriate popup based on result
4. Update UI loading state

**Handles**:
- Network errors
- API validation errors
- Partial failures
- Complete failures

#### 2. `sendEmail(sessionId)`
Sends email to all students in a session.

**Same flow as sendWhatsapp**

#### 3. `showSuccessPopup(data)`
Shows success notification with statistics.

**Displays**:
- Success message
- Total students
- Sent count
- Failed count (if any)
- List of recipients

#### 4. `showPartialFailurePopup(data)`
Shows warning popup with detailed failure information.

**Displays**:
- Summary message with count
- Statistics table
- List of failed students with:
  - Student name
  - Phone/Email
  - Failure reason
  - Error type description

#### 5. `showErrorPopup(errorData)`
Shows error popup with description.

**Displays**:
- Error title
- Error message
- Error type explanation
- Detailed failures (if available)

#### 6. `getErrorTypeDescription(errorType)`
Returns user-friendly description for error type.

```javascript
const errorTypeDescription = {
  'invalid_number': 'Phone number format validation fails',
  'not_on_whatsapp': 'Valid phone but user not registered on WhatsApp',
  'network_error': 'Connection issues with WhatsApp service',
  'authentication_error': 'API authentication failed',
  'exception': 'Unexpected error occurred'
}
```

---

## Logging

All errors are logged with:
- **Log Level**: WARNING for expected errors, ERROR for exceptions
- **Context**: Student/user name, phone/email, session ID
- **Details**: Full error message, error type, and response data
- **Stack Trace**: Included for exceptions

### Example Log Entries

**Warning Log**:
```
[2024-04-16 10:30:45] local.WARNING: WhatsApp send failed for student
{
  "student": "John Doe",
  "phone": "+1234567890",
  "error": "Number not on WhatsApp",
  "error_type": "not_on_whatsapp",
  "session_id": 1
}
```

**Error Log**:
```
[2024-04-16 10:30:45] local.ERROR: WhatsApp connection error
{
  "error": "Failed to connect to 157.90.25.110:3001",
  "trace": "..."
}
```

---

## API Endpoints

### WhatsApp Routes
```
POST /Mail/send-whatsapp              - Send to single number
POST /Mail/send-whatsapp-to-session   - Send to session students
GET  /Mail/qr                         - Get WhatsApp QR code
POST /Mail/reset                      - Reset WhatsApp service
GET  /Mail/start                      - Start WhatsApp service
```

### Email Routes
```
POST /Mail/send-email      - Send to session students
```

### Session Routes
```
POST /Mail/session-details - Get session details with bookings
```

---

## Database Query Filters

**Booking Filters**:
- `payment_status == 'paid'` - Only confirmed payments
- `status == 'confirmed'` - Only confirmed bookings

**Student Selection**:
- Includes: id, name, email, MOBILE
- Filters inactive/cancelled students

**Course Details**:
- Includes: id, title_en, title_ar
- Links through session

---

## Error Messages Examples

### Invalid Number Errors
```
❌ Invalid number: Phone number format validation fails
   Reason: Phone number format validation fails. Numbers must be 7-15 digits.
```

```
❌ Invalid number: Phone number too short
   Reason: Phone number has less than 7 digits.
```

```
❌ Invalid number: Phone number too long
   Reason: Phone number exceeds 15 digits (E.164 standard).
```

### Not on WhatsApp
```
❌ Number not on WhatsApp
   Reason: The phone number is valid but not registered on WhatsApp.
```

### Network Errors
```
❌ Network error: Connection issues with WhatsApp service
   Reason: Connection issues with WhatsApp service. Please try again later.
```

---

## Success Messages

### Complete Success
```
✅ WhatsApp messages sent to 5 student(s)

📊 Statistics:
   👥 Total Students: 5
   ✅ Successfully Sent: 5
   ❌ Failed: 0
```

### Partial Success
```
✅ WhatsApp messages sent to 3 student(s) (2 failed)

📊 Statistics:
   👥 Total Students: 5
   ✅ Successfully Sent: 3
   ❌ Failed: 2

❌ Failure Details:
   Jane Smith (+1234567890): Invalid number: Phone number format validation fails
   Bob Wilson (+1987654321): Number not on WhatsApp
```

---

## Troubleshooting

| Issue | Solution |
|-------|----------|
| "Invalid number" for valid numbers | Check if phone has country code; must be 7-15 digits |
| "Number not on WhatsApp" | User needs to install WhatsApp on that number |
| Network errors | Check WhatsApp API service status (157.90.25.110:3001) |
| Bulk send very slow | Consider increasing HTTP timeout or send in smaller batches |
| Students not showing | Verify payment_status='paid' AND status='confirmed' in database |
| "Session not found" | Confirm session_id is correct and exists |
| "No bookings found" | Ensure there are bookings with payment_status='paid' AND status='confirmed' |

---

## Best Practices

✅ **Always validate** phone numbers before sending  
✅ **Categorize errors** for better user feedback  
✅ **Log everything** for debugging and auditing  
✅ **Show detailed failures** instead of generic messages  
✅ **Handle network errors** gracefully with retry suggestions  
✅ **Filter by payment** and status to ensure legitimate recipients  
✅ **Batch similar errors** for cleaner reporting  
✅ **Timeout HTTP requests** to avoid hanging  

---

## Future Improvements

- [ ] Add retry mechanism for failed messages
- [ ] Implement message queue for better performance
- [ ] Add SMS fallback for invalid WhatsApp numbers
- [ ] Create dashboard for message history and analytics
- [ ] Add scheduled message sending
- [ ] Implement message templates with validation
- [ ] Add bulk error export (CSV/PDF)

