# Optiqo Backend - Production Deployment Guide

This guide covers deploying the Optiqo binary options trading platform backend to production.

## 📋 Prerequisites

- Ubuntu 22.04 LTS or similar Linux server
- Root or sudo access
- Domain name configured
- SSL certificate (Let's Encrypt recommended)

## 🔧 Server Requirements

### Minimum Specifications
- **CPU**: 2 cores
- **RAM**: 4GB
- **Storage**: 50GB SSD
- **Bandwidth**: 100Mbps

### Recommended Specifications
- **CPU**: 4+ cores
- **RAM**: 8GB+
- **Storage**: 100GB+ SSD
- **Bandwidth**: 1Gbps

## 🚀 Installation Steps

### 1. Update System

```bash
sudo apt update && sudo apt upgrade -y
```

### 2. Install Required Software

```bash
# Install PHP 8.2
sudo apt install -y software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt update
sudo apt install -y php8.2 php8.2-fpm php8.2-cli php8.2-common php8.2-mysql \
    php8.2-zip php8.2-gd php8.2-mbstring php8.2-curl php8.2-xml php8.2-bcmath \
    php8.2-redis php8.2-intl

# Install MySQL 8.0
sudo apt install -y mysql-server

# Install Redis
sudo apt install -y redis-server

# Install Nginx
sudo apt install -y nginx

# Install Composer
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer

# Install Supervisor (for queue workers)
sudo apt install -y supervisor

# Install Certbot (for SSL)
sudo apt install -y certbot python3-certbot-nginx
```

### 3. Configure MySQL

```bash
sudo mysql_secure_installation

# Create database and user
sudo mysql -u root -p
```

```sql
CREATE DATABASE optiqo CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'optiqo_user'@'localhost' IDENTIFIED BY 'your_secure_password';
GRANT ALL PRIVILEGES ON optiqo.* TO 'optiqo_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;
```

### 4. Configure Redis

```bash
sudo nano /etc/redis/redis.conf
```

Update these settings:
```
maxmemory 256mb
maxmemory-policy allkeys-lru
```

```bash
sudo systemctl restart redis-server
sudo systemctl enable redis-server
```

### 5. Deploy Application

```bash
# Create application directory
sudo mkdir -p /var/www/optiqo
sudo chown -R $USER:$USER /var/www/optiqo

# Clone repository
cd /var/www/optiqo
git clone <your-repository-url> .

# Install dependencies
composer install --optimize-autoloader --no-dev

# Set permissions
sudo chown -R www-data:www-data /var/www/optiqo
sudo chmod -R 755 /var/www/optiqo
sudo chmod -R 775 /var/www/optiqo/storage
sudo chmod -R 775 /var/www/optiqo/bootstrap/cache
```

### 6. Configure Environment

```bash
cp .env.example .env
nano .env
```

Update with production values:
```env
APP_ENV=production
APP_DEBUG=false
APP_URL=https://api.optiqo.com

DB_DATABASE=optiqo
DB_USERNAME=optiqo_user
DB_PASSWORD=your_secure_password

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis
BROADCAST_DRIVER=redis

FRONTEND_URL=https://optiqo.com
```

```bash
# Generate application key
php artisan key:generate

# Create storage link
php artisan storage:link

# Import database schema
mysql -u optiqo_user -p optiqo < database/schema.sql

# Cache configuration
php artisan config:cache
php artisan route:cache
php artisan view:cache
```

### 7. Configure Nginx

```bash
sudo nano /etc/nginx/sites-available/optiqo
```

```nginx
server {
    listen 80;
    server_name api.optiqo.com;
    root /var/www/optiqo/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    index index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }

    # Rate limiting
    limit_req_zone $binary_remote_addr zone=api:10m rate=60r/m;
    limit_req zone=api burst=10 nodelay;
}
```

```bash
# Enable site
sudo ln -s /etc/nginx/sites-available/optiqo /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
```

### 8. Configure SSL

```bash
sudo certbot --nginx -d api.optiqo.com
```

### 9. Configure Queue Workers (Supervisor)

```bash
sudo nano /etc/supervisor/conf.d/optiqo-worker.conf
```

```ini
[program:optiqo-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/optiqo/artisan queue:work redis --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=4
redirect_stderr=true
stdout_logfile=/var/www/optiqo/storage/logs/worker.log
stopwaitsecs=3600
```

```bash
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start optiqo-worker:*
```

### 10. Configure WebSocket Service

```bash
sudo nano /etc/systemd/system/optiqo-websocket.service
```

```ini
[Unit]
Description=Optiqo WebSocket Server
After=network.target

[Service]
Type=simple
User=www-data
WorkingDirectory=/var/www/optiqo
ExecStart=/usr/bin/php /var/www/optiqo/artisan websocket:serve
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
```

```bash
sudo systemctl daemon-reload
sudo systemctl enable optiqo-websocket
sudo systemctl start optiqo-websocket
```

### 11. Configure Cron (Laravel Scheduler)

```bash
sudo crontab -e -u www-data
```

Add:
```
* * * * * cd /var/www/optiqo && php artisan schedule:run >> /dev/null 2>&1
```

### 12. Configure Firewall

```bash
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
```

## 🔒 Security Hardening

### 1. Disable Directory Listing

Already configured in Nginx config above.

### 2. Hide PHP Version

```bash
sudo nano /etc/php/8.2/fpm/php.ini
```

Set:
```ini
expose_php = Off
```

### 3. Configure Rate Limiting

Already configured in Nginx config above.

### 4. Enable Fail2Ban

```bash
sudo apt install -y fail2ban
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
```

### 5. Regular Security Updates

```bash
# Create update script
sudo nano /usr/local/bin/security-updates.sh
```

```bash
#!/bin/bash
apt update
apt upgrade -y
apt autoremove -y
```

```bash
sudo chmod +x /usr/local/bin/security-updates.sh

# Add to crontab
sudo crontab -e
```

Add:
```
0 2 * * 0 /usr/local/bin/security-updates.sh
```

## 📊 Monitoring

### 1. Application Logs

```bash
# View Laravel logs
tail -f /var/www/optiqo/storage/logs/laravel.log

# View Nginx logs
tail -f /var/log/nginx/error.log
tail -f /var/log/nginx/access.log

# View PHP-FPM logs
tail -f /var/log/php8.2-fpm.log
```

### 2. Queue Monitoring

```bash
# Check queue workers
sudo supervisorctl status

# View worker logs
tail -f /var/www/optiqo/storage/logs/worker.log
```

### 3. WebSocket Monitoring

```bash
# Check WebSocket service
sudo systemctl status optiqo-websocket

# View WebSocket logs
sudo journalctl -u optiqo-websocket -f
```

### 4. System Resources

```bash
# CPU and Memory
htop

# Disk usage
df -h

# Redis monitoring
redis-cli monitor
```

## 🔄 Deployment Updates

### Zero-Downtime Deployment

```bash
cd /var/www/optiqo

# Enable maintenance mode
php artisan down

# Pull latest changes
git pull origin main

# Update dependencies
composer install --optimize-autoloader --no-dev

# Run migrations (if any)
php artisan migrate --force

# Clear and cache
php artisan config:cache
php artisan route:cache
php artisan view:cache

# Restart services
sudo supervisorctl restart optiqo-worker:*
sudo systemctl restart optiqo-websocket
sudo systemctl reload php8.2-fpm

# Disable maintenance mode
php artisan up
```

## 💾 Backup Strategy

### 1. Database Backup

```bash
# Create backup script
sudo nano /usr/local/bin/backup-database.sh
```

```bash
#!/bin/bash
BACKUP_DIR="/var/backups/optiqo"
DATE=$(date +%Y%m%d_%H%M%S)
mkdir -p $BACKUP_DIR

mysqldump -u optiqo_user -p'your_password' optiqo | gzip > $BACKUP_DIR/optiqo_$DATE.sql.gz

# Keep only last 7 days
find $BACKUP_DIR -name "optiqo_*.sql.gz" -mtime +7 -delete
```

```bash
sudo chmod +x /usr/local/bin/backup-database.sh

# Schedule daily backups
sudo crontab -e
```

Add:
```
0 3 * * * /usr/local/bin/backup-database.sh
```

### 2. Application Backup

```bash
# Backup storage and uploads
tar -czf /var/backups/optiqo/storage_$(date +%Y%m%d).tar.gz /var/www/optiqo/storage
```

## 🚨 Troubleshooting

### Queue Not Processing

```bash
# Restart queue workers
sudo supervisorctl restart optiqo-worker:*

# Check for failed jobs
php artisan queue:failed
```

### WebSocket Connection Issues

```bash
# Check service status
sudo systemctl status optiqo-websocket

# Restart service
sudo systemctl restart optiqo-websocket

# Check logs
sudo journalctl -u optiqo-websocket -n 100
```

### High Memory Usage

```bash
# Clear cache
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear

# Restart PHP-FPM
sudo systemctl restart php8.2-fpm
```

### Database Connection Issues

```bash
# Check MySQL status
sudo systemctl status mysql

# Check connections
mysql -u optiqo_user -p -e "SHOW PROCESSLIST;"
```

## 📈 Performance Optimization

### 1. OPcache Configuration

```bash
sudo nano /etc/php/8.2/fpm/conf.d/10-opcache.ini
```

```ini
opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
opcache.revalidate_freq=2
opcache.fast_shutdown=1
```

### 2. PHP-FPM Tuning

```bash
sudo nano /etc/php/8.2/fpm/pool.d/www.conf
```

```ini
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
pm.max_requests = 500
```

### 3. MySQL Optimization

```bash
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
```

```ini
innodb_buffer_pool_size = 2G
innodb_log_file_size = 256M
max_connections = 200
query_cache_size = 0
query_cache_type = 0
```

## 📞 Support

For deployment issues, contact the development team or create an issue in the repository.

## ✅ Post-Deployment Checklist

- [ ] SSL certificate installed and auto-renewal configured
- [ ] Database backups scheduled
- [ ] Queue workers running
- [ ] WebSocket service running
- [ ] Cron jobs configured
- [ ] Firewall configured
- [ ] Monitoring tools set up
- [ ] Error logging configured
- [ ] Rate limiting enabled
- [ ] Security headers configured
- [ ] Performance optimization applied
- [ ] Documentation updated