# Deployment Guide

This guide provides step-by-step instructions for deploying the Shopify Order Sender app to production.

## Pre-Deployment Checklist

- [ ] Domain with SSL certificate configured
- [ ] MySQL database created
- [ ] Shopify Partner account with app created
- [ ] Target domain API endpoints implemented
- [ ] Server with PHP 8.1+ and required extensions

## Server Requirements

### PHP Extensions Required
```bash
sudo apt update
sudo apt install -y php php-cli php-fpm php-json php-common php-mysql php-zip php-gd php-mbstring php-curl php-xml php-pear php-bcmath
```

### MySQL Setup
```bash
sudo apt install -y mysql-server
sudo mysql_secure_installation
```

Create database:
```sql
CREATE DATABASE shopify_order_sender;
CREATE USER 'shopify_user'@'localhost' IDENTIFIED BY 'secure_password';
GRANT ALL PRIVILEGES ON shopify_order_sender.* TO 'shopify_user'@'localhost';
FLUSH PRIVILEGES;
```

## Deployment Steps

### 1. Upload Application Files

```bash
# Clone repository
git clone <repository-url> /var/www/shopify-order-sender
cd /var/www/shopify-order-sender

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

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

### 2. Environment Configuration

```bash
# Copy environment file
cp .env.example .env

# Generate application key
php artisan key:generate
```

Update `.env` with production values:
```env
APP_NAME="Shopify Order Sender"
APP_ENV=production
APP_DEBUG=false
APP_URL=https://your-domain.com

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=shopify_order_sender
DB_USERNAME=shopify_user
DB_PASSWORD=secure_password

SHOPIFY_API_KEY=your_production_api_key
SHOPIFY_API_SECRET=your_production_api_secret
SHOPIFY_WEBHOOK_SECRET=your_webhook_secret
SHOPIFY_SCOPES=read_orders,read_customers

LOG_CHANNEL=daily
LOG_LEVEL=error
```

### 3. Database Migration

```bash
php artisan migrate --force
```

### 4. Web Server Configuration

#### Apache Configuration

Create virtual host file `/etc/apache2/sites-available/shopify-order-sender.conf`:

```apache
<VirtualHost *:80>
    ServerName your-domain.com
    DocumentRoot /var/www/shopify-order-sender/public
    
    <Directory /var/www/shopify-order-sender/public>
        AllowOverride All
        Require all granted
    </Directory>
    
    ErrorLog ${APACHE_LOG_DIR}/shopify-order-sender_error.log
    CustomLog ${APACHE_LOG_DIR}/shopify-order-sender_access.log combined
</VirtualHost>

<VirtualHost *:443>
    ServerName your-domain.com
    DocumentRoot /var/www/shopify-order-sender/public
    
    SSLEngine on
    SSLCertificateFile /path/to/your/certificate.crt
    SSLCertificateKeyFile /path/to/your/private.key
    
    <Directory /var/www/shopify-order-sender/public>
        AllowOverride All
        Require all granted
    </Directory>
    
    ErrorLog ${APACHE_LOG_DIR}/shopify-order-sender_ssl_error.log
    CustomLog ${APACHE_LOG_DIR}/shopify-order-sender_ssl_access.log combined
</VirtualHost>
```

Enable site and modules:
```bash
sudo a2ensite shopify-order-sender
sudo a2enmod rewrite ssl
sudo systemctl restart apache2
```

#### Nginx Configuration

Create configuration file `/etc/nginx/sites-available/shopify-order-sender`:

```nginx
server {
    listen 80;
    server_name your-domain.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name your-domain.com;
    root /var/www/shopify-order-sender/public;
    index index.php;

    ssl_certificate /path/to/your/certificate.crt;
    ssl_certificate_key /path/to/your/private.key;

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

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

    location ~ /\.ht {
        deny all;
    }
}
```

Enable site:
```bash
sudo ln -s /etc/nginx/sites-available/shopify-order-sender /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
```

### 5. SSL Certificate Setup

#### Using Let's Encrypt (Recommended)

```bash
sudo apt install certbot python3-certbot-apache
sudo certbot --apache -d your-domain.com
```

For Nginx:
```bash
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your-domain.com
```

### 6. Shopify App Configuration

In your Shopify Partner dashboard:

1. **App URLs:**
   - App URL: `https://your-domain.com/auth/install`
   - Allowed redirection URLs: `https://your-domain.com/auth/callback`

2. **Webhooks:**
   - Order creation: `https://your-domain.com/webhooks/orders/create`
   - App uninstalled: `https://your-domain.com/webhooks/app/uninstalled`

3. **App Scopes:**
   - `read_orders`
   - `read_customers`

### 7. Optimization

#### Cache Configuration
```bash
php artisan config:cache
php artisan route:cache
php artisan view:cache
```

#### Queue Setup (Optional)
For better performance, set up queues:

```bash
# Install supervisor
sudo apt install supervisor

# Create queue worker configuration
sudo nano /etc/supervisor/conf.d/shopify-order-sender.conf
```

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

Start supervisor:
```bash
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start shopify-order-sender-worker:*
```

## Post-Deployment Testing

### 1. Test App Installation
Visit: `https://your-domain.com/auth/install?shop=test-store.myshopify.com`

### 2. Test Webhook Endpoints
```bash
# Test webhook endpoint
curl -X POST https://your-domain.com/webhooks/orders/create \
  -H "Content-Type: application/json" \
  -H "X-Shopify-Shop-Domain: test-store.myshopify.com" \
  -H "X-Shopify-Hmac-Sha256: test-hmac" \
  -d '{"test": "data"}'
```

### 3. Monitor Logs
```bash
tail -f /var/www/shopify-order-sender/storage/logs/laravel.log
```

## Maintenance

### Regular Tasks

1. **Log Rotation**
   ```bash
   # Add to crontab
   0 0 * * * cd /var/www/shopify-order-sender && php artisan log:clear
   ```

2. **Database Backup**
   ```bash
   # Daily backup script
   #!/bin/bash
   mysqldump -u shopify_user -p shopify_order_sender > /backup/shopify_$(date +%Y%m%d).sql
   ```

3. **SSL Certificate Renewal**
   ```bash
   # Auto-renewal with cron
   0 12 * * * /usr/bin/certbot renew --quiet
   ```

### Updates

1. **Application Updates**
   ```bash
   cd /var/www/shopify-order-sender
   git pull origin main
   composer install --optimize-autoloader --no-dev
   php artisan migrate --force
   php artisan config:cache
   php artisan route:cache
   php artisan view:cache
   ```

2. **Security Updates**
   ```bash
   sudo apt update && sudo apt upgrade
   composer update
   ```

## Monitoring

### Health Checks

Create a health check endpoint by adding to `routes/web.php`:
```php
Route::get('/health', function () {
    return response()->json([
        'status' => 'ok',
        'timestamp' => now(),
        'database' => DB::connection()->getPdo() ? 'connected' : 'disconnected'
    ]);
});
```

### Log Monitoring

Set up log monitoring with tools like:
- ELK Stack (Elasticsearch, Logstash, Kibana)
- Splunk
- Datadog
- New Relic

## Troubleshooting

### Common Issues

1. **Permission Errors**
   ```bash
   sudo chown -R www-data:www-data /var/www/shopify-order-sender
   sudo chmod -R 755 /var/www/shopify-order-sender
   sudo chmod -R 775 /var/www/shopify-order-sender/storage
   ```

2. **Database Connection Issues**
   - Check MySQL service status
   - Verify database credentials
   - Test connection manually

3. **SSL Certificate Issues**
   ```bash
   sudo certbot certificates
   sudo certbot renew --dry-run
   ```

4. **Webhook Delivery Issues**
   - Check Shopify webhook delivery logs
   - Verify webhook URL accessibility
   - Test HMAC verification

### Emergency Procedures

1. **Rollback Deployment**
   ```bash
   git checkout previous-stable-tag
   composer install --optimize-autoloader --no-dev
   php artisan migrate:rollback
   ```

2. **Disable App Temporarily**
   ```bash
   # Set maintenance mode
   php artisan down --message="Maintenance in progress"
   
   # Re-enable
   php artisan up
   ```

## Security Checklist

- [ ] HTTPS enabled with valid SSL certificate
- [ ] Database credentials secured
- [ ] File permissions properly set
- [ ] Debug mode disabled in production
- [ ] Webhook HMAC verification enabled
- [ ] Regular security updates applied
- [ ] Access logs monitored
- [ ] Firewall configured
- [ ] Backup strategy implemented

## Support

For deployment issues:
1. Check server logs
2. Verify all configuration settings
3. Test individual components
4. Review Shopify Partner dashboard for errors

