# Unofficial WhatsApp Marketing Module

## Overview

This module provides unofficial WhatsApp integration for marketing, bulk messaging, and customer communication without using the official WhatsApp Business API. It includes comprehensive anti-ban measures, number warming systems, and intelligent rate limiting.

## ⚠️ Important Disclaimers

1. **This is an unofficial integration** - It uses WhatsApp Web protocol, which violates WhatsApp's Terms of Service
2. **Risk of Ban** - Your WhatsApp number can be banned by WhatsApp for bulk messaging
3. **No Guarantees** - Even with all precautions, bans can still occur
4. **Use at Your Own Risk** - This is intended for legitimate business communications only
5. **Legal Compliance** - Ensure you comply with spam laws and have consent from recipients

## Key Features

### 1. **Number Warming System**
Gradually increases message limits to avoid triggering WhatsApp's spam detection.

**Three Warming Schedules:**

- **Conservative (21 Days)** - Safest, recommended for new numbers
  - Day 1: 20 messages → Day 21: 500 messages
  - Gradual 3-week progression

- **Moderate (14 Days)** - Balanced approach
  - Day 1: 30 messages → Day 14: 500 messages
  - 2-week warming period

- **Aggressive (7 Days)** - Fast but risky
  - Day 1: 50 messages → Day 7: 500 messages
  - Only for established numbers

### 2. **Multi-Layer Rate Limiting**

- **Per Minute**: Default 5 messages/min (adjustable)
- **Per Hour**: Default 60 messages/hour
- **Per Day**: Based on warming schedule (20-500)
- **Randomized Delays**: 10-30 seconds between messages (human-like behavior)

### 3. **Anti-Ban Measures**

**Ban Score System (0-100)**:
- Low (0-30): Safe - Green status
- Medium (31-60): Caution - Yellow status
- High (61-80): Warning - Orange status
- Critical (81-100): Danger - Red status

**Automatic Actions Based on Ban Score:**
- Score > 60: Reduce sending speed by 50%
- Score > 80: Pause all campaigns for 24 hours
- Score > 90: Require manual review before resuming

**What Increases Ban Score:**
- Consecutive failures (+5 per failure)
- Messages marked as spam (+15 per report)
- Disconnections during campaign (+10)
- Exceeding rate limits (+20)
- Same message to multiple people (+3 per duplicate)

**What Decreases Ban Score:**
- Successful message delivery (-1 per message)
- 24 hours of no issues (-10 per day)
- Recipient replies to message (-5 per reply)
- Messages from saved contacts (-2 per message)

### 4. **Campaign Management**

**Campaign Types:**
- **Blast Campaign**: Send to multiple contacts at once
- **Drip Campaign**: Scheduled messages over time
- **Follow-up Campaign**: Automated responses based on triggers
- **Personalized Campaign**: Custom messages with variables

**Campaign Features:**
- Contact list management
- Message templates with variables `{name}`, `{company}`, etc.
- Media support (images, videos, documents)
- Scheduling and time-zone awareness
- A/B testing capabilities
- Real-time analytics

### 5. **Smart Queue System**

**Priority Levels:**
- **Urgent**: Customer service replies (processed immediately)
- **High**: Transactional messages (order confirmations, etc.)
- **Normal**: Marketing campaigns
- **Low**: Bulk broadcasts

**Queue Management:**
- Respects rate limits automatically
- Pauses during high-risk periods (midnight-6am)
- Retries failed messages (max 3 attempts)
- Distributes load across multiple accounts

## Database Schema

### whatsapp_unofficial_accounts
Stores WhatsApp account connections and their status.

**Key Fields:**
- `phone_number`: WhatsApp number
- `status`: disconnected, qr_pending, connected, warming, active, banned
- `warming_day`: Current day in warming schedule (1-21)
- `messages_per_day`: Current daily limit
- `ban_score`: Risk level (0-100)
- `session_data`: Encrypted WhatsApp Web session

### whatsapp_warming_schedules
Predefined warming schedules.

**Includes:**
- Conservative, Moderate, Aggressive schedules
- Daily message limits for each day
- Auto-adjusts account limits daily

### whatsapp_unofficial_campaigns
Marketing campaigns and broadcasts.

**Features:**
- Campaign name, type, status
- Target audience filters
- Message templates
- Scheduling options
- Success metrics

### whatsapp_unofficial_messages
Message queue and history.

**Tracks:**
- Message content and recipient
- Send status (pending, sent, delivered, read, failed)
- Timestamps and delivery confirmation
- Error logs for failures

### whatsapp_unofficial_contacts
Contact database for campaigns.

**Stores:**
- Phone numbers and names
- Tags and segments
- Opt-in/opt-out status
- Engagement metrics

## Technical Implementation

### Backend (Laravel)

**Models:**
- `WhatsAppUnofficialAccount`
- `WhatsAppWarmingSchedule`
- `WhatsAppCampaign`
- `WhatsAppMessage`
- `WhatsAppContact`

**Controllers:**
- `WhatsAppUnofficialController` - Main dashboard
- `WhatsAppCampaignController` - Campaign management
- `WhatsAppContactController` - Contact management

**Jobs (Queue):**
- `SendWhatsAppMessage` - Individual message sending
- `ProcessCampaign` - Campaign execution
- `UpdateWarmingDay` - Daily warming progression
- `CalculateBanScore` - Risk assessment
- `CleanupSession` - Session management

### Frontend Integration

**WhatsApp Web Connection:**
- Uses `whatsapp-web.js` library (Node.js)
- QR code scanning for authentication
- Maintains persistent session
- Auto-reconnect on disconnection

**Real-time Updates:**
- WebSocket for live status
- Message delivery confirmations
- Campaign progress tracking

## Setup Instructions

### 1. Install Dependencies

```bash
# Install Node.js packages (for WhatsApp Web)
npm install whatsapp-web.js qrcode-terminal

# Install Laravel packages
composer require predis/predis  # For queue management
```

### 2. Run Migrations

```bash
php artisan migrate
```

This creates all necessary tables with default warming schedules.

### 3. Configure Queue

In `.env`:
```
QUEUE_CONNECTION=redis
REDIS_CLIENT=predis
```

Start queue worker:
```bash
php artisan queue:work --queue=whatsapp-urgent,whatsapp-high,whatsapp-normal,whatsapp-low
```

### 4. Start WhatsApp Service

```bash
# Start Node.js WhatsApp Web service
node whatsapp-service.js
```

### 5. Connect WhatsApp Account

1. Go to Marketing → WhatsApp → Unofficial Accounts
2. Click "Add New Number"
3. Scan QR code with your WhatsApp mobile app
4. Choose warming schedule
5. Account will start in "warming" status

## Best Practices

### ✅ DO's

1. **Always Warm New Numbers** - Use Conservative schedule for brand new numbers
2. **Get Consent** - Only message people who opted in
3. **Personalize Messages** - Use names and relevant content
4. **Respect Time Zones** - Don't send messages at night
5. **Monitor Ban Score** - Keep it below 30
6. **Vary Message Content** - Don't send identical messages
7. **Use Saved Contacts** - Save important contacts in phone
8. **Space Out Messages** - Use random delays
9. **Respond to Replies** - Engage with responses
10. **Keep Sessions Active** - Don't disconnect frequently

### ❌ DON'Ts

1. **Don't Send Spam** - Unsolicited commercial messages
2. **Don't Use Fresh Numbers** - Always warm up first
3. **Don't Exceed Limits** - Respect rate limits strictly
4. **Don't Send Identical Messages** - Vary content slightly
5. **Don't Ignore Opt-Outs** - Honor unsubscribe requests
6. **Don't Message at Night** - Respect local time zones
7. **Don't Use Multiple Devices** - One device per number
8. **Don't Share Sessions** - Keep session data private
9. **Don't Reconnect Frequently** - Maintain stable connection
10. **Don't Send Media Spam** - Limit media messages

## Usage Workflow

### Step 1: Add WhatsApp Account
```
Dashboard → Unofficial Accounts → Add Number → Scan QR → Choose Warming
```

### Step 2: Import Contacts
```
Contacts → Import CSV → Map Fields → Review → Import
```

### Step 3: Create Campaign
```
Campaigns → Create → Choose Type → Select Contacts → Write Message → Schedule
```

### Step 4: Monitor Campaign
```
Campaigns → View Campaign → Live Stats → Delivery Reports
```

### Step 5: Manage Health
```
Accounts → View Account → Check Ban Score → Adjust Limits
```

## Monitoring & Analytics

### Account Health Dashboard

- **Status**: Current account state
- **Ban Score**: Risk level with color coding
- **Today's Usage**: Messages sent vs limit
- **Warming Progress**: Day X of Y
- **Success Rate**: % of delivered messages
- **Response Rate**: % of messages that got replies

### Campaign Analytics

- **Delivery Rate**: % successfully delivered
- **Read Rate**: % opened/read
- **Reply Rate**: % that generated responses
- **Opt-Out Rate**: % that unsubscribed
- **Bounce Rate**: % failed deliveries
- **Best Time**: Optimal sending times

## Troubleshooting

### Account Disconnected
**Solution**: Reconnect by scanning QR again. Check internet connection.

### High Ban Score
**Solution**:
1. Pause all campaigns
2. Wait 24-48 hours
3. Resume slowly with reduced limits

### Messages Failing
**Solution**:
1. Check if number is valid
2. Verify recipient hasn't blocked you
3. Ensure account is connected
4. Check rate limits aren't exceeded

### QR Code Not Loading
**Solution**:
1. Restart WhatsApp service
2. Clear browser cache
3. Check Node.js service is running

## Advanced Features

### Custom Variables in Messages
```
Hi {name}!

Your order #{order_id} has been confirmed.
Total: {amount}
Delivery: {date}

Thank you for choosing {company}!
```

### Webhook Integration
Receive real-time updates via webhooks:
- Message delivered
- Message read
- Reply received
- Campaign completed

### API Access
RESTful API for external integrations:
```
POST /api/whatsapp/send
GET /api/whatsapp/status/{id}
POST /api/whatsapp/campaign/create
```

## Security Considerations

1. **Session Data Encryption**: All session data is encrypted in database
2. **Access Control**: Role-based permissions for account management
3. **Audit Logs**: Track all message sending activities
4. **API Authentication**: Secure API endpoints with tokens
5. **Data Privacy**: GDPR-compliant contact management

## Maintenance

### Daily Tasks (Automated)
- Update warming day
- Calculate ban scores
- Clean old messages
- Generate reports

### Weekly Tasks (Manual)
- Review ban scores
- Audit campaign performance
- Clean contact lists
- Update message templates

### Monthly Tasks (Manual)
- Analyze trends
- Optimize warming schedules
- Review ROI
- Update strategies

## Legal & Compliance

1. **Get Consent**: Use double opt-in for subscribers
2. **Provide Opt-Out**: Easy unsubscribe in every message
3. **Respect Privacy**: Secure contact data
4. **Follow Laws**: Comply with local spam regulations
5. **Business Hours**: Send only during appropriate times

## Support & Resources

### Documentation
- This guide
- API documentation
- Video tutorials
- FAQs

### Community
- User forum
- Feature requests
- Bug reports

## Conclusion

This Unofficial WhatsApp Marketing Module provides powerful marketing capabilities while minimizing ban risks through intelligent warming, rate limiting, and monitoring systems. Always prioritize quality over quantity, respect recipients, and comply with regulations.

**Remember**: The best way to avoid bans is to send valuable, relevant messages to people who want to hear from you.
