# Deployment Guide

## Production Deployment

### 1. Environment Setup

```bash
# Set production environment
export APP_ENV=production

# Create necessary directories
mkdir -p logs invoices
chmod 755 logs invoices
```

### 2. Security Configuration

```php
// config/config.php - Production settings
return [
    'debug' => false,
    'security' => [
        'encryption_key' => 'generate_a_32_character_random_key_here',
        'session_timeout' => 3600,
        'max_login_attempts' => 5,
        'lockout_duration' => 900
    ]
];
```

### 3. Web Server Configuration

#### Apache with SSL

```apache
<VirtualHost *:443>
    ServerName yourdomain.com
    DocumentRoot /path/to/factur-x.point8.fr/admin
    
    SSLEngine on
    SSLCertificateFile /path/to/certificate.crt
    SSLCertificateKeyFile /path/to/private.key
    
    <Directory /path/to/factur-x.point8.fr/admin>
        AllowOverride All
        Require all granted
        
        # Restrict admin access by IP (optional)
        # Require ip 192.168.1.0/24
        # Require ip 203.0.113.0/24
    </Directory>
    
    # Security headers
    Header always set X-Frame-Options DENY
    Header always set X-Content-Type-Options nosniff
    Header always set X-XSS-Protection "1; mode=block"
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
    
    ErrorLog ${APACHE_LOG_DIR}/facturx_error.log
    CustomLog ${APACHE_LOG_DIR}/facturx_access.log combined
</VirtualHost>
```

#### Nginx with SSL

```nginx
server {
    listen 443 ssl http2;
    server_name yourdomain.com;
    root /path/to/factur-x.point8.fr/admin;
    index index.php;
    
    ssl_certificate /path/to/certificate.crt;
    ssl_certificate_key /path/to/private.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
    ssl_prefer_server_ciphers off;
    
    # Security headers
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";
    
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
    
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        
        # PHP security
        fastcgi_param HTTPS on;
        fastcgi_param SERVER_PORT 443;
    }
    
    # Deny access to sensitive files
    location ~ /\. {
        deny all;
    }
    
    location ~ /(config|logs|invoices)/ {
        deny all;
    }
}
```

### 4. Multi-Customer Deployment

#### Database Setup per Customer

```bash
# For each customer
mysql -u root -p

CREATE DATABASE customer1_orders CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'customer1_user'@'localhost' IDENTIFIED BY 'secure_password_1';
GRANT ALL PRIVILEGES ON customer1_orders.* TO 'customer1_user'@'localhost';

CREATE DATABASE customer2_orders CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'customer2_user'@'localhost' IDENTIFIED BY 'secure_password_2';
GRANT ALL PRIVILEGES ON customer2_orders.* TO 'customer2_user'@'localhost';
```

#### Customer Configuration Files

```php
// /customers/customer1/config/config.php
return [
    'database' => [
        'host' => 'localhost',
        'name' => 'customer1_orders',
        'user' => 'customer1_user',
        'password' => 'secure_password_1'
    ],
    'company' => [
        'name' => 'Customer 1 Company',
        'address' => 'Customer 1 Address',
        'siret' => '11111111111111'
    ]
];

// /customers/customer2/config/config.php
return [
    'database' => [
        'host' => 'localhost',
        'name' => 'customer2_orders',
        'user' => 'customer2_user',
        'password' => 'secure_password_2'
    ],
    'company' => [
        'name' => 'Customer 2 Company',
        'address' => 'Customer 2 Address',
        'siret' => '22222222222222'
    ]
];
```

### 5. Automated Deployment Script

```bash
#!/bin/bash
# deploy.sh

set -e

CUSTOMER_NAME=$1
if [ -z "$CUSTOMER_NAME" ]; then
    echo "Usage: $0 <customer_name>"
    exit 1
fi

echo "Deploying for customer: $CUSTOMER_NAME"

# Create customer directory
mkdir -p "/var/www/factur-x.point8.fr/customers/$CUSTOMER_NAME"

# Copy files
cp -r src admin examples "/var/www/factur-x.point8.fr/customers/$CUSTOMER_NAME/"

# Create config
cp config/config.example.php "/var/www/factur-x.point8.fr/customers/$CUSTOMER_NAME/config/config.php"

# Set permissions
chown -R www-data:www-data "/var/www/factur-x.point8.fr/customers/$CUSTOMER_NAME"
chmod -R 755 "/var/www/factur-x.point8.fr/customers/$CUSTOMER_NAME"

# Create directories
mkdir -p "/var/www/factur-x.point8.fr/customers/$CUSTOMER_NAME/logs"
mkdir -p "/var/www/factur-x.point8.fr/customers/$CUSTOMER_NAME/invoices"
chmod 755 "/var/www/factur-x.point8.fr/customers/$CUSTOMER_NAME/logs"
chmod 755 "/var/www/factur-x.point8.fr/customers/$CUSTOMER_NAME/invoices"

echo "Deployment completed for $CUSTOMER_NAME"
echo "Next steps:"
echo "1. Edit /var/www/factur-x.point8.fr/customers/$CUSTOMER_NAME/config/config.php"
echo "2. Import database schema"
echo "3. Configure web server for customer access"
```

### 6. Monitoring and Maintenance

#### Log Rotation

```bash
# /etc/logrotate.d/facturx
/var/www/factur-x.point8.fr/customers/*/logs/*.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    notifempty
    create 644 www-data www-data
}
```

#### Backup Script

```bash
#!/bin/bash
# backup.sh

BACKUP_DIR="/backup/factur-x"
DATE=$(date +%Y%m%d_%H%M%S)

mkdir -p "$BACKUP_DIR"

# Backup all customer databases
for customer_dir in /var/www/factur-x.point8.fr/customers/*/; do
    customer_name=$(basename "$customer_dir")
    config_file="$customer_dir/config/config.php"
    
    if [ -f "$config_file" ]; then
        # Extract database info from config
        db_name=$(php -r "include '$config_file'; echo \$config['database']['name'];")
        db_user=$(php -r "include '$config_file'; echo \$config['database']['user'];")
        db_pass=$(php -r "include '$config_file'; echo \$config['database']['password'];")
        
        # Backup database
        mysqldump -u "$db_user" -p"$db_pass" "$db_name" > "$BACKUP_DIR/${customer_name}_${DATE}.sql"
        
        # Backup files
        tar -czf "$BACKUP_DIR/${customer_name}_files_${DATE}.tar.gz" -C "$customer_dir" invoices logs
    fi
done

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

echo "Backup completed: $DATE"
```

### 7. Performance Optimization

#### Database Optimization

```sql
-- Add indexes for better performance
CREATE INDEX idx_orders_customer_status ON orders(customer_name, status);
CREATE INDEX idx_orders_date_range ON orders(created_at, status);
CREATE INDEX idx_invoices_date_range ON invoices(invoice_date, status);
```

#### PHP Configuration

```ini
; php.ini optimizations
memory_limit = 256M
max_execution_time = 300
upload_max_filesize = 10M
post_max_size = 10M
opcache.enable = 1
opcache.memory_consumption = 128
opcache.max_accelerated_files = 4000
```

### 8. Security Checklist

- [ ] HTTPS enabled with valid SSL certificate
- [ ] Database passwords are strong and unique
- [ ] Admin panel access restricted by IP if needed
- [ ] Regular security updates applied
- [ ] File permissions properly configured
- [ ] Backup system in place and tested
- [ ] Error logging enabled and monitored
- [ ] Rate limiting configured
- [ ] Input validation working correctly
- [ ] Audit trail logging enabled

### 9. Troubleshooting Common Issues

#### Database Connection Issues
```bash
# Test database connection
mysql -u username -p database_name -e "SELECT 1"

# Check MySQL logs
tail -f /var/log/mysql/error.log
```

#### Permission Issues
```bash
# Check file permissions
ls -la /var/www/factur-x.point8.fr/customers/

# Fix permissions
chown -R www-data:www-data /var/www/factur-x.point8.fr/customers/
chmod -R 755 /var/www/factur-x.point8.fr/customers/
```

#### Performance Issues
```bash
# Check MySQL performance
mysql -u root -p -e "SHOW PROCESSLIST"

# Enable slow query log
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL slow_query_log_file = '/var/log/mysql/slow.log';
SET GLOBAL long_query_time = 1;
```
