# 🚀 Production Deployment Guide

## Subscription Reminder System - Production Setup

This guide covers the complete production deployment process for the subscription reminder system.

## 📋 Prerequisites

- **PHP 8.1+** with extensions: curl, mbstring, xml, zip, pdo_mysql
- **MySQL 8.0+** or compatible database
- **Composer** for PHP dependency management
- **Node.js & npm** for asset compilation
- **Web Server** (Nginx/Apache)
- **Supervisor** for queue management
- **SSL Certificate** (recommended)

## 🛠️ Server Configuration

### 1. Web Server Setup

**Nginx Configuration** (`/etc/nginx/sites-available/subscriptions.mycloud.mu`):

```nginx
server {
    listen 80;
    server_name subscriptions.mycloud.mu;
    root /var/www/subscriptions.mycloud.mu/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.3-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}
```

### 2. Queue Worker Setup

Install and configure Supervisor:

```bash
sudo apt-get install supervisor
sudo systemctl enable supervisor
sudo systemctl start supervisor
```

Create supervisor configuration at `/etc/supervisor/conf.d/laravel-worker.conf`:

```ini
[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/subscriptions.mycloud.mu/artisan queue:work --sleep=3 --tries=3 --max-jobs=1000 --queue=reminders
directory=/var/www/subscriptions.mycloud.mu
autostart=true
autorestart=true
numprocs=2
redirect_stderr=true
stdout_logfile=/var/www/subscriptions.mycloud.mu/storage/logs/worker.log
stopwaitsecs=3600
user=www-data
```

### 3. Cron Job Setup

Add to crontab (`crontab -e`):

```bash
# Subscription reminders - run every day at 5 AM
0 5 * * * cd /var/www/subscriptions.mycloud.mu && php artisan send:reminders >> /var/log/cron-reminders.log 2>&1

# Health check - every 30 minutes
*/30 * * * * cd /var/www/subscriptions.mycloud.mu && php artisan schedule:run >> /var/log/cron-schedule.log 2>&1
```

## 🚀 Deployment Process

### Option 1: Automated Deployment

```bash
# Make deployment script executable
chmod +x deploy.sh

# Run deployment
sudo ./deploy.sh production
```

### Option 2: Manual Deployment

```bash
# 1. Backup database and files
sudo -u www-data php artisan backup:run --only-db

# 2. Upload new files
# (git pull or file transfer)

# 3. Install dependencies
composer install --no-dev --optimize-autoloader
npm ci --production
npm run build

# 4. Run migrations
php artisan migrate --force

# 5. Optimize
php artisan config:cache
php artisan route:cache
php artisan view:cache

# 6. Set permissions
sudo chown -R www-data:www-data /var/www/subscriptions.mycloud.mu
find /var/www/subscriptions.mycloud.mu/storage -type d -exec chmod 755 {} \;
find /var/www/subscriptions.mycloud.mu/storage -type f -exec chmod 644 {} \;

# 7. Restart services
sudo supervisorctl restart laravel-worker:*
sudo systemctl reload nginx
```

## ⚙️ Environment Configuration

Copy `.env.example` to `.env` and configure:

```bash
cp .env.example .env
nano .env
```

**Required Environment Variables:**

```env
# Application
APP_NAME="Subscription Manager"
APP_ENV=production
APP_KEY=base64:YOUR_GENERATED_KEY_HERE
APP_DEBUG=false
APP_URL=https://subscriptions.mycloud.mu

# Database
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password

# Email Configuration (ZeptoMail)
EMAIL_FROM=noreply@mycloud.mu
ZEPTOMAIL_API_KEY=your_zeptomail_api_key

# SMS Configuration
SMS_API_URL=https://your-sms-provider.com
SMS_API_KEY=your_sms_api_key

# Reminder Settings
REMINDER_BATCH_SIZE=50
RATE_LIMIT_DELAY=1
ENABLE_MONITORING=true

# Queue Settings
QUEUE_CONNECTION=database
REMINDER_QUEUE_CONNECTION=database

# Logging
LOG_CHANNEL=stack
LOG_LEVEL=error
```

## 🔐 Security Setup

### 1. Generate Application Key

```bash
php artisan key:generate
```

### 2. Set Up SSL Certificate

```bash
# Using Let's Encrypt (certbot)
sudo certbot --nginx -d subscriptions.mycloud.mu
```

### 3. Configure Firewall

```bash
sudo ufw allow 'Nginx Full'
sudo ufw allow 'OpenSSH'
sudo ufw enable
```

## 📊 Monitoring & Health Checks

### Health Check Endpoints

- **Application Health**: `https://subscriptions.mycloud.mu/cron/health`
- **Admin Dashboard**: `https://subscriptions.mycloud.mu/admin`

### Monitoring Setup

1. **Set up monitoring for the health endpoint**
2. **Configure alerts for failed reminders** (check `email_log` and `sms_log` tables)
3. **Monitor queue size** via the dashboard or health endpoint
4. **Set up log aggregation** for `storage/logs/laravel.log`

## 🚨 Troubleshooting

### Common Issues

**Queue workers not starting:**
```bash
sudo supervisorctl status
sudo supervisorctl restart laravel-worker:*
tail -f /var/www/subscriptions.mycloud.mu/storage/logs/worker.log
```

**Database connection errors:**
```bash
php artisan tinker
>>> DB::connection()->getPdo();
```

**Permission errors:**
```bash
sudo chown -R www-data:www-data /var/www/subscriptions.mycloud.mu
sudo chmod -R 755 /var/www/subscriptions.mycloud.mu/storage
```

**Reminder emails not sending:**
```bash
php artisan tinker
>>> dispatch(new App\Jobs\SendReminderJob(App\Models\Subscription::first(), 60, 'email'));
```

## 📞 Support

For production issues:
1. Check the health endpoint: `/cron/health`
2. Review logs in `storage/logs/`
3. Check queue status: `php artisan queue:failed`
4. Verify database connectivity

## 🔄 Backup Strategy

- **Daily database backups** (automated via cron)
- **Application backups** before deployments
- **Off-site backup storage** for critical data
- **Test restore procedures** regularly

---

**🎉 Deployment Complete!**

Your subscription reminder system is now production-ready with:
- ✅ Robust error handling and retry logic
- ✅ Performance optimization for large datasets
- ✅ Comprehensive monitoring and health checks
- ✅ Rate limiting and API protection
- ✅ Enhanced security and validation
- ✅ Proper deployment configuration
- ✅ Production-grade dashboard with analytics
