# 🚀 PRODUCTION DEPLOYMENT GUIDE

Complete guide untuk deploy License API ke production server.

---

## 📋 **PRE-DEPLOYMENT CHECKLIST**

### **1. Server Requirements**

**Minimum:**
- ✅ PHP 8.2 atau lebih tinggi
- ✅ Composer 2.x
- ✅ MySQL 5.7+ atau PostgreSQL 12+
- ✅ Nginx atau Apache
- ✅ SSL Certificate (Let's Encrypt gratis)
- ✅ 1GB RAM minimum (2GB recommended)
- ✅ 10GB Storage

**Extensions PHP yang dibutuhkan:**
```bash
php -m | grep -E 'pdo|mysql|mbstring|xml|ctype|json|tokenizer|openssl|bcmath'
```

Harus terinstall:
- ✅ PDO
- ✅ PDO_MySQL atau PDO_PgSQL
- ✅ mbstring
- ✅ xml
- ✅ ctype
- ✅ json
- ✅ tokenizer
- ✅ openssl
- ✅ bcmath

---

## 🖥️ **SERVER SETUP**

### **Option A: Shared Hosting** (Mudah, Murah)

**Recommended Providers:**
- Hostinger (Rp 25k/bulan)
- Niagahoster (Rp 45k/bulan)
- Rumahweb (Rp 75k/bulan)

**Steps:**
1. Upload via FTP/cPanel File Manager
2. Import database via phpMyAdmin
3. Update .env file
4. Set permissions
5. Done!

---

### **Option B: VPS** (Recommended for Production)

**Recommended Providers:**
- DigitalOcean ($6/month)
- Vultr ($5/month)
- Linode ($5/month)
- AWS Lightsail ($5/month)

**Steps:** (Detailed below)

---

## 🚀 **DEPLOYMENT STEPS (VPS)**

### **Step 1: Prepare Server (Ubuntu 22.04)**

```bash
# Update system
sudo apt update && sudo apt upgrade -y

# Install PHP 8.2
sudo apt install software-properties-common -y
sudo add-apt-repository ppa:ondrej/php -y
sudo apt update
sudo apt install php8.2 php8.2-fpm php8.2-cli php8.2-common php8.2-mysql \
  php8.2-mbstring php8.2-xml php8.2-curl php8.2-zip php8.2-gd \
  php8.2-bcmath php8.2-intl -y

# Install Nginx
sudo apt install nginx -y

# Install MySQL
sudo apt install mysql-server -y
sudo mysql_secure_installation

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

# Install Git
sudo apt install git -y

# Install Certbot (for SSL)
sudo apt install certbot python3-certbot-nginx -y
```

---

### **Step 2: Create Database**

```bash
# Login to MySQL
sudo mysql -u root -p

# Create database and user
CREATE DATABASE license_api_production CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'licenseapi'@'localhost' IDENTIFIED BY 'your_secure_password_here';
GRANT ALL PRIVILEGES ON license_api_production.* TO 'licenseapi'@'localhost';
FLUSH PRIVILEGES;
EXIT;
```

---

### **Step 3: Upload Application**

**Option A: Via Git (Recommended)**

```bash
# Create directory
sudo mkdir -p /var/www/licenseapi
cd /var/www/licenseapi

# Clone (if using Git repo)
# git clone https://github.com/yourusername/licenseapi.git .

# Or upload via SFTP/SCP
# Use FileZilla or WinSCP to upload all files
```

**Option B: Upload Manually**

1. Zip project di local (exclude: vendor/, node_modules/, .env, storage/*)
2. Upload via SFTP to `/var/www/licenseapi`
3. Unzip di server

---

### **Step 4: Configure Application**

```bash
# Navigate to project
cd /var/www/licenseapi

# Install dependencies
composer install --optimize-autoloader --no-dev

# Copy environment file
cp env.production.example .env

# Edit .env
nano .env
```

**Update `.env` dengan data production:**

```env
APP_NAME="License API"
APP_ENV=production
APP_DEBUG=false
APP_URL=https://api.yourdomain.com

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=license_api_production
DB_USERNAME=licenseapi
DB_PASSWORD=your_secure_password_here
```

```bash
# Generate app key
php artisan key:generate

# Run migrations
php artisan migrate --force

# Seed initial data (optional)
php artisan db:seed --class=LicenseSeeder

# Cache configuration
php artisan config:cache
php artisan route:cache
php artisan view:cache

# Set permissions
sudo chown -R www-data:www-data /var/www/licenseapi
sudo chmod -R 755 /var/www/licenseapi
sudo chmod -R 775 /var/www/licenseapi/storage
sudo chmod -R 775 /var/www/licenseapi/bootstrap/cache
```

---

### **Step 5: Configure Nginx**

```bash
# Create Nginx config
sudo nano /etc/nginx/sites-available/licenseapi
```

**Add configuration:**

```nginx
server {
    listen 80;
    server_name api.yourdomain.com;
    root /var/www/licenseapi/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;
    }
}
```

```bash
# Enable site
sudo ln -s /etc/nginx/sites-available/licenseapi /etc/nginx/sites-enabled/

# Test Nginx config
sudo nginx -t

# Restart Nginx
sudo systemctl restart nginx
```

---

### **Step 6: Setup SSL (HTTPS)**

```bash
# Get SSL certificate (automatic)
sudo certbot --nginx -d api.yourdomain.com

# Test auto-renewal
sudo certbot renew --dry-run
```

Certbot akan otomatis:
- Generate SSL certificate
- Update Nginx config
- Setup auto-renewal

---

### **Step 7: Setup Firewall**

```bash
# Allow SSH, HTTP, HTTPS
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw enable
sudo ufw status
```

---

### **Step 8: Setup Process Monitor (Optional)**

**Install Supervisor (untuk queue workers):**

```bash
sudo apt install supervisor -y

# Create config
sudo nano /etc/supervisor/conf.d/licenseapi.conf
```

Add:

```ini
[program:licenseapi-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/licenseapi/artisan queue:work --sleep=3 --tries=3
autostart=true
autorestart=true
user=www-data
numprocs=2
redirect_stderr=true
stdout_logfile=/var/www/licenseapi/storage/logs/worker.log
```

```bash
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start licenseapi-worker:*
```

---

## 🔒 **SECURITY HARDENING**

### **1. Update .env Security**

```env
APP_DEBUG=false  # NEVER true in production!
APP_ENV=production
SESSION_SECURE_COOKIE=true
```

### **2. Disable Directory Listing**

Already handled by Nginx config above.

### **3. Hide Laravel Version**

Edit `public/index.php`:

```php
// Remove or comment:
// header('X-Powered-By: PHP/'.PHP_VERSION);
```

### **4. Setup Rate Limiting**

Already configured in `bootstrap/app.php`:

```php
->withMiddleware(function (Middleware $middleware) {
    $middleware->throttleApi();
})
```

### **5. Setup Fail2Ban (Optional)**

```bash
sudo apt install fail2ban -y
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
```

### **6. Regular Backups**

**Automated Daily Backup:**

```bash
# Create backup script
sudo nano /usr/local/bin/backup-licenseapi.sh
```

Add:

```bash
#!/bin/bash
BACKUP_DIR="/backups/licenseapi"
DATE=$(date +%Y%m%d_%H%M%S)

# Create backup directory
mkdir -p $BACKUP_DIR

# Backup database
mysqldump -u licenseapi -p'your_password' license_api_production > $BACKUP_DIR/db_$DATE.sql

# Backup files
tar -czf $BACKUP_DIR/files_$DATE.tar.gz /var/www/licenseapi

# Keep only last 7 days
find $BACKUP_DIR -type f -mtime +7 -delete

echo "Backup completed: $DATE"
```

```bash
sudo chmod +x /usr/local/bin/backup-licenseapi.sh

# Add to crontab (daily at 2 AM)
sudo crontab -e
```

Add:

```
0 2 * * * /usr/local/bin/backup-licenseapi.sh
```

---

## 📊 **MONITORING**

### **1. Setup Log Rotation**

```bash
sudo nano /etc/logrotate.d/licenseapi
```

Add:

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

### **2. Monitor Disk Space**

```bash
# Check disk usage
df -h

# Check Laravel logs
tail -f /var/www/licenseapi/storage/logs/laravel.log
```

### **3. Setup Uptime Monitoring**

Use services like:
- UptimeRobot (gratis)
- Pingdom
- StatusCake

Monitor URL: `https://api.yourdomain.com/api/verify?key=test&domain=test`

---

## 🎯 **POST-DEPLOYMENT CHECKLIST**

### **Test Everything:**

```bash
# 1. Check website accessible
curl https://api.yourdomain.com

# 2. Test API endpoints
curl "https://api.yourdomain.com/api/verify?key=test&domain=test"

# 3. Test admin panel
# Open: https://api.yourdomain.com/

# 4. Check SSL
curl -I https://api.yourdomain.com | grep -i "strict-transport"

# 5. Check logs
tail -n 50 /var/www/licenseapi/storage/logs/laravel.log

# 6. Test database connection
cd /var/www/licenseapi
php artisan tinker
>>> App\Models\License::count()
```

### **Performance Test:**

```bash
# Install Apache Bench
sudo apt install apache2-utils -y

# Test API performance
ab -n 100 -c 10 https://api.yourdomain.com/api/verify?key=test&domain=test
```

---

## 📱 **UPDATE CLIENT FILES**

Update `LicenseValidator.php` di semua client websites:

```php
// OLD (development):
private $apiBaseUrl = 'http://127.0.0.1:8000/api';

// NEW (production):
private $apiBaseUrl = 'https://api.yourdomain.com/api';
```

---

## 🔄 **UPDATING APPLICATION**

**For future updates:**

```bash
# Backup first!
/usr/local/bin/backup-licenseapi.sh

# Pull latest code (if using Git)
cd /var/www/licenseapi
git pull origin main

# Update dependencies
composer install --optimize-autoloader --no-dev

# Run migrations
php artisan migrate --force

# Clear & cache
php artisan config:cache
php artisan route:cache
php artisan view:cache

# Restart services
sudo systemctl restart php8.2-fpm
sudo systemctl restart nginx
```

---

## 🆘 **TROUBLESHOOTING**

### **Issue: 500 Internal Server Error**

```bash
# Check Laravel logs
tail -f /var/www/licenseapi/storage/logs/laravel.log

# Check Nginx logs
sudo tail -f /var/log/nginx/error.log

# Check PHP-FPM logs
sudo tail -f /var/log/php8.2-fpm.log

# Fix permissions
sudo chown -R www-data:www-data /var/www/licenseapi
sudo chmod -R 775 /var/www/licenseapi/storage
```

### **Issue: Database Connection Failed**

```bash
# Test MySQL connection
mysql -u licenseapi -p license_api_production

# Check .env database credentials
cat /var/www/licenseapi/.env | grep DB_

# Clear config cache
php artisan config:clear
php artisan config:cache
```

### **Issue: SSL Certificate Expired**

```bash
# Renew certificate
sudo certbot renew

# Restart Nginx
sudo systemctl restart nginx
```

---

## 📈 **SCALING**

### **When to Scale:**

- > 10,000 licenses
- > 1000 API requests/minute
- Multiple customer websites

### **Scaling Options:**

1. **Vertical Scaling** - Upgrade VPS (more CPU/RAM)
2. **Horizontal Scaling** - Load balancer + multiple servers
3. **Database Scaling** - Master-slave replication
4. **Caching** - Redis/Memcached
5. **CDN** - CloudFlare for static assets

---

## 💰 **ESTIMATED COSTS**

| Service | Cost/Month | Purpose |
|---------|------------|---------|
| VPS (Basic) | $5-10 | App + Database |
| Domain | $1-2 | yourdomain.com |
| SSL | $0 | Let's Encrypt (gratis) |
| Backup Storage | $2-5 | Optional |
| **Total** | **$8-17** | **Basic Production** |

---

## ✅ **PRODUCTION READINESS CHECKLIST**

**Server:**
- [ ] PHP 8.2+ installed
- [ ] MySQL/PostgreSQL configured
- [ ] Nginx/Apache configured
- [ ] SSL certificate installed
- [ ] Firewall configured
- [ ] Backups automated

**Application:**
- [ ] .env configured for production
- [ ] APP_DEBUG=false
- [ ] Database migrated
- [ ] Permissions set correctly
- [ ] Cache cleared and rebuilt
- [ ] Logs rotating

**Security:**
- [ ] HTTPS enabled
- [ ] Strong database password
- [ ] Rate limiting enabled
- [ ] Directory listing disabled
- [ ] Laravel version hidden

**Testing:**
- [ ] Website accessible
- [ ] API endpoints working
- [ ] Admin panel accessible
- [ ] SSL certificate valid
- [ ] Performance acceptable

**Monitoring:**
- [ ] Uptime monitoring setup
- [ ] Log monitoring
- [ ] Disk space monitoring
- [ ] Backup verification

---

## 🎉 **DEPLOYMENT COMPLETE!**

Your License API is now **PRODUCTION READY**! 🚀

**Access Points:**
- API Server: `https://api.yourdomain.com/`
- Admin Panel: `https://api.yourdomain.com/`
- API Endpoints: `https://api.yourdomain.com/api/*`

**Next Steps:**
1. Update all client websites with new API URL
2. Create first production license
3. Monitor logs and performance
4. Set up regular backups
5. Document for your team

---

**Version:** 1.0.0  
**Last Updated:** November 2024  
**Status:** Production Ready ✅

