# Mikhmon WhatsApp & Billing Integration

This integration adds comprehensive customer billing management and WhatsApp automation capabilities to your Mikhmon installation.

## Features

### 🏢 Customer Management
- Complete customer database with contact information
- Integration with MikroTik user accounts
- Package and pricing management
- Customer status tracking (Active/Suspended/Terminated)

### 📋 Invoice Management
- Automated monthly invoice generation
- Multiple payment method support
- Overdue tracking and notifications
- Payment confirmation system

### 📱 WhatsApp Automation
- Automated billing reminders
- Payment confirmations
- Service suspension warnings
- Welcome messages for new customers
- Bulk messaging capabilities
- Message logging and tracking

### 📊 Dashboard Integration
- Real-time WhatsApp service status
- Invoice summary cards
- Customer statistics
- Overdue payment tracking

## Installation

### 1. Database Setup
Run the SQL script to create the billing tables:
```sql
-- Execute the contents of billing/database.sql in your MySQL database
```

### 2. Node.js WhatsApp Service
1. Install Node.js (version 14 or higher)
2. Run the startup script:
   ```
   start-whatsapp-service.bat
   ```
3. Scan the QR code with your WhatsApp to authenticate

### 3. PHP Configuration
The billing system is compatible with **PHP 5.4+** and requires:
- Standard PHP installation (no special extensions needed)
- Write permissions on the project directory
- File system access for JSON storage

**Note**: No database setup required! Uses file-based storage.

## Usage

### Starting the WhatsApp Service
1. Double-click `start-whatsapp-service.bat`
2. Wait for QR code to appear
3. Scan with WhatsApp
4. Service will show "WhatsApp Client is ready!" when connected

### Customer Management
1. Navigate to **Billing & WhatsApp → Customer Management**
2. Add customers with contact information
3. Link to MikroTik usernames
4. Set package pricing

### Invoice Management
1. Navigate to **Billing & WhatsApp → Invoice Management**
2. Generate monthly invoices automatically
3. Record payments when received
4. Send reminders for overdue accounts

### WhatsApp Integration
- **Automatic Messages**: Welcome messages, billing reminders, payment confirmations
- **Manual Messages**: Send custom messages to customers
- **Bulk Operations**: Send notifications to multiple customers
- **Logs**: Track all sent messages

## API Endpoints

### WhatsApp Service (Node.js - Port 3000)
- `GET /health` - Check service status
- `POST /send-message` - Send single message
- `POST /send-bulk` - Send bulk messages
- `GET /logs` - Get message history

### PHP Bridge Functions
```php
// Send WhatsApp message
sendWhatsAppMessage($phone, $message, $customer_id);

// Send billing reminder
sendBillingReminder($phone, $name, $amount, $due_date, $customer_id);

// Send payment confirmation
sendPaymentConfirmation($phone, $name, $amount, $invoice_number, $customer_id);

// Check WhatsApp service status
isWhatsAppReady();
```

## Configuration

### WhatsApp Service Settings
Edit `whatsapp-service/server.js`:
- Change port (default: 3000)
- Modify database connection
- Adjust message delays

### Database Connection
Edit `api/billing.php`:
- Update database credentials
- Modify table names if needed

## Automated Operations

### Monthly Invoice Generation
```php
// Generate invoices for all active customers
$billing->generateMonthlyInvoices($month, $year);
```

### Overdue Notifications
```php
// Send WhatsApp reminders to overdue customers
$billing->sendOverdueNotifications();
```

### Scheduled Tasks
You can set up cron jobs or Windows scheduled tasks to:
- Generate monthly invoices automatically
- Send overdue notifications daily
- Clean up old message logs

## Security

### WhatsApp Authentication
- Uses WhatsApp Web.js with local authentication
- Session data stored securely in `wwebjs_auth` folder
- No third-party services involved

### Database Security
- Uses prepared statements to prevent SQL injection
- Sanitized input validation
- Error logging without exposing sensitive data

## Troubleshooting

### WhatsApp Service Issues
1. **QR Code Not Appearing**: Check Node.js installation and dependencies
2. **Authentication Failed**: Delete `wwebjs_auth` folder and restart
3. **Messages Not Sending**: Check internet connection and WhatsApp status

### Database Issues
1. **Connection Failed**: Verify MySQL credentials in config
2. **Tables Not Found**: Run the database.sql script
3. **Permission Denied**: Check MySQL user permissions

### PHP Issues
1. **CURL Error**: Enable curl extension in PHP
2. **File Permissions**: Ensure write access to project directory
3. **Memory Limit**: Increase PHP memory limit if needed

## Message Templates

### Billing Reminder
```
📧 *Billing Reminder* 📧

Dear *{customer_name}*,

This is a friendly reminder that your payment of *Rp {amount}* is due on *{due_date}*.

Please make your payment to avoid service interruption.

Thank you for your business! 🙏
```

### Payment Confirmation
```
✅ *Payment Confirmed* ✅

Dear *{customer_name}*,

We have received your payment of *Rp {amount}* for invoice #{invoice_number}.

Thank you for your prompt payment! 🎉

Your service will continue uninterrupted.
```

### Welcome Message
```
🎉 *Welcome to Our Internet Service* 🎉

Dear *{customer_name}*,

Your internet account has been activated!

📋 *Account Details:*
• Username: *{username}*
• Password: *{password}*

Please keep this information safe and do not share with others.

Welcome aboard! 🚀
```

## Support

For issues and questions:
1. Check the troubleshooting section
2. Review the Mikhmon documentation
3. Verify WhatsApp service logs
4. Check PHP error logs

## License

This integration follows the same license as Mikhmon (GPL-2.0).