# GengSewa Production Deployment Guide

## Overview
This guide covers deployment and optimization for handling 100-1000 daily booking requests.

## Pre-Deployment Checklist

### 1. Environment Configuration
- [ ] Copy `.env.production.example` to `.env`
- [ ] Update all production values in `.env`
- [ ] Set `APP_ENV=production`
- [ ] Set `APP_DEBUG=false`
- [ ] Generate new `APP_KEY`: `php artisan key:generate`
- [ ] Configure production database credentials
- [ ] Set up Redis for cache, session, and queues
- [ ] Configure email SMTP settings
- [ ] Update Bayarcash production credentials

### 2. Database Optimization
All database indexes have been added via migration. To apply:

```bash
# Run migrations
php artisan migrate

# Verify indexes were created
php artisan db:show
```

**Indexes Added:**
- **Bookings**: status, user_id, listing_id, check_in/check_out, composites
- **Listings**: is_available, is_featured, rental_type_id, location_id, user_id, composites
- **Users**: role, email_verified_at, vacation_mode
- **Payments**: booking_id, status, transaction_id, created_at
- **Pickup Locations**: is_active, type, created_by
- **Discount Tiers**: listing_id with min_days
- **Add-ons**: is_active
- **Reviews**: listing_id, user_id, created_at

### 3. Query Optimization
All N+1 queries have been optimized with eager loading:

**Optimized Components:**
- ✅ `ListingSearch` - Eager loads location, rentalType, reviews
- ✅ `BookingForm` - Preloads discountTiers, addOns, pickupLocations
- ✅ `Admin\BookingsManager` - Loads all relationships in single query
- ✅ `Host\BookingsManager` - Optimized for host-specific queries
- ✅ `User\Bookings` - Eager loads nested relationships
- ✅ `ListingDetails` - Preloads all display data
- ✅ `Admin\Dashboard` - Optimized statistics queries
- ✅ `Home` - Cached featured listings and filters

### 4. Caching Strategy

**Cache Layers:**
1. **Application Cache** (Redis recommended)
2. **OPcache** (PHP bytecode cache)
3. **Query Result Cache** (via Laravel Cache)

**Cached Data:**
- Locations (1 hour TTL)
- Rental Types (1 hour TTL)
- Featured Listings (10 minutes TTL)
- Application Settings (1 hour TTL)
- Filter Options (1 hour TTL)

**Cache Commands:**
```bash
# Warm up cache with frequently accessed data
php artisan cache:warmup

# Clear all caches
php artisan cache:clear

# Clear specific cache stores
php artisan config:clear
php artisan route:clear
php artisan view:clear
```

### 5. Production Optimization

Run the production optimization command:

```bash
# Optimize for production
php artisan production:optimize

# Or with cache clearing
php artisan production:optimize --clear
```

This command will:
- ✅ Cache configuration
- ✅ Cache routes
- ✅ Cache views
- ✅ Cache events
- ✅ Optimize Composer autoloader
- ✅ Build production assets (Vite)

### 6. Queue Configuration

**For Production (Recommended: Redis)**

1. Update `.env`:
```env
QUEUE_CONNECTION=redis
REDIS_QUEUE_CONNECTION=default
```

2. Start queue worker:
```bash
# Basic worker
php artisan queue:work redis --tries=3

# Production worker with timeout and memory limits
php artisan queue:work redis \
  --tries=3 \
  --timeout=60 \
  --max-jobs=1000 \
  --max-time=3600 \
  --sleep=3
```

3. Set up supervisor (Linux) or create a Windows service:

**Supervisor Configuration** (`/etc/supervisor/conf.d/gengsewa-worker.conf`):
```ini
[program:gengsewa-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /path/to/gengsewa/artisan queue:work redis --tries=3 --timeout=60
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=2
redirect_stderr=true
stdout_logfile=/path/to/gengsewa/storage/logs/worker.log
stopwaitsecs=3600
```

Then reload supervisor:
```bash
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start gengsewa-worker:*
```

### 7. Task Scheduling

Add to crontab:
```bash
* * * * * cd /path/to/gengsewa && php artisan schedule:run >> /dev/null 2>&1
```

**Scheduled Tasks:**
- Cache warmup every 30 minutes (recommended)
- Failed queue job cleanup
- Log rotation
- Database backups

Add to `app/Console/Kernel.php`:
```php
protected function schedule(Schedule $schedule)
{
    // Warm up cache every 30 minutes
    $schedule->command('cache:warmup')->everyThirtyMinutes();

    // Clean up old failed jobs weekly
    $schedule->command('queue:prune-failed --hours=168')->weekly();

    // Clean old cache entries
    $schedule->command('cache:prune-stale-tags')->hourly();
}
```

### 8. Server Configuration

**PHP Configuration (`php.ini`):**
```ini
; Memory limit
memory_limit = 256M

; OPcache settings
opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=20000
opcache.validate_timestamps=0  ; Disable in production
opcache.revalidate_freq=0
opcache.save_comments=1
opcache.fast_shutdown=1

; Performance
max_execution_time = 60
max_input_time = 60
post_max_size = 20M
upload_max_filesize = 10M
```

**MySQL Configuration (`my.cnf`):**
```ini
[mysqld]
# Connection settings
max_connections = 100
connect_timeout = 10
wait_timeout = 600
max_allowed_packet = 64M

# Buffer pool (adjust based on RAM)
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT

# Query cache (if MySQL < 8.0)
query_cache_type = 1
query_cache_size = 64M
query_cache_limit = 2M

# Performance
tmp_table_size = 64M
max_heap_table_size = 64M
table_open_cache = 4000
```

**Nginx Configuration:**
```nginx
server {
    listen 80;
    server_name yoursite.com www.yoursite.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name yoursite.com www.yoursite.com;
    root /path/to/gengsewa/public;

    index index.php index.html;

    # SSL configuration
    ssl_certificate /path/to/ssl/cert.pem;
    ssl_certificate_key /path/to/ssl/key.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml+rss application/json;

    # Client body size (for file uploads)
    client_max_body_size 20M;

    # Security headers (already added in Laravel middleware)
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;

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

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

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;

        # PHP FPM timeout
        fastcgi_read_timeout 60;
    }

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

### 9. Redis Configuration

Install and configure Redis:

```bash
# Install Redis
sudo apt-get install redis-server

# Configure Redis (/etc/redis/redis.conf)
maxmemory 256mb
maxmemory-policy allkeys-lru
save 900 1
save 300 10
save 60 10000
```

### 10. Security Checklist

- [ ] Set `APP_DEBUG=false`
- [ ] Generate strong `APP_KEY`
- [ ] Use HTTPS/SSL certificate
- [ ] Configure firewall (UFW/iptables)
- [ ] Disable directory listing
- [ ] Remove sensitive files from public access
- [ ] Set proper file permissions (755 for directories, 644 for files)
- [ ] Configure CSP headers (already in `SecurityHeaders` middleware)
- [ ] Enable rate limiting
- [ ] Set up fail2ban for brute force protection
- [ ] Regular security updates

### 11. Monitoring & Logging

**Log Files:**
- Application logs: `storage/logs/laravel.log`
- Queue worker logs: `storage/logs/worker.log`
- Nginx access: `/var/log/nginx/access.log`
- Nginx error: `/var/log/nginx/error.log`
- MySQL slow query: `/var/log/mysql/slow-query.log`

**Monitoring Tools:**
- Laravel Telescope (development only)
- New Relic / DataDog (APM)
- Sentry (error tracking)
- Laravel Horizon (queue monitoring - if using Redis)

**Log Rotation:**
```bash
# Add to /etc/logrotate.d/gengsewa
/path/to/gengsewa/storage/logs/*.log {
    daily
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data www-data
    sharedscripts
}
```

### 12. Backup Strategy

**Daily Backups:**
```bash
#!/bin/bash
# /path/to/backup.sh

DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/backups/gengsewa"

# Database backup
mysqldump -u username -ppassword gengsewa > $BACKUP_DIR/db_$DATE.sql
gzip $BACKUP_DIR/db_$DATE.sql

# Application files backup
tar -czf $BACKUP_DIR/files_$DATE.tar.gz /path/to/gengsewa \
  --exclude='/path/to/gengsewa/storage/logs' \
  --exclude='/path/to/gengsewa/node_modules' \
  --exclude='/path/to/gengsewa/vendor'

# Delete backups older than 30 days
find $BACKUP_DIR -type f -mtime +30 -delete
```

Add to crontab:
```bash
0 2 * * * /path/to/backup.sh >> /var/log/backup.log 2>&1
```

### 13. Performance Testing

Test your application under load:

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

# Test homepage (simulate 100 concurrent users, 1000 requests)
ab -n 1000 -c 100 https://yoursite.com/

# Test booking flow
ab -n 500 -c 50 https://yoursite.com/listings

# Expected results for optimized setup:
# - Time per request: < 100ms (average)
# - Requests per second: > 500
# - Failed requests: 0
```

### 14. Deployment Workflow

**Initial Deployment:**
```bash
# 1. Clone repository
git clone <repository-url> /var/www/gengsewa
cd /var/www/gengsewa

# 2. Install dependencies
composer install --optimize-autoloader --no-dev
npm install
npm run build

# 3. Set permissions
sudo chown -R www-data:www-data storage bootstrap/cache
sudo chmod -R 775 storage bootstrap/cache

# 4. Configure environment
cp .env.production.example .env
nano .env  # Edit with production values
php artisan key:generate

# 5. Run migrations
php artisan migrate --force

# 6. Optimize for production
php artisan production:optimize

# 7. Warm up cache
php artisan cache:warmup

# 8. Start queue workers
sudo supervisorctl start gengsewa-worker:*
```

**Updates/Redeployment:**
```bash
# 1. Enable maintenance mode
php artisan down

# 2. Pull latest code
git pull origin main

# 3. Update dependencies
composer install --optimize-autoloader --no-dev
npm install
npm run build

# 4. Run migrations
php artisan migrate --force

# 5. Clear and rebuild caches
php artisan production:optimize --clear

# 6. Warm up cache
php artisan cache:warmup

# 7. Restart queue workers
sudo supervisorctl restart gengsewa-worker:*

# 8. Disable maintenance mode
php artisan up
```

### 15. Performance Benchmarks

**Expected Performance (100-1000 daily requests):**
- Homepage load time: < 200ms
- Listing search: < 300ms
- Booking creation: < 500ms
- Database queries: < 50ms average
- Cache hit ratio: > 80%
- Server CPU usage: < 40%
- Memory usage: < 60%

### 16. Scaling Beyond 1000 Daily Requests

If traffic exceeds 1000 requests/day:

1. **Horizontal Scaling:**
   - Add load balancer (nginx/HAProxy)
   - Deploy multiple application servers
   - Use shared Redis/Database servers

2. **Database Optimization:**
   - Implement read replicas
   - Consider database connection pooling (PgBouncer/ProxySQL)

3. **CDN Integration:**
   - Serve static assets via CDN (CloudFlare, AWS CloudFront)
   - Cache listing images on CDN

4. **Advanced Caching:**
   - Full page caching for public pages
   - API response caching
   - Fragment caching in Blade templates

## Support & Troubleshooting

### Common Issues:

**Queue jobs not processing:**
```bash
# Check if worker is running
sudo supervisorctl status gengsewa-worker:*

# Restart workers
sudo supervisorctl restart gengsewa-worker:*

# Check failed jobs
php artisan queue:failed
```

**Cache issues:**
```bash
# Clear all caches
php artisan production:optimize --clear

# Rebuild caches
php artisan production:optimize
```

**Performance degradation:**
```bash
# Check slow queries
php artisan db:monitor

# Monitor queue status
php artisan queue:monitor redis

# Check cache hit ratio in Redis
redis-cli INFO stats
```

## Conclusion

Following this guide will ensure your GengSewa application is optimized for production use with:
- ✅ Comprehensive database indexing
- ✅ Query optimization with eager loading
- ✅ Multi-layer caching strategy
- ✅ Queue-based task processing
- ✅ Production-ready server configuration
- ✅ Security hardening
- ✅ Monitoring and logging
- ✅ Backup and recovery procedures

For questions or issues, refer to Laravel documentation or create an issue in the repository.
