# Apache Virtual Host Configuration for Multi-Tenant Subdomain Routing
# Customer Communication Automation Platform
# 
# This configuration enables subdomain-based tenant isolation
# Each customer accesses their instance via: businessname.automation.proviska.com

# ===================================================================
# WILDCARD SSL CERTIFICATE REQUIRED
# ===================================================================
# You need a wildcard SSL certificate for *.automation.proviska.com
# Or use Let's Encrypt with DNS validation for wildcard support

# ===================================================================
# MAIN VIRTUAL HOST - Handles all subdomains
# ===================================================================
<VirtualHost *:443>
    # Wildcard server name to catch all subdomains
    ServerName automation.proviska.com
    ServerAlias *.automation.proviska.com
    
    # Document root
    DocumentRoot /var/www/html/proviska-ai
    
    # SSL Configuration
    SSLEngine on
    SSLCertificateFile /etc/ssl/certs/automation.proviska.com.crt
    SSLCertificateKeyFile /etc/ssl/private/automation.proviska.com.key
    SSLCertificateChainFile /etc/ssl/certs/automation.proviska.com.chain.crt
    
    # Security Headers
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
    Header always set X-Content-Type-Options "nosniff"
    Header always set X-Frame-Options "SAMEORIGIN"
    Header always set X-XSS-Protection "1; mode=block"
    Header always set Content-Security-Policy "default-src 'self' https:; script-src 'self' 'unsafe-inline' https:; style-src 'self' 'unsafe-inline' https:;"
    
    # PHP Configuration
    <FilesMatch \.php$>
        SetHandler "proxy:unix:/var/run/php/php8.2-fpm.sock|fcgi://localhost"
    </FilesMatch>
    
    # API Directory Configuration
    <Directory /var/www/html/proviska-ai/api>
        Options -Indexes +FollowSymLinks
        AllowOverride None
        Require all granted
        
        # Enable CORS for API endpoints
        Header always set Access-Control-Allow-Origin "https://*.automation.proviska.com"
        Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
        Header always set Access-Control-Allow-Headers "Content-Type, Authorization, X-CSRF-Token"
        Header always set Access-Control-Max-Age "3600"
        
        # Handle OPTIONS requests for CORS preflight
        RewriteEngine On
        RewriteCond %{REQUEST_METHOD} OPTIONS
        RewriteRule ^(.*)$ $1 [R=200,L]
    </Directory>
    
    # Subdomain Extraction and Validation
    RewriteEngine On
    
    # Extract subdomain and pass to PHP
    RewriteCond %{HTTP_HOST} ^([a-z0-9-]+)\.automation\.proviska\.com$ [NC]
    RewriteRule ^(.*)$ - [E=SUBDOMAIN:%1]
    
    # Pass subdomain to PHP via server variable
    SetEnvIf Host "^([a-z0-9-]+)\.automation\.proviska\.com$" BUSINESS_SUBDOMAIN=$1
    
    # Redirect root domain to login or marketing page
    RewriteCond %{HTTP_HOST} ^automation\.proviska\.com$ [NC]
    RewriteRule ^$ /login.php [L]
    
    # Block access to sensitive directories
    <DirectoryMatch "^/var/www/html/proviska-ai/(database|scripts|lib|config)">
        Require all denied
    </DirectoryMatch>
    
    # Logging with subdomain information
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" subdomain:%{BUSINESS_SUBDOMAIN}e" subdomain_combined
    CustomLog /var/log/apache2/automation-access.log subdomain_combined
    ErrorLog /var/log/apache2/automation-error.log
    
    # Performance optimizations
    <IfModule mod_deflate.c>
        AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json
    </IfModule>
    
    <IfModule mod_expires.c>
        ExpiresActive On
        ExpiresByType image/jpg "access plus 1 month"
        ExpiresByType image/jpeg "access plus 1 month"
        ExpiresByType image/gif "access plus 1 month"
        ExpiresByType image/png "access plus 1 month"
        ExpiresByType text/css "access plus 1 week"
        ExpiresByType application/javascript "access plus 1 week"
    </IfModule>
</VirtualHost>

# ===================================================================
# HTTP TO HTTPS REDIRECT
# ===================================================================
<VirtualHost *:80>
    ServerName automation.proviska.com
    ServerAlias *.automation.proviska.com
    
    # Redirect all HTTP traffic to HTTPS
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]
</VirtualHost>

# ===================================================================
# NGINX CONFIGURATION ALTERNATIVE
# ===================================================================
# If using Nginx instead of Apache, use this configuration:

# server {
#     listen 443 ssl http2;
#     server_name *.automation.proviska.com;
#     
#     # SSL Configuration
#     ssl_certificate /etc/ssl/certs/automation.proviska.com.crt;
#     ssl_certificate_key /etc/ssl/private/automation.proviska.com.key;
#     
#     # Security Headers
#     add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
#     add_header X-Content-Type-Options "nosniff" always;
#     add_header X-Frame-Options "SAMEORIGIN" always;
#     add_header X-XSS-Protection "1; mode=block" always;
#     
#     root /var/www/html/proviska-ai;
#     index index.php;
#     
#     # Extract subdomain
#     set $subdomain "";
#     if ($host ~* ^([a-z0-9-]+)\.automation\.proviska\.com$) {
#         set $subdomain $1;
#     }
#     
#     # Pass subdomain to PHP
#     location ~ \.php$ {
#         fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
#         fastcgi_index index.php;
#         fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
#         fastcgi_param BUSINESS_SUBDOMAIN $subdomain;
#         include fastcgi_params;
#     }
#     
#     # API endpoints
#     location /api {
#         try_files $uri $uri/ /api/index.php?$query_string;
#         
#         # CORS headers
#         add_header Access-Control-Allow-Origin "https://*.automation.proviska.com" always;
#         add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always;
#         add_header Access-Control-Allow-Headers "Content-Type, Authorization, X-CSRF-Token" always;
#         
#         if ($request_method = 'OPTIONS') {
#             return 204;
#         }
#     }
#     
#     # Block sensitive directories
#     location ~ ^/(database|scripts|lib|config)/ {
#         deny all;
#     }
#     
#     # Logging
#     access_log /var/log/nginx/automation-access.log combined;
#     error_log /var/log/nginx/automation-error.log;
# }
# 
# # HTTP to HTTPS redirect
# server {
#     listen 80;
#     server_name *.automation.proviska.com;
#     return 301 https://$host$request_uri;
# }

# ===================================================================
# DNS CONFIGURATION REQUIREMENTS
# ===================================================================
# Add these DNS records to your domain:
# 
# 1. A record for main domain:
#    automation.proviska.com -> YOUR_SERVER_IP
# 
# 2. Wildcard A record for subdomains:
#    *.automation.proviska.com -> YOUR_SERVER_IP
# 
# 3. Optional: CNAME records for specific customers (more control):
#    acmecorp.automation.proviska.com -> automation.proviska.com
#    techstart.automation.proviska.com -> automation.proviska.com

# ===================================================================
# ENABLE CONFIGURATION
# ===================================================================
# For Apache:
# sudo a2ensite automation-subdomain
# sudo systemctl reload apache2
# 
# For Nginx:
# sudo ln -s /etc/nginx/sites-available/automation-subdomain /etc/nginx/sites-enabled/
# sudo nginx -t
# sudo systemctl reload nginx