# Configuration & Deployment

## Overview

This document covers all aspects of configuring and deploying the EventBookings Shopify app, including development setup, production deployment, monitoring, and maintenance procedures.

## Development Environment Setup

### Prerequisites

#### System Requirements
- **PHP**: 8.0 or higher
- **Database**: MySQL 8.0+ or PostgreSQL 13+
- **Web Server**: Apache 2.4+ or Nginx 1.18+
- **Redis**: 6.0+ (for caching and sessions)
- **Composer**: 2.0+
- **Node.js**: 16+ (for asset compilation)

#### Required PHP Extensions
```bash
# Check required extensions
php -m | grep -E "(pdo|pdo_mysql|mbstring|openssl|tokenizer|xml|ctype|json|bcmath|curl|fileinfo|gd|intl|zip)"

# Install missing extensions (Ubuntu/Debian)
sudo apt-get install php8.1-mysql php8.1-mbstring php8.1-xml php8.1-curl php8.1-gd php8.1-intl php8.1-zip php8.1-bcmath php8.1-redis

# Install missing extensions (CentOS/RHEL)
sudo yum install php-mysql php-mbstring php-xml php-curl php-gd php-intl php-zip php-bcmath php-redis
```

### Local Development Setup

#### Option 1: Laravel Sail (Docker)

```bash
# Create project with Sail
curl -s https://laravel.build/eventbookings-shopify-app | bash

cd eventbookings-shopify-app

# Start development environment
./vendor/bin/sail up -d

# Install additional services
./vendor/bin/sail artisan sail:install --with=mysql,redis
```

**File: `docker-compose.yml` (additions)**
```yaml
version: '3'
services:
    laravel.test:
        # ... existing configuration
        ports:
            - '${APP_PORT:-80}:80'
            - '${VITE_PORT:-5173}:${VITE_PORT:-5173}'
        environment:
            WWWUSER: '${WWWUSER}'
            LARAVEL_SAIL: 1
            XDEBUG_MODE: '${SAIL_XDEBUG_MODE:-off}'
            XDEBUG_CONFIG: '${SAIL_XDEBUG_CONFIG:-client_host=host.docker.internal}'
        volumes:
            - '.:/var/www/html'
        networks:
            - sail
        depends_on:
            - mysql
            - redis

    # Add ngrok for Shopify webhooks
    ngrok:
        image: ngrok/ngrok:latest
        restart: unless-stopped
        command:
            - "start"
            - "--all"
            - "--config"
            - "/etc/ngrok.yml"
        volumes:
            - ./ngrok.yml:/etc/ngrok.yml
        ports:
            - 4040:4040
        networks:
            - sail
```

**File: `ngrok.yml`**
```yaml
version: "2"
authtoken: YOUR_NGROK_AUTH_TOKEN
tunnels:
  app:
    addr: laravel.test:80
    proto: http
    hostname: your-app.ngrok.io  # Optional: use reserved domain
```

#### Option 2: Local LAMP/XAMPP Stack

**XAMPP Configuration:**
```bash
# Download and install XAMPP
# https://www.apachefriends.org/

# Start services
sudo /opt/lampp/lampp start

# Or on Windows
# Start XAMPP Control Panel and start Apache, MySQL
```

**Virtual Host Configuration (Apache):**

**File: `/opt/lampp/etc/extra/httpd-vhosts.conf`**
```apache
<VirtualHost *:80>
    ServerName eventbookings-shopify.local
    DocumentRoot /opt/lampp/htdocs/eventbookings-shopify-app/public

    <Directory /opt/lampp/htdocs/eventbookings-shopify-app/public>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog logs/eventbookings-error.log
    CustomLog logs/eventbookings-access.log combined
</VirtualHost>
```

**File: `/etc/hosts`**
```
127.0.0.1 eventbookings-shopify.local
```

### Environment Configuration

#### Development Environment

**File: `.env.development`**
```env
# Application
APP_NAME="EventBookings Shopify App"
APP_ENV=local
APP_KEY=base64:GENERATE_WITH_php_artisan_key:generate
APP_DEBUG=true
APP_URL=http://eventbookings-shopify.local

# Database
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=eventbookings_shopify_dev
DB_USERNAME=root
DB_PASSWORD=

# Shopify Configuration
SHOPIFY_CLIENT_ID=your_development_client_id
SHOPIFY_CLIENT_SECRET=your_development_client_secret
SHOPIFY_REDIRECT_URI=http://eventbookings-shopify.local/auth/shopify/callback
SHOPIFY_WEBHOOK_SECRET=your_webhook_secret

# EventBookings API
EVENTBOOKINGS_IDENTITY_URL=https://identity.eventbookings.com
EVENTBOOKINGS_API_URL=https://api-rto.eventbookings.com/v3
EVENTBOOKINGS_TIMEOUT=30

# Cache and Sessions
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis

# Redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

# Mail (for error notifications)
MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@eventbookings-shopify.local"
MAIL_FROM_NAME="${APP_NAME}"

# Logging
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

# Development Tools
TELESCOPE_ENABLED=true
DEBUGBAR_ENABLED=true
```

#### Testing Environment

**File: `.env.testing`**
```env
# Application
APP_ENV=testing
APP_KEY=base64:SAME_AS_DEVELOPMENT
APP_DEBUG=true
APP_URL=http://localhost

# Database (separate test database)
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=eventbookings_shopify_test
DB_USERNAME=root
DB_PASSWORD=

# Cache (use array driver for testing)
CACHE_DRIVER=array
SESSION_DRIVER=array
QUEUE_CONNECTION=sync

# Disable external API calls in tests
EVENTBOOKINGS_MOCK_API=true
SHOPIFY_MOCK_API=true

# Mail (use log driver for testing)
MAIL_MAILER=log
```

## Production Deployment

### Server Requirements

#### Recommended Server Specifications

**Minimum Requirements:**
- **CPU**: 2 vCPUs
- **RAM**: 4 GB
- **Storage**: 20 GB SSD
- **Bandwidth**: 100 Mbps

**Recommended for Production:**
- **CPU**: 4 vCPUs
- **RAM**: 8 GB
- **Storage**: 50 GB SSD
- **Bandwidth**: 1 Gbps

#### Production Server Stack

**Option 1: Traditional LAMP Stack**
```bash
# Ubuntu 22.04 LTS setup
sudo apt update && sudo apt upgrade -y

# Install PHP 8.1
sudo apt install software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt update
sudo apt install php8.1 php8.1-fpm php8.1-mysql php8.1-mbstring php8.1-xml php8.1-curl php8.1-gd php8.1-intl php8.1-zip php8.1-bcmath php8.1-redis

# Install Nginx
sudo apt install nginx

# Install MySQL
sudo apt install mysql-server

# Install Redis
sudo apt install redis-server

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

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

**Option 2: Docker Production Setup**

**File: `docker-compose.prod.yml`**
```yaml
version: '3.8'

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile.prod
    container_name: eventbookings-app
    restart: unless-stopped
    working_dir: /var/www
    volumes:
      - ./:/var/www
      - ./docker/php/local.ini:/usr/local/etc/php/conf.d/local.ini
    networks:
      - app-network
    depends_on:
      - db
      - redis

  webserver:
    image: nginx:alpine
    container_name: eventbookings-webserver
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./:/var/www
      - ./docker/nginx/conf.d/:/etc/nginx/conf.d/
      - ./docker/nginx/ssl/:/etc/nginx/ssl/
    networks:
      - app-network
    depends_on:
      - app

  db:
    image: mysql:8.0
    container_name: eventbookings-db
    restart: unless-stopped
    environment:
      MYSQL_DATABASE: ${DB_DATABASE}
      MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
      MYSQL_PASSWORD: ${DB_PASSWORD}
      MYSQL_USER: ${DB_USERNAME}
    volumes:
      - dbdata:/var/lib/mysql
      - ./docker/mysql/my.cnf:/etc/mysql/my.cnf
    networks:
      - app-network

  redis:
    image: redis:7-alpine
    container_name: eventbookings-redis
    restart: unless-stopped
    volumes:
      - redisdata:/data
    networks:
      - app-network

volumes:
  dbdata:
    driver: local
  redisdata:
    driver: local

networks:
  app-network:
    driver: bridge
```

**File: `Dockerfile.prod`**
```dockerfile
FROM php:8.1-fpm

# Set working directory
WORKDIR /var/www

# Install system dependencies
RUN apt-get update && apt-get install -y \
    git \
    curl \
    libpng-dev \
    libonig-dev \
    libxml2-dev \
    libzip-dev \
    zip \
    unzip \
    libfreetype6-dev \
    libjpeg62-turbo-dev \
    libpng-dev \
    libicu-dev \
    && rm -rf /var/lib/apt/lists/*

# Install PHP extensions
RUN docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install -j$(nproc) \
        pdo_mysql \
        mbstring \
        exif \
        pcntl \
        bcmath \
        gd \
        intl \
        zip

# Install Redis extension
RUN pecl install redis && docker-php-ext-enable redis

# Install Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

# Copy application files
COPY . /var/www

# Set proper permissions
RUN chown -R www-data:www-data /var/www \
    && chmod -R 755 /var/www/storage \
    && chmod -R 755 /var/www/bootstrap/cache

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

# Generate optimized autoloader
RUN php artisan config:cache \
    && php artisan route:cache \
    && php artisan view:cache

EXPOSE 9000

CMD ["php-fpm"]
```

### Production Environment Configuration

**File: `.env.production`**
```env
# Application
APP_NAME="EventBookings Shopify App"
APP_ENV=production
APP_KEY=base64:GENERATE_SECURE_KEY_FOR_PRODUCTION
APP_DEBUG=false
APP_URL=https://your-production-domain.com

# Database
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=eventbookings_shopify_prod
DB_USERNAME=eventbookings_user
DB_PASSWORD=SECURE_DATABASE_PASSWORD

# Shopify Configuration
SHOPIFY_CLIENT_ID=your_production_client_id
SHOPIFY_CLIENT_SECRET=your_production_client_secret
SHOPIFY_REDIRECT_URI=https://your-production-domain.com/auth/shopify/callback
SHOPIFY_WEBHOOK_SECRET=your_production_webhook_secret

# EventBookings API
EVENTBOOKINGS_IDENTITY_URL=https://identity.eventbookings.com
EVENTBOOKINGS_API_URL=https://api-rto.eventbookings.com/v3
EVENTBOOKINGS_TIMEOUT=30

# Cache and Sessions
CACHE_DRIVER=redis
SESSION_DRIVER=redis
SESSION_LIFETIME=120
SESSION_ENCRYPT=true
SESSION_SECURE_COOKIE=true

# Queue
QUEUE_CONNECTION=redis

# Redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=SECURE_REDIS_PASSWORD
REDIS_PORT=6379

# Mail
MAIL_MAILER=smtp
MAIL_HOST=your-smtp-server.com
MAIL_PORT=587
MAIL_USERNAME=your-smtp-username
MAIL_PASSWORD=your-smtp-password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS="noreply@your-production-domain.com"
MAIL_FROM_NAME="${APP_NAME}"

# Logging
LOG_CHANNEL=daily
LOG_LEVEL=warning
LOG_DAILY_DAYS=14

# Security
SESSION_SECURE_COOKIE=true
SESSION_HTTP_ONLY=true
SESSION_SAME_SITE=lax

# Performance
OPCACHE_ENABLE=1
OPCACHE_MEMORY_CONSUMPTION=256
OPCACHE_MAX_ACCELERATED_FILES=20000

# Monitoring
SENTRY_LARAVEL_DSN=your_sentry_dsn_if_using_sentry
```

### Web Server Configuration

#### Nginx Configuration

**File: `/etc/nginx/sites-available/eventbookings-shopify`**
```nginx
server {
    listen 80;
    listen [::]:80;
    server_name your-production-domain.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name your-production-domain.com;
    root /var/www/eventbookings-shopify-app/public;

    # SSL Configuration
    ssl_certificate /etc/letsencrypt/live/your-production-domain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/your-production-domain.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # 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;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    # CORS Headers for Widget Endpoints
    location ~* ^/(widgets|api)/ {
        add_header Access-Control-Allow-Origin "*" always;
        add_header Access-Control-Allow-Methods "GET, POST, OPTIONS" always;
        add_header Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With" always;
        add_header Access-Control-Max-Age "3600" always;

        if ($request_method = 'OPTIONS') {
            return 204;
        }

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

    # General Configuration
    index index.php;
    charset utf-8;

    # Disable access to hidden files
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }

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

    # PHP handling
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_hide_header X-Powered-By;

        # Security
        fastcgi_param HTTPS on;
        fastcgi_param SERVER_PORT 443;
    }

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

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_min_length 10240;
    gzip_proxied expired no-cache no-store private auth;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/x-javascript
        application/xml+rss
        application/javascript
        application/json;

    # Logs
    access_log /var/log/nginx/eventbookings-access.log;
    error_log /var/log/nginx/eventbookings-error.log;
}
```

#### Apache Configuration

**File: `/etc/apache2/sites-available/eventbookings-shopify.conf`**
```apache
<VirtualHost *:80>
    ServerName your-production-domain.com
    Redirect permanent / https://your-production-domain.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName your-production-domain.com
    DocumentRoot /var/www/eventbookings-shopify-app/public

    # SSL Configuration
    SSLEngine on
    SSLCertificateFile /etc/letsencrypt/live/your-production-domain.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/your-production-domain.com/privkey.pem

    # Security Headers
    Header always set X-Frame-Options "SAMEORIGIN"
    Header always set X-Content-Type-Options "nosniff"
    Header always set X-XSS-Protection "1; mode=block"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"

    # CORS for Widget Endpoints
    <LocationMatch "^/(widgets|api)/">
        Header set Access-Control-Allow-Origin "*"
        Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
        Header set Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With"
        Header set Access-Control-Max-Age "3600"
    </LocationMatch>

    # Directory Configuration
    <Directory /var/www/eventbookings-shopify-app/public>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted

        # PHP Configuration
        <FilesMatch \.php$>
            SetHandler "proxy:unix:/var/run/php/php8.1-fpm.sock|fcgi://localhost"
        </FilesMatch>
    </Directory>

    # Static files caching
    <LocationMatch "\.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$">
        ExpiresActive On
        ExpiresDefault "access plus 1 year"
        Header set Cache-Control "public, immutable"
    </LocationMatch>

    # Compression
    LoadModule deflate_module modules/mod_deflate.so
    <Location />
        SetOutputFilter DEFLATE
        SetEnvIfNoCase Request_URI \
            \.(?:gif|jpe?g|png)$ no-gzip dont-vary
        SetEnvIfNoCase Request_URI \
            \.(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary
    </Location>

    # Logs
    CustomLog /var/log/apache2/eventbookings-access.log combined
    ErrorLog /var/log/apache2/eventbookings-error.log
</VirtualHost>
```

### Database Configuration

#### MySQL Production Setup

**File: `/etc/mysql/mysql.conf.d/eventbookings.cnf`**
```ini
[mysqld]
# Basic Settings
default_storage_engine = InnoDB
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

# Performance Tuning
innodb_buffer_pool_size = 2G
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 1
innodb_flush_method = O_DIRECT

# Connection Settings
max_connections = 200
connect_timeout = 10
wait_timeout = 600
interactive_timeout = 600

# Query Cache (if needed)
query_cache_type = 1
query_cache_size = 64M
query_cache_limit = 1M

# Logging
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 2
log_queries_not_using_indexes = 1

# Security
bind-address = 127.0.0.1
```

#### Database User Setup

```sql
-- Create production database and user
CREATE DATABASE eventbookings_shopify_prod CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- Create dedicated user with limited privileges
CREATE USER 'eventbookings_user'@'localhost' IDENTIFIED BY 'SECURE_PASSWORD';

-- Grant necessary permissions
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, INDEX, ALTER, DROP, REFERENCES ON eventbookings_shopify_prod.* TO 'eventbookings_user'@'localhost';

-- Remove dangerous permissions
REVOKE SUPER, PROCESS, FILE, SHUTDOWN, RELOAD ON *.* FROM 'eventbookings_user'@'localhost';

FLUSH PRIVILEGES;
```

### SSL Certificate Setup

#### Using Let's Encrypt

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

# Obtain SSL certificate
sudo certbot --nginx -d your-production-domain.com

# Auto-renewal setup
sudo crontab -e
# Add this line:
0 12 * * * /usr/bin/certbot renew --quiet

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

#### Using Custom SSL Certificate

```bash
# Create SSL directory
sudo mkdir -p /etc/nginx/ssl

# Copy your certificates
sudo cp your-domain.crt /etc/nginx/ssl/
sudo cp your-domain.key /etc/nginx/ssl/

# Set proper permissions
sudo chmod 644 /etc/nginx/ssl/your-domain.crt
sudo chmod 600 /etc/nginx/ssl/your-domain.key
sudo chown root:root /etc/nginx/ssl/*
```

## Deployment Scripts

### Automated Deployment Script

**File: `deploy.sh`**
```bash
#!/bin/bash

# EventBookings Shopify App Deployment Script
set -e

# Configuration
APP_DIR="/var/www/eventbookings-shopify-app"
BACKUP_DIR="/var/backups/eventbookings"
DATE=$(date +%Y%m%d_%H%M%S)

echo "🚀 Starting deployment at $(date)"

# Create backup
echo "📦 Creating backup..."
sudo mkdir -p $BACKUP_DIR
sudo tar -czf $BACKUP_DIR/backup_$DATE.tar.gz -C $APP_DIR .

# Pull latest code
echo "📥 Pulling latest code..."
cd $APP_DIR
git pull origin main

# Install/update dependencies
echo "📚 Installing dependencies..."
composer install --no-dev --optimize-autoloader --no-interaction

# Run database migrations
echo "🗄️ Running database migrations..."
php artisan migrate --force

# Clear and cache configuration
echo "⚡ Optimizing application..."
php artisan config:clear
php artisan config:cache
php artisan route:clear
php artisan route:cache
php artisan view:clear
php artisan view:cache

# Clear application cache
php artisan cache:clear

# Set proper permissions
echo "🔐 Setting permissions..."
sudo chown -R www-data:www-data storage bootstrap/cache
sudo chmod -R 775 storage bootstrap/cache

# Restart services
echo "🔄 Restarting services..."
sudo systemctl reload php8.1-fpm
sudo systemctl reload nginx

# Run health check
echo "🏥 Running health check..."
php artisan tinker --execute="dump(App\Models\ShopifyStore::count());"

echo "✅ Deployment completed successfully at $(date)"

# Clean old backups (keep last 5)
echo "🧹 Cleaning old backups..."
sudo find $BACKUP_DIR -name "backup_*.tar.gz" -type f | sort -r | tail -n +6 | sudo xargs rm -f

echo "🎉 Deployment process finished!"
```

### Zero-Downtime Deployment

**File: `deploy-zero-downtime.sh`**
```bash
#!/bin/bash

# Zero-downtime deployment script
set -e

APP_NAME="eventbookings-shopify-app"
APP_DIR="/var/www/$APP_NAME"
RELEASES_DIR="$APP_DIR/releases"
SHARED_DIR="$APP_DIR/shared"
CURRENT_LINK="$APP_DIR/current"
RELEASE_DIR="$RELEASES_DIR/$(date +%Y%m%d_%H%M%S)"

echo "🚀 Starting zero-downtime deployment..."

# Create directory structure
sudo mkdir -p $RELEASES_DIR $SHARED_DIR/{storage,bootstrap/cache}

# Clone code to new release directory
echo "📥 Preparing new release..."
git clone https://github.com/your-repo/eventbookings-shopify-app.git $RELEASE_DIR
cd $RELEASE_DIR

# Install dependencies
echo "📚 Installing dependencies..."
composer install --no-dev --optimize-autoloader --no-interaction

# Link shared directories
echo "🔗 Linking shared directories..."
rm -rf storage bootstrap/cache
ln -s $SHARED_DIR/storage storage
ln -s $SHARED_DIR/bootstrap/cache bootstrap/cache

# Copy environment file
cp $SHARED_DIR/.env .env

# Run optimizations
echo "⚡ Optimizing application..."
php artisan config:cache
php artisan route:cache
php artisan view:cache

# Run migrations
echo "🗄️ Running database migrations..."
php artisan migrate --force

# Health check
echo "🏥 Running health check..."
php artisan tinker --execute="dump('Health check passed');" > /dev/null

# Switch to new release
echo "🔄 Switching to new release..."
sudo ln -sfn $RELEASE_DIR $CURRENT_LINK

# Reload services
sudo systemctl reload php8.1-fpm
sudo systemctl reload nginx

# Clean old releases (keep last 3)
echo "🧹 Cleaning old releases..."
sudo find $RELEASES_DIR -maxdepth 1 -type d | sort -r | tail -n +4 | sudo xargs rm -rf

echo "✅ Zero-downtime deployment completed!"
```

## Monitoring and Logging

### Application Monitoring

#### Health Check Endpoint

**File: `routes/api.php`**
```php
Route::get('/health', function () {
    $checks = [
        'database' => false,
        'redis' => false,
        'eventbookings_api' => false,
    ];

    try {
        // Database check
        DB::select('SELECT 1');
        $checks['database'] = true;
    } catch (\Exception $e) {
        \Log::error('Health check: Database failed', ['error' => $e->getMessage()]);
    }

    try {
        // Redis check
        Cache::store('redis')->put('health_check', true, 10);
        $checks['redis'] = Cache::store('redis')->get('health_check');
    } catch (\Exception $e) {
        \Log::error('Health check: Redis failed', ['error' => $e->getMessage()]);
    }

    try {
        // EventBookings API check
        $client = new GuzzleHttp\Client(['timeout' => 5]);
        $response = $client->get(config('eventbookings.identity_url'));
        $checks['eventbookings_api'] = $response->getStatusCode() === 200;
    } catch (\Exception $e) {
        \Log::error('Health check: EventBookings API failed', ['error' => $e->getMessage()]);
    }

    $healthy = array_reduce($checks, function($carry, $check) {
        return $carry && $check;
    }, true);

    return response()->json([
        'status' => $healthy ? 'healthy' : 'unhealthy',
        'checks' => $checks,
        'timestamp' => now()->toISOString(),
    ], $healthy ? 200 : 503);
});
```

#### System Monitoring Script

**File: `monitor.sh`**
```bash
#!/bin/bash

# System monitoring script
LOG_FILE="/var/log/eventbookings-monitor.log"
APP_URL="https://your-production-domain.com"

log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> $LOG_FILE
}

# Check application health
health_check() {
    response=$(curl -s -o /dev/null -w "%{http_code}" $APP_URL/api/health)
    if [ $response -eq 200 ]; then
        log_message "✅ Application health check passed"
    else
        log_message "❌ Application health check failed (HTTP $response)"
        # Send alert (email, Slack, etc.)
        # mail -s "EventBookings App Health Check Failed" admin@yourcompany.com < /dev/null
    fi
}

# Check disk usage
disk_check() {
    usage=$(df /var/www | tail -1 | awk '{print $5}' | sed 's/%//')
    if [ $usage -gt 80 ]; then
        log_message "⚠️ Disk usage is at $usage%"
        # Send alert
    fi
}

# Check memory usage
memory_check() {
    usage=$(free | grep Mem | awk '{printf("%.0f", $3/$2 * 100.0)}')
    if [ $usage -gt 90 ]; then
        log_message "⚠️ Memory usage is at $usage%"
        # Send alert
    fi
}

# Check log file sizes
log_size_check() {
    find /var/log -name "*.log" -size +100M -exec echo "⚠️ Large log file: {}" \; >> $LOG_FILE
}

# Run all checks
health_check
disk_check
memory_check
log_size_check

# Rotate log file if it gets too large
if [ -f $LOG_FILE ] && [ $(stat -f%z $LOG_FILE 2>/dev/null || stat -c%s $LOG_FILE) -gt 10485760 ]; then
    mv $LOG_FILE ${LOG_FILE}.old
    touch $LOG_FILE
fi
```

### Log Management

#### Logrotate Configuration

**File: `/etc/logrotate.d/eventbookings`**
```
/var/www/eventbookings-shopify-app/storage/logs/*.log {
    daily
    missingok
    rotate 14
    compress
    notifempty
    create 0644 www-data www-data
    postrotate
        systemctl reload php8.1-fpm
    endscript
}

/var/log/nginx/eventbookings-*.log {
    daily
    missingok
    rotate 30
    compress
    notifempty
    create 0644 www-data adm
    postrotate
        systemctl reload nginx
    endscript
}
```

### Performance Monitoring

#### PHP-FPM Pool Configuration

**File: `/etc/php/8.1/fpm/pool.d/eventbookings.conf`**
```ini
[eventbookings]
user = www-data
group = www-data
listen = /var/run/php/php8.1-fpm-eventbookings.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660

; Process management
pm = dynamic
pm.max_children = 20
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 10
pm.max_requests = 1000

; Performance
request_terminate_timeout = 300
request_slowlog_timeout = 10
slowlog = /var/log/php-fpm-slow.log

; Status page
pm.status_path = /status
ping.path = /ping

; Security
security.limit_extensions = .php

; Environment variables
env[APP_ENV] = production
env[CACHE_DRIVER] = redis
```

## Backup and Recovery

### Database Backup

**File: `backup-database.sh`**
```bash
#!/bin/bash

# Database backup script
DB_NAME="eventbookings_shopify_prod"
DB_USER="eventbookings_user"
DB_PASS="SECURE_PASSWORD"
BACKUP_DIR="/var/backups/mysql"
DATE=$(date +%Y%m%d_%H%M%S)

# Create backup directory
mkdir -p $BACKUP_DIR

# Create database dump
mysqldump -u$DB_USER -p$DB_PASS \
    --single-transaction \
    --routines \
    --triggers \
    --events \
    --hex-blob \
    $DB_NAME | gzip > $BACKUP_DIR/eventbookings_$DATE.sql.gz

# Upload to S3 (optional)
if command -v aws &> /dev/null; then
    aws s3 cp $BACKUP_DIR/eventbookings_$DATE.sql.gz s3://your-backup-bucket/database/
fi

# Clean old backups (keep last 7 days)
find $BACKUP_DIR -name "eventbookings_*.sql.gz" -mtime +7 -delete

echo "Database backup completed: eventbookings_$DATE.sql.gz"
```

### Full Application Backup

**File: `backup-full.sh`**
```bash
#!/bin/bash

# Full application backup script
APP_DIR="/var/www/eventbookings-shopify-app"
BACKUP_DIR="/var/backups/application"
DATE=$(date +%Y%m%d_%H%M%S)

# Create backup directory
mkdir -p $BACKUP_DIR

# Backup application files (excluding vendor and node_modules)
tar -czf $BACKUP_DIR/app_$DATE.tar.gz \
    -C $APP_DIR \
    --exclude='vendor' \
    --exclude='node_modules' \
    --exclude='.git' \
    --exclude='storage/logs/*.log' \
    .

# Backup uploaded files and storage
tar -czf $BACKUP_DIR/storage_$DATE.tar.gz -C $APP_DIR/storage .

# Upload to S3 (optional)
if command -v aws &> /dev/null; then
    aws s3 cp $BACKUP_DIR/app_$DATE.tar.gz s3://your-backup-bucket/application/
    aws s3 cp $BACKUP_DIR/storage_$DATE.tar.gz s3://your-backup-bucket/storage/
fi

echo "Application backup completed: app_$DATE.tar.gz, storage_$DATE.tar.gz"
```

### Automated Backup Cron Jobs

```bash
# Edit crontab
sudo crontab -e

# Add backup jobs
# Database backup every 6 hours
0 */6 * * * /var/www/eventbookings-shopify-app/scripts/backup-database.sh

# Full application backup daily at 2 AM
0 2 * * * /var/www/eventbookings-shopify-app/scripts/backup-full.sh

# System monitoring every 5 minutes
*/5 * * * * /var/www/eventbookings-shopify-app/scripts/monitor.sh
```

## Security Considerations

### Firewall Configuration

```bash
# Configure UFW firewall
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Allow SSH (change port if using non-standard)
sudo ufw allow 22/tcp

# Allow HTTP and HTTPS
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

# Enable firewall
sudo ufw enable
```

### Security Updates

```bash
# Create security update script
sudo nano /etc/cron.daily/security-updates

#!/bin/bash
apt update
apt upgrade -y --only-upgrade
apt autoremove -y
apt autoclean

# Restart services if needed
if [ -f /var/run/reboot-required ]; then
    echo "System reboot required" | mail -s "Server Reboot Required" admin@yourcompany.com
fi

# Make executable
sudo chmod +x /etc/cron.daily/security-updates
```

This comprehensive configuration and deployment guide provides everything needed to successfully deploy and maintain the EventBookings Shopify app in production while ensuring security, performance, and reliability.