# Main Nginx Configuration File
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    # Include additional configuration files
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # Log settings
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    # Gzip settings (optional)
    gzip on;
    gzip_types text/plain application/xml text/css application/javascript;

    # Include server block configurations
    include /etc/nginx/conf.d/*.conf;

    # Redirect HTTP to HTTPS
    server {
        listen 80;
        server_name nnks.truckwash.dk;

        return 301 https://$host$request_uri;
    }

    server {
        listen 443 ssl;
        server_name nnks.truckwash.dk;

        ssl_certificate /etc/letsencrypt/live/nnks.truckwash.dk/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/nnks.truckwash.dk/privkey.pem;

        root /var/www/html;
        index index.html index.htm index.php;

        # Enable SSL options
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_prefer_server_ciphers on;

        # Logging
        error_log /var/log/nginx/error.log;
        access_log /var/log/nginx/access.log combined;

        # Add CORS headers
        location / {
              add_header Access-Control-Allow-Origin *;
              add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
              add_header Access-Control-Allow-Headers "Authorization, Content-Type, X-Requested-With, X-Customer-Number";
              add_header Access-Control-Allow-Credentials true;

              # If OPTIONS method is needed for preflight
              if ($request_method = 'OPTIONS') {
                  add_header Access-Control-Allow-Origin *;
                  add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
                  add_header Access-Control-Allow-Headers "Authorization, Content-Type, X-Requested-With, X-Customer-Number";
                  return 204; # No Content
              }

              # Run the index.php file, no matter what the request URI is
                try_files $uri $uri/ /index.php?$query_string;
        }

        # Location for PHP (using PHP 8.2)
        location ~ \.php$ {
            include fastcgi_params;
            fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        }

        # Location for static files
        location ~* \.(cgi|shtml|phtml)$ {
            # Additional SSL options or configurations can be placed here, if necessary.
        }
    }
}