# ============================================================
# Club Palestino CRM v2.0 — Configuración Nginx Segura
# /etc/nginx/sites-available/clubpalestino
# ============================================================

# Redirección HTTP → HTTPS
server {
    listen 80;
    listen [::]:80;
    server_name sociosclubpalestino.cl www.sociosclubpalestino.cl;
    return 301 https://$host$request_uri;
}

# Servidor principal HTTPS
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name sociosclubpalestino.cl www.sociosclubpalestino.cl;

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

    # ── TLS / SSL ──────────────────────────────────────────────
    ssl_certificate     /etc/letsencrypt/live/sociosclubpalestino.cl/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/sociosclubpalestino.cl/privkey.pem;
    ssl_session_timeout 1d;
    ssl_session_cache   shared:SSL:50m;
    ssl_session_tickets off;

    # TLS 1.2 y 1.3 solamente
    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:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers off;

    # HSTS (6 meses)
    add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload" always;

    # ── HEADERS DE SEGURIDAD ───────────────────────────────────
    add_header X-Content-Type-Options     "nosniff"                  always;
    add_header X-Frame-Options            "SAMEORIGIN"               always;
    add_header X-XSS-Protection           "1; mode=block"            always;
    add_header Referrer-Policy            "strict-origin-when-cross-origin" always;
    add_header Permissions-Policy         "camera=(), microphone=(), geolocation=()" always;
    add_header Content-Security-Policy    "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https://api.anthropic.com https://live-server.wati.io https://mindicador.cl; font-src 'self'; frame-ancestors 'self';" always;

    # ── RATE LIMITING ──────────────────────────────────────────
    # Definir zonas en nginx.conf:
    # limit_req_zone $binary_remote_addr zone=api:10m rate=30r/m;
    # limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
    # limit_req_zone $binary_remote_addr zone=general:10m rate=100r/m;

    location /api/ {
        limit_req zone=api burst=10 nodelay;
        limit_req_status 429;
        try_files $uri $uri/ /api/index.php?$query_string;
        include snippets/php-fpm.conf;
    }

    location ~ /api/(seguridad|login)\.php {
        limit_req zone=login burst=3 nodelay;
        limit_req_status 429;
        include snippets/php-fpm.conf;
    }

    # ── PORTAL PWA ─────────────────────────────────────────────
    location /portal/ {
        try_files $uri $uri/ /portal/index.html;

        # Cache para assets estáticos del PWA
        location ~* \.(js|css|png|jpg|svg|ico|woff2)$ {
            expires 30d;
            add_header Cache-Control "public, immutable";
        }

        # Service Worker no cacheable
        location = /portal/sw.js {
            add_header Cache-Control "no-cache, no-store, must-revalidate";
            add_header Pragma "no-cache";
        }
    }

    # ── PHP ────────────────────────────────────────────────────
    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_read_timeout 300;

        # Parámetros de seguridad PHP
        fastcgi_param PHP_VALUE "
            expose_php = Off
            display_errors = Off
            log_errors = On
            error_log = /var/log/clubpalestino/php_errors.log
            session.cookie_secure = 1
            session.cookie_httponly = 1
            session.cookie_samesite = Strict
            session.use_strict_mode = 1
            session.gc_maxlifetime = 28800
        ";
    }

    # ── ARCHIVOS SENSIBLES — BLOQUEAR ──────────────────────────
    location ~ /\. { deny all; }
    location ~ \.env { deny all; }
    location ~ /\.git { deny all; }
    location ~ /backup { deny all; }
    location ~ /storage/logs { deny all; }
    location ~ \.(sql|sh|key|pfx|p12)$ { deny all; }

    # ── ACCESO SOLO A ARCHIVOS PHP Y ESTÁTICOS ─────────────────
    location / {
        try_files $uri $uri/ /index.php?$query_string;
        limit_req zone=general burst=20 nodelay;
    }

    # ── LOGS ───────────────────────────────────────────────────
    access_log /var/log/nginx/clubpalestino_access.log combined;
    error_log  /var/log/nginx/clubpalestino_error.log warn;

    # ── GZIP ───────────────────────────────────────────────────
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript text/xml;

    # ── TAMAÑO MÁXIMO UPLOAD ───────────────────────────────────
    client_max_body_size 20M; # Para carga de CAF, documentos, etc.
}
