# Production Deployment Guide - WhatsApp Marketing Module

## 📋 Table of Contents
1. [Server Requirements](#server-requirements)
2. [Initial Server Setup](#initial-server-setup)
3. [Install Dependencies](#install-dependencies)
4. [Deploy Laravel Application](#deploy-laravel-application)
5. [Deploy WhatsApp Service](#deploy-whatsapp-service)
6. [Configure Nginx](#configure-nginx)
7. [SSL/HTTPS Setup](#sslhttps-setup)
8. [Process Management](#process-management)
9. [Security Hardening](#security-hardening)
10. [Monitoring & Logging](#monitoring--logging)
11. [Backup Automation](#backup-automation)
12. [Testing Production](#testing-production)
13. [Troubleshooting](#troubleshooting)

---

## Server Requirements

### Minimum Specifications
- **OS:** Ubuntu 22.04 LTS (recommended) or Ubuntu 20.04 LTS
- **CPU:** 2 cores (4+ recommended for high volume)
- **RAM:** 4GB (8GB+ recommended)
- **Storage:** 40GB SSD minimum
- **Network:** 100 Mbps connection

### Recommended VPS Providers
- DigitalOcean ($24/month - 4GB RAM, 2 vCPUs)
- Vultr ($18/month - 4GB RAM, 2 vCPUs)
- Linode ($24/month - 4GB RAM, 2 vCPUs)
- AWS EC2 t3.medium
- Google Cloud e2-medium

### Required Software Versions
- PHP 8.1 or 8.2
- MySQL 8.0 or MariaDB 10.6+
- Node.js 18.x or 20.x LTS
- Nginx 1.18+
- Redis 6.0+ (for queues)
- Supervisor 4.0+
- PM2 (latest)

---

## Initial Server Setup

### 1. Connect to Server
```bash
ssh root@your-server-ip
```

### 2. Create Deploy User
```bash
# Create user
adduser deploy
usermod -aG sudo deploy

# Allow sudo without password (optional, for automation)
echo "deploy ALL=(ALL) NOPASSWD:ALL" | sudo tee /etc/sudoers.d/deploy

# Switch to deploy user
su - deploy
```

### 3. Update System
```bash
sudo apt update && sudo apt upgrade -y
sudo apt install -y curl git unzip software-properties-common
```

### 4. Configure Firewall
```bash
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw enable
sudo ufw status
```

### 5. Set Timezone
```bash
sudo timedatectl set-timezone Asia/Kuala_Lumpur  # Adjust to your timezone
timedatectl
```

---

## Install Dependencies

### 1. Install PHP 8.2
```bash
# Add PHP repository
sudo add-apt-repository ppa:ondrej/php -y
sudo apt update

# Install PHP and extensions
sudo apt install -y php8.2-fpm php8.2-cli php8.2-mysql php8.2-mbstring \
  php8.2-xml php8.2-curl php8.2-zip php8.2-gd php8.2-bcmath \
  php8.2-redis php8.2-intl php8.2-soap

# Verify installation
php -v
```

### 2. Install MySQL 8.0
```bash
sudo apt install -y mysql-server

# Secure MySQL
sudo mysql_secure_installation

# Create database
sudo mysql -u root -p
```

**In MySQL:**
```sql
CREATE DATABASE neosolvix_production CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'neosolvix'@'localhost' IDENTIFIED BY 'your-strong-password';
GRANT ALL PRIVILEGES ON neosolvix_production.* TO 'neosolvix'@'localhost';
FLUSH PRIVILEGES;
EXIT;
```

### 3. Install Redis
```bash
sudo apt install -y redis-server

# Configure Redis
sudo systemctl enable redis-server
sudo systemctl start redis-server

# Test
redis-cli ping  # Should return "PONG"
```

### 4. Install Node.js 20.x LTS
```bash
# Install Node.js
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs

# Verify
node -v
npm -v

# Install PM2 globally
sudo npm install -g pm2
```

### 5. Install Nginx
```bash
sudo apt install -y nginx

# Enable and start
sudo systemctl enable nginx
sudo systemctl start nginx

# Verify
curl http://localhost  # Should show Nginx welcome page
```

### 6. Install Composer
```bash
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
composer --version
```

### 7. Install Supervisor
```bash
sudo apt install -y supervisor
sudo systemctl enable supervisor
sudo systemctl start supervisor
```

---

## Deploy Laravel Application

### 1. Create Directory Structure
```bash
sudo mkdir -p /var/www/neosolvix
sudo chown -R deploy:deploy /var/www/neosolvix
cd /var/www/neosolvix
```

### 2. Clone Repository
```bash
# If using Git
git clone https://github.com/your-repo/neosolvix-web.git .

# Or upload via rsync from local
# rsync -avz --exclude 'node_modules' --exclude '.git' \
#   /path/to/local/neosolvix-web/ deploy@server-ip:/var/www/neosolvix/
```

### 3. Install PHP Dependencies
```bash
cd /var/www/neosolvix
composer install --no-dev --optimize-autoloader
```

### 4. Configure Environment
```bash
cp .env.example .env
nano .env
```

**Production `.env` settings:**
```env
APP_NAME=Neosolvix
APP_ENV=production
APP_KEY=  # Will generate in next step
APP_DEBUG=false
APP_URL=https://your-domain.com

LOG_CHANNEL=stack
LOG_LEVEL=error

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=neosolvix_production
DB_USERNAME=neosolvix
DB_PASSWORD=your-strong-password

BROADCAST_DRIVER=log
CACHE_DRIVER=redis
FILESYSTEM_DISK=local
QUEUE_CONNECTION=redis
SESSION_DRIVER=redis
SESSION_LIFETIME=120

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

# WhatsApp Service
WHATSAPP_NODE_SERVICE_URL=http://localhost:3001

# Mail settings (configure your SMTP)
MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
```

### 5. Generate Application Key
```bash
php artisan key:generate
```

### 6. Run Migrations
```bash
php artisan migrate --force
```

### 7. Seed Warming Schedules
```bash
php artisan db:seed --class=WhatsAppWarmingScheduleSeeder --force
```

### 8. Optimize Laravel
```bash
php artisan config:cache
php artisan route:cache
php artisan view:cache
```

### 9. Set Permissions
```bash
sudo chown -R deploy:www-data /var/www/neosolvix
sudo chmod -R 755 /var/www/neosolvix
sudo chmod -R 775 /var/www/neosolvix/storage
sudo chmod -R 775 /var/www/neosolvix/bootstrap/cache
```

---

## Deploy WhatsApp Service

### 1. Navigate to Service Directory
```bash
cd /var/www/neosolvix/whatsapp-service
```

### 2. Install Node Dependencies
```bash
npm install --production
```

### 3. Configure Environment
```bash
cp .env.example .env
nano .env
```

**Production `.env`:**
```env
PORT=3001
NODE_ENV=production

# Laravel Backend URL
LARAVEL_API_URL=https://your-domain.com/api

# Session Storage Path
SESSION_PATH=./sessions

# CORS Settings
CORS_ORIGIN=https://your-domain.com
```

### 4. Create Sessions Directory
```bash
mkdir -p sessions
chmod 755 sessions
```

### 5. Test Service Manually (optional)
```bash
npm start
# Press Ctrl+C to stop after verifying it starts without errors
```

---

## Configure Nginx

### 1. Create Laravel Site Configuration
```bash
sudo nano /etc/nginx/sites-available/neosolvix
```

**Paste this configuration:**
```nginx
# Laravel Application
server {
    listen 80;
    listen [::]:80;
    server_name your-domain.com www.your-domain.com;

    root /var/www/neosolvix/public;
    index index.php index.html;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;

    # Logging
    access_log /var/log/nginx/neosolvix-access.log;
    error_log /var/log/nginx/neosolvix-error.log;

    # Laravel routes
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # PHP-FPM
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_hide_header X-Powered-By;
    }

    # Deny access to hidden files
    location ~ /\.(?!well-known).* {
        deny all;
    }

    # Asset caching
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}

# WhatsApp Service Reverse Proxy
server {
    listen 80;
    server_name whatsapp.your-domain.com;

    # Logging
    access_log /var/log/nginx/whatsapp-service-access.log;
    error_log /var/log/nginx/whatsapp-service-error.log;

    # Proxy to Node.js service
    location / {
        proxy_pass http://localhost:3001;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;

        # Socket.IO specific
        proxy_buffering off;
        proxy_read_timeout 86400;
    }
}
```

### 2. Enable Site
```bash
sudo ln -s /etc/nginx/sites-available/neosolvix /etc/nginx/sites-enabled/
sudo nginx -t  # Test configuration
sudo systemctl reload nginx
```

### 3. Update DNS Records

**Add these DNS records at your domain registrar:**
- **A Record:** `your-domain.com` → `your-server-ip`
- **A Record:** `www.your-domain.com` → `your-server-ip`
- **A Record:** `whatsapp.your-domain.com` → `your-server-ip`

Wait 5-10 minutes for DNS propagation.

---

## SSL/HTTPS Setup

### 1. Install Certbot
```bash
sudo apt install -y certbot python3-certbot-nginx
```

### 2. Obtain SSL Certificates
```bash
# For main domain
sudo certbot --nginx -d your-domain.com -d www.your-domain.com

# For WhatsApp service subdomain
sudo certbot --nginx -d whatsapp.your-domain.com
```

**Follow prompts:**
- Enter email address
- Agree to terms
- Choose: Redirect HTTP to HTTPS (option 2)

### 3. Test Auto-Renewal
```bash
sudo certbot renew --dry-run
```

### 4. Update WhatsApp Service .env
```bash
nano /var/www/neosolvix/whatsapp-service/.env
```

Change:
```env
CORS_ORIGIN=https://your-domain.com
```

### 5. Update Laravel .env
```bash
nano /var/www/neosolvix/.env
```

Change:
```env
APP_URL=https://your-domain.com
WHATSAPP_NODE_SERVICE_URL=https://whatsapp.your-domain.com
```

### 6. Clear Laravel Cache
```bash
cd /var/www/neosolvix
php artisan config:clear
php artisan config:cache
```

---

## Process Management

### 1. Setup PM2 for WhatsApp Service

**Create PM2 ecosystem file:**
```bash
nano /var/www/neosolvix/whatsapp-service/ecosystem.config.js
```

*Content will be in separate file - see `whatsapp-service/ecosystem.config.js`*

**Start service:**
```bash
cd /var/www/neosolvix/whatsapp-service
pm2 start ecosystem.config.js
pm2 save
pm2 startup systemd
# Copy and run the command PM2 outputs
```

**PM2 Commands:**
```bash
pm2 list              # List all processes
pm2 logs whatsapp-service  # View logs
pm2 restart whatsapp-service  # Restart
pm2 stop whatsapp-service     # Stop
pm2 delete whatsapp-service   # Remove
```

### 2. Setup Supervisor for Laravel Queue

**Create queue worker config:**
```bash
sudo nano /etc/supervisor/conf.d/neosolvix-worker.conf
```

*Content will be in separate file - see below*

### 3. Setup Cron for Laravel Scheduler

```bash
crontab -e
```

**Add this line:**
```cron
* * * * * cd /var/www/neosolvix && php artisan schedule:run >> /dev/null 2>&1
```

---

## Security Hardening

### 1. Disable Directory Listing
Already handled in Nginx config above.

### 2. Hide PHP Version
```bash
sudo nano /etc/php/8.2/fpm/php.ini
```

Find and set:
```ini
expose_php = Off
```

Restart PHP-FPM:
```bash
sudo systemctl restart php8.2-fpm
```

### 3. Configure Fail2Ban (Optional but Recommended)
```bash
sudo apt install -y fail2ban

sudo nano /etc/fail2ban/jail.local
```

```ini
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 5

[sshd]
enabled = true

[nginx-http-auth]
enabled = true

[nginx-limit-req]
enabled = true
```

```bash
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
```

### 4. Secure MySQL
```bash
sudo mysql -u root -p
```

```sql
DELETE FROM mysql.user WHERE User='';
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';
FLUSH PRIVILEGES;
EXIT;
```

### 5. Disable Root SSH Login
```bash
sudo nano /etc/ssh/sshd_config
```

Find and set:
```
PermitRootLogin no
PasswordAuthentication no  # If using SSH keys
```

```bash
sudo systemctl restart sshd
```

---

## Monitoring & Logging

### 1. Setup Log Rotation
```bash
sudo nano /etc/logrotate.d/neosolvix
```

```
/var/www/neosolvix/storage/logs/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 deploy www-data
    sharedscripts
}

/var/log/pm2/*.log {
    daily
    missingok
    rotate 7
    compress
    delaycompress
    notifempty
    create 0640 deploy deploy
}
```

### 2. Monitor Disk Space
```bash
# Install monitoring tools
sudo apt install -y htop iotop ncdu

# Check disk usage
df -h
ncdu /var/www
```

### 3. Monitor Processes
```bash
# Laravel queue
sudo supervisorctl status

# WhatsApp service
pm2 status

# System resources
htop
```

### 4. Setup Email Alerts (Optional)

Install and configure `mailutils`:
```bash
sudo apt install -y mailutils

# Test
echo "Test email from server" | mail -s "Test" your@email.com
```

---

## Backup Automation

### 1. Create Backup Script
```bash
sudo nano /usr/local/bin/neosolvix-backup.sh
```

*Content will be in separate file - see `deployment/backup.sh`*

### 2. Make Executable
```bash
sudo chmod +x /usr/local/bin/neosolvix-backup.sh
```

### 3. Schedule Daily Backups
```bash
sudo crontab -e
```

```cron
# Daily backup at 2 AM
0 2 * * * /usr/local/bin/neosolvix-backup.sh >> /var/log/neosolvix-backup.log 2>&1
```

---

## Testing Production

### 1. Test Laravel Application
```bash
curl -I https://your-domain.com
# Should return 200 OK with HTTPS
```

### 2. Test WhatsApp Service
```bash
curl https://whatsapp.your-domain.com/health
# Should return JSON with status "ok"
```

### 3. Test Queue Worker
```bash
sudo supervisorctl status neosolvix-worker
# Should show RUNNING
```

### 4. Test Scheduler
```bash
cd /var/www/neosolvix
php artisan schedule:list
# Should show scheduled commands
```

### 5. End-to-End Test
1. Access: `https://your-domain.com`
2. Login to admin
3. Connect WhatsApp account (scan QR)
4. Create and launch test campaign
5. Verify messages sent successfully

---

## Troubleshooting

### Issue: 502 Bad Gateway

**Check PHP-FPM:**
```bash
sudo systemctl status php8.2-fpm
sudo tail -f /var/log/nginx/neosolvix-error.log
```

**Restart services:**
```bash
sudo systemctl restart php8.2-fpm
sudo systemctl reload nginx
```

### Issue: Queue Not Processing

**Check Supervisor:**
```bash
sudo supervisorctl status
sudo supervisorctl tail neosolvix-worker
sudo supervisorctl restart neosolvix-worker
```

### Issue: WhatsApp Service Not Starting

**Check PM2:**
```bash
pm2 logs whatsapp-service
pm2 restart whatsapp-service
```

**Check Node.js version:**
```bash
node -v  # Should be 18.x or 20.x
```

### Issue: SSL Certificate Errors

**Renew manually:**
```bash
sudo certbot renew --force-renewal
sudo systemctl reload nginx
```

### Issue: Database Connection Failed

**Check MySQL:**
```bash
sudo systemctl status mysql
sudo mysql -u neosolvix -p neosolvix_production
```

**Check credentials in `.env`**

### Issue: Permission Denied

**Fix permissions:**
```bash
cd /var/www/neosolvix
sudo chown -R deploy:www-data .
sudo chmod -R 755 .
sudo chmod -R 775 storage bootstrap/cache
```

---

## Post-Deployment Checklist

- [ ] All services running (Nginx, PHP-FPM, MySQL, Redis, PM2, Supervisor)
- [ ] SSL certificates installed and auto-renewal configured
- [ ] Firewall configured (UFW enabled with ports 80, 443, 22)
- [ ] Cron jobs configured (scheduler + backups)
- [ ] Logs rotating properly
- [ ] Backups scheduled and tested
- [ ] Queue worker running via Supervisor
- [ ] WhatsApp service running via PM2
- [ ] DNS records configured correctly
- [ ] Email alerts configured (optional)
- [ ] Monitoring setup (optional)
- [ ] End-to-end test successful
- [ ] Documentation updated with server details

---

## Maintenance Commands

```bash
# Update application
cd /var/www/neosolvix
git pull
composer install --no-dev --optimize-autoloader
php artisan migrate --force
php artisan config:cache
php artisan route:cache
php artisan view:cache
sudo supervisorctl restart neosolvix-worker

# Update WhatsApp service
cd /var/www/neosolvix/whatsapp-service
git pull
npm install --production
pm2 restart whatsapp-service

# Check logs
tail -f /var/www/neosolvix/storage/logs/laravel.log
pm2 logs whatsapp-service
sudo supervisorctl tail neosolvix-worker
tail -f /var/log/nginx/neosolvix-error.log

# Restart everything
sudo systemctl restart nginx php8.2-fpm mysql redis-server
sudo supervisorctl restart all
pm2 restart all
```

---

## 🎉 Deployment Complete!

Your WhatsApp Marketing Module is now running in production with:
- ✅ HTTPS/SSL enabled
- ✅ Queue worker running 24/7
- ✅ WhatsApp service managed by PM2
- ✅ Automated backups
- ✅ Log rotation
- ✅ Security hardened

**Access your application at:** `https://your-domain.com`

**Monitor WhatsApp service:** `https://whatsapp.your-domain.com/health`
