##############################################################
# GMLM Platform — Nginx Configuration
# Handles HTTP→HTTPS redirect, SSL termination,
# static asset caching, and PHP-FPM proxy.
##############################################################

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid       /var/run/nginx.pid;

events {
    worker_connections 1024;
    use epoll;
    multi_accept on;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    # ── Logging ─────────────────────────────────────────────
    log_format main '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent" '
                    'rt=$request_time';

    access_log /var/log/nginx/access.log main;

    # ── Performance ──────────────────────────────────────────
    sendfile           on;
    tcp_nopush         on;
    tcp_nodelay        on;
    keepalive_timeout  65;
    types_hash_max_size 2048;
    client_max_body_size 50M;
    server_tokens      off;

    # ── Gzip Compression ─────────────────────────────────────
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types
        text/plain text/css text/xml text/javascript
        application/json application/javascript application/xml
        application/rss+xml font/truetype font/opentype
        image/svg+xml;

    # ── Rate Limiting Zones ───────────────────────────────────
    limit_req_zone  $binary_remote_addr zone=api:10m    rate=60r/m;
    limit_req_zone  $binary_remote_addr zone=login:10m  rate=10r/m;
    limit_req_zone  $binary_remote_addr zone=general:10m rate=120r/m;
    limit_conn_zone $binary_remote_addr zone=perip:10m;

    # ── FastCGI Cache ─────────────────────────────────────────
    fastcgi_cache_path /tmp/nginx-cache levels=1:2 keys_zone=GMLM:10m max_size=100m inactive=60m;
    fastcgi_cache_key  "$scheme$request_method$host$request_uri";

    # ── HTTP → HTTPS Redirect ────────────────────────────────
    server {
        listen 80;
        server_name _;

        location /.well-known/acme-challenge/ {
            root /var/www/certbot;
        }

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

    # ── HTTPS Application Server ──────────────────────────────
    server {
        listen 443 ssl http2;
        server_name _;

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

        # ── SSL ──────────────────────────────────────────────
        ssl_certificate     /etc/nginx/certs/fullchain.pem;
        ssl_certificate_key /etc/nginx/certs/privkey.pem;
        ssl_session_timeout 1d;
        ssl_session_cache   shared:SSL:50m;
        ssl_session_tickets off;

        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers   ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
        ssl_prefer_server_ciphers off;

        # HSTS (1 year — only enable after SSL is confirmed working)
        # add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

        # ── 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 Permissions-Policy        "geolocation=(), microphone=(), camera=()" always;
        add_header Content-Security-Policy
            "default-src 'self';
             script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdnjs.cloudflare.com;
             style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
             font-src 'self' https://fonts.gstatic.com;
             img-src 'self' data: blob: https:;
             connect-src 'self';
             frame-ancestors 'none';"
            always;

        # ── Static Asset Caching ──────────────────────────────
        location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot|webp|avif)$ {
            expires     1y;
            add_header  Cache-Control "public, immutable";
            add_header  Vary Accept-Encoding;
            access_log  off;
            log_not_found off;
        }

        # ── Media / Uploads (private — never serve directly) ─
        location ~ ^/storage/app/private {
            deny all;
            return 403;
        }

        location ~ ^/storage/app/kyc {
            deny all;
            return 403;
        }

        # ── Block sensitive files ─────────────────────────────
        location ~ /\.(env|git|htaccess|dockerignore) {
            deny all;
            return 404;
        }

        location ~ /\.(DS_Store|idea|vscode) {
            deny all;
            return 404;
        }

        # ── API Rate Limiting ─────────────────────────────────
        location /api/v1/auth/login {
            limit_req zone=login burst=5 nodelay;
            limit_req_status 429;
            try_files $uri $uri/ /index.php?$query_string;
        }

        location /api/ {
            limit_req zone=api burst=20 nodelay;
            limit_req_status 429;
            try_files $uri $uri/ /index.php?$query_string;
        }

        # ── Main Laravel Handler ──────────────────────────────
        location / {
            limit_req zone=general burst=50 nodelay;
            limit_conn perip 20;

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

        # ── PHP-FPM ───────────────────────────────────────────
        location ~ \.php$ {
            fastcgi_pass  127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_buffers 16 16k;
            fastcgi_buffer_size 32k;
            fastcgi_read_timeout 120;

            include       fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
            fastcgi_param DOCUMENT_ROOT   $realpath_root;

            # Hide PHP version
            fastcgi_hide_header X-Powered-By;
        }

        # ── Health check endpoint (no auth, no logging) ───────
        location = /api/v1/health {
            access_log off;
            try_files $uri /index.php?$query_string;
        }

        # ── Deny hidden files ─────────────────────────────────
        location ~ /\.(?!well-known) {
            deny all;
        }

        error_page 404 /index.php;
    }
}
