================================================================================
WHATSAPP SELF-HOSTED GATEWAY - ARCHITECTURE
================================================================================

Diagram arsitektur sistem WhatsApp Gateway self-hosted untuk MikhMon.

================================================================================
SYSTEM ARCHITECTURE
================================================================================

┌─────────────────────────────────────────────────────────────────────────┐
│                           USER / CUSTOMER                                │
│                                                                           │
│  ┌──────────────┐         ┌──────────────┐         ┌──────────────┐    │
│  │   Browser    │         │  WhatsApp    │         │  WhatsApp    │    │
│  │   (Admin)    │         │   (Agent)    │         │  (Customer)  │    │
│  └──────┬───────┘         └──────┬───────┘         └──────┬───────┘    │
│         │                        │                        │             │
└─────────┼────────────────────────┼────────────────────────┼─────────────┘
          │                        │                        │
          │ HTTP                   │ HTTP                   │ WhatsApp
          │                        │                        │ Protocol
          ▼                        ▼                        ▼
┌─────────────────────────────────────────────────────────────────────────┐
│                         MIKHMON APPLICATION (PHP)                        │
│                                                                           │
│  ┌────────────────────────────────────────────────────────────────┐    │
│  │                      Admin Panel                                │    │
│  │  - Generate Voucher                                             │    │
│  │  - User Management                                              │    │
│  │  - Agent Management                                             │    │
│  │  - WhatsApp Settings                                            │    │
│  │  - WhatsApp Gateway Admin ← NEW!                               │    │
│  └────────────────────────────────────────────────────────────────┘    │
│                                                                           │
│  ┌────────────────────────────────────────────────────────────────┐    │
│  │                   WhatsApp Integration                          │    │
│  │  - whatsapp_config.php (Config & Functions)                    │    │
│  │  - sendWhatsAppMessage() → Call Gateway API                    │    │
│  │  - formatVoucherMessage() → Format pesan                       │    │
│  │  - whatsapp_webhook.php → Handle incoming messages             │    │
│  └────────────────────────────────────────────────────────────────┘    │
│                                                                           │
│  ┌────────────────────────────────────────────────────────────────┐    │
│  │                    Agent System                                 │    │
│  │  - Agent Panel (agent/dashboard.php)                           │    │
│  │  - Generate Voucher API (api/agent_generate_voucher.php)      │    │
│  │  - Auto-deduct balance                                          │    │
│  │  - Send via WhatsApp                                            │    │
│  └────────────────────────────────────────────────────────────────┘    │
│                                                                           │
└───────────────────────────────┬───────────────────────────────────────────┘
                                │
                                │ HTTP POST
                                │ X-API-Key: xxx
                                │
                                ▼
┌─────────────────────────────────────────────────────────────────────────┐
│              WHATSAPP GATEWAY SERVICE (Node.js + Baileys)               │
│                         Port: 3000 (default)                             │
│                                                                           │
│  ┌────────────────────────────────────────────────────────────────┐    │
│  │                      REST API Server                            │    │
│  │  - Express.js                                                   │    │
│  │  - CORS enabled                                                 │    │
│  │  - API Key authentication                                       │    │
│  │  - Body parser (JSON)                                           │    │
│  └────────────────────────────────────────────────────────────────┘    │
│                                                                           │
│  ┌────────────────────────────────────────────────────────────────┐    │
│  │                      API Endpoints                              │    │
│  │  GET  /health              → Health check                       │    │
│  │  GET  /api/status          → Connection status                  │    │
│  │  GET  /api/qr              → Get QR code                        │    │
│  │  POST /api/send            → Send single message                │    │
│  │  POST /api/send-bulk       → Send bulk messages                 │    │
│  │  POST /api/logout          → Logout WhatsApp                    │    │
│  │  POST /api/restart         → Restart connection                 │    │
│  │  GET  /api/logs            → Get message logs                   │    │
│  └────────────────────────────────────────────────────────────────┘    │
│                                                                           │
│  ┌────────────────────────────────────────────────────────────────┐    │
│  │                   WhatsApp Client (Baileys)                     │    │
│  │  - Multi-device support                                         │    │
│  │  - QR Code authentication                                       │    │
│  │  - Session persistence (auth_info/)                             │    │
│  │  - Auto-reconnect                                               │    │
│  │  - Message queue                                                │    │
│  │  - Delay anti-spam (2s between messages)                        │    │
│  └────────────────────────────────────────────────────────────────┘    │
│                                                                           │
│  ┌────────────────────────────────────────────────────────────────┐    │
│  │                   Message Handler                               │    │
│  │  - Handle incoming messages                                     │    │
│  │  - Forward to MikhMon webhook                                   │    │
│  │  - Bot commands (HARGA, BELI, HELP)                            │    │
│  │  - Auto-reply                                                   │    │
│  └────────────────────────────────────────────────────────────────┘    │
│                                                                           │
│  ┌────────────────────────────────────────────────────────────────┐    │
│  │                      Database Logger                            │    │
│  │  - Log outgoing messages                                        │    │
│  │  - Log incoming messages                                        │    │
│  │  - Log errors                                                   │    │
│  │  - Table: wa_message_logs                                       │    │
│  └────────────────────────────────────────────────────────────────┘    │
│                                                                           │
└───────────────────────────────┬───────────────────────────────────────────┘
                                │
                                │ WhatsApp Web Protocol
                                │ WebSocket
                                │
                                ▼
┌─────────────────────────────────────────────────────────────────────────┐
│                        WHATSAPP SERVERS                                  │
│                                                                           │
│  - WhatsApp Web API                                                      │
│  - Multi-device support                                                  │
│  - End-to-end encryption                                                 │
│                                                                           │
└─────────────────────────────────────────────────────────────────────────┘

================================================================================
DATA FLOW - SEND VOUCHER
================================================================================

1. Admin/Agent generate voucher di MikhMon
   ↓
2. MikhMon call sendWhatsAppMessage()
   ↓
3. sendWhatsAppMessage() → HTTP POST ke Gateway API
   URL: http://localhost:3000/api/send
   Headers: X-API-Key: xxx
   Body: { phone: "08xxx", message: "voucher..." }
   ↓
4. Gateway API validate API key
   ↓
5. Gateway format phone number (62xxx)
   ↓
6. Gateway send via Baileys client
   ↓
7. Baileys → WhatsApp Servers
   ↓
8. WhatsApp Servers → Customer's WhatsApp
   ↓
9. Gateway log to database (wa_message_logs)
   ↓
10. Gateway return response to MikhMon
    { success: true, message: "sent" }
    ↓
11. MikhMon log to file (logs/whatsapp_log.txt)
    ↓
12. Done! ✅

================================================================================
DATA FLOW - INCOMING MESSAGE (BOT)
================================================================================

1. Customer send message to WhatsApp
   ↓
2. WhatsApp Servers → Gateway (Baileys)
   ↓
3. Gateway receive message event
   ↓
4. messageHandler process message
   ↓
5. Check command (HARGA, BELI, HELP)
   ↓
6. If command found:
   - Process command
   - Generate response
   - Send reply via Baileys
   ↓
7. Forward to MikhMon webhook
   HTTP POST: api/whatsapp_webhook.php
   Body: { sender: "62xxx", message: "...", timestamp: "..." }
   ↓
8. MikhMon webhook process:
   - Parse command
   - Generate voucher (if BELI)
   - Send voucher back
   ↓
9. Log to database
   ↓
10. Done! ✅

================================================================================
COMPONENT DETAILS
================================================================================

1. MIKHMON (PHP)
   ----------------
   Location: /var/www/html/mikhmon/
   
   Files:
   - include/whatsapp_config.php
     → Configuration & functions
     → sendWhatsAppMessage()
     → formatVoucherMessage()
   
   - settings/whatsapp_gateway_admin.php
     → Admin panel untuk monitoring
     → QR code display
     → Test message
     → Connection control
   
   - api/whatsapp_webhook.php
     → Handle incoming messages
     → Process bot commands
     → Generate voucher
   
   - hotspot/generateuser.php
     → Generate voucher
     → Send via WhatsApp
   
   - agent/dashboard.php
     → Agent panel
     → Generate voucher
     → Auto-send WhatsApp

2. GATEWAY SERVICE (Node.js)
   ---------------------------
   Location: /var/www/html/mikhmon/whatsapp-gateway/
   
   Files:
   - server.js
     → Main server
     → Express app
     → Initialize WhatsApp client
   
   - src/whatsapp.js
     → Baileys client
     → Send message
     → Handle connection
   
   - src/messageHandler.js
     → Process incoming messages
     → Bot commands
     → Forward to webhook
   
   - src/routes.js
     → API endpoints
     → Authentication
     → Request handling
   
   - src/database.js
     → MySQL connection
     → Message logging
   
   - src/logger.js
     → Pino logger
     → Console & file logging

3. DATABASE
   ---------
   Tables:
   
   - wa_message_logs
     → id, phone, message, direction
     → status, error_message
     → sent_at, received_at, created_at
   
   - wa_sessions
     → id, session_name, phone_number
     → status, last_connected
     → created_at, updated_at
   
   - agent_transactions (existing)
     → Track agent voucher generation
   
   - agent_vouchers (existing)
     → Track vouchers sent via WhatsApp

4. SESSION DATA
   -------------
   Location: whatsapp-gateway/auth_info/
   
   Files:
   - creds.json → WhatsApp credentials
   - app-state-sync-*.json → Session state
   - pre-key-*.json → Encryption keys
   
   IMPORTANT: Backup this folder!

================================================================================
SECURITY LAYERS
================================================================================

1. API KEY AUTHENTICATION
   - Required for all API calls
   - Header: X-API-Key
   - Must match .env and whatsapp_config.php

2. SESSION VALIDATION
   - MikhMon session check
   - Agent authentication
   - Admin authentication

3. INPUT VALIDATION
   - Phone number format
   - Message length
   - SQL injection prevention (PDO)
   - XSS prevention

4. RATE LIMITING
   - 2 second delay between messages
   - Prevent spam detection
   - Queue management

5. ENCRYPTION
   - WhatsApp end-to-end encryption
   - HTTPS (recommended for production)
   - Password hashing (bcrypt)

================================================================================
SCALABILITY
================================================================================

1. HORIZONTAL SCALING
   - Multiple gateway instances
   - Load balancer
   - Shared session storage

2. VERTICAL SCALING
   - Increase RAM (for more connections)
   - Faster CPU (for message processing)
   - SSD storage (for session data)

3. OPTIMIZATION
   - PM2 cluster mode
   - Redis for queue
   - CDN for static files
   - Database indexing

================================================================================
MONITORING & LOGGING
================================================================================

1. GATEWAY LOGS
   - PM2 logs: pm2 logs mikhmon-wa-gateway
   - Console logs (pino-pretty)
   - Error logs: logs/error.log
   - Combined logs: logs/combined.log

2. MESSAGE LOGS
   - Database: wa_message_logs table
   - File: mikhmon/logs/whatsapp_log.txt
   - Webhook logs: mikhmon/logs/webhook_log.txt

3. METRICS
   - Connection status
   - Message count (sent/failed)
   - Uptime
   - Response time

4. ALERTS
   - Connection lost
   - High error rate
   - Low balance (agent)
   - Spam detection

================================================================================
BACKUP & RECOVERY
================================================================================

1. BACKUP
   - Session data: whatsapp-gateway/auth_info/
   - Database: wa_message_logs, wa_sessions
   - Configuration: .env, whatsapp_config.php
   - Logs: logs/

2. RECOVERY
   - Restore session data → No need to scan QR again
   - Restore database → Message history
   - Restore config → Same API key

3. DISASTER RECOVERY
   - If session lost → Scan QR code again
   - If database lost → Logs still in files
   - If gateway crash → PM2 auto-restart

================================================================================
DEPLOYMENT OPTIONS
================================================================================

1. SAME SERVER (Recommended for small scale)
   - MikhMon & Gateway on same server
   - localhost communication
   - Easy setup

2. SEPARATE SERVER (Recommended for production)
   - MikhMon on web server
   - Gateway on dedicated server
   - Better performance & isolation

3. DOCKER (Recommended for DevOps)
   - Containerized deployment
   - Easy scaling
   - Consistent environment

4. CLOUD (Recommended for high availability)
   - AWS, GCP, Azure
   - Auto-scaling
   - Load balancing
   - High availability

================================================================================
PERFORMANCE
================================================================================

Resource Usage:
- CPU: ~5-10% (idle), ~20-30% (active)
- RAM: ~100-200MB (idle), ~300-500MB (active)
- Disk: ~50MB (code), ~10-100MB (session)
- Network: ~1-5 Mbps (depends on message volume)

Capacity:
- Messages per minute: ~30 (with 2s delay)
- Concurrent connections: 1 (per gateway instance)
- Max message size: 65KB (WhatsApp limit)

Optimization:
- Use PM2 cluster mode for multiple instances
- Use Redis for message queue
- Use CDN for static assets
- Optimize database queries

================================================================================

Version: 1.0.0
Last Updated: 2024
License: GPL-2.0

================================================================================
