# ==================================================
# WhatsApp Bot Manager - HestiaCP Compatible .htaccess
# Optimizado para hosting compartido y VPS con HestiaCP
# ==================================================

# Configuración básica de seguridad
ServerSignature Off

# Desactivar listado de directorios
Options -Indexes

# Activar RewriteEngine
RewriteEngine On

# ==================================================
# PROTECCIÓN DE ARCHIVOS CRÍTICOS
# ==================================================

# Proteger archivos de configuración (compatible con HestiaCP)
<FilesMatch "^(config|database|\.env).*\.(php|ini|conf)$">
    Require all denied
</FilesMatch>

# Proteger archivos sensibles
<FilesMatch "\.(log|sql|md|txt|json|lock)$">
    <RequireAll>
        Require ip 127.0.0.1
        Require ip ::1
    </RequireAll>
</FilesMatch>

# Proteger archivos de instalación después de completada
<IfModule mod_rewrite.c>
    RewriteCond %{REQUEST_FILENAME} install.*\.php$ [NC]
    RewriteCond %{REMOTE_ADDR} !^127\.0\.0\.1$
    RewriteCond %{REMOTE_ADDR} !^::1$
    RewriteRule .* - [F,L]
</IfModule>

# Proteger archivos dot (ocultos)
<FilesMatch "^\.|\.bak$|\.old$|\.orig$|\.save$|\.swp$|\.tmp$">
    Require all denied
</FilesMatch>

# ==================================================
# PROTECCIÓN DE DIRECTORIOS
# ==================================================

# Proteger directorio de logs
<IfModule mod_alias.c>
    RedirectMatch 403 ^/logs/.*$
</IfModule>

# Proteger directorio de tests (si existe)
<IfModule mod_alias.c>
    RedirectMatch 403 ^/tests/.*$
</IfModule>

# ==================================================
# HEADERS DE SEGURIDAD (Compatible HestiaCP)
# ==================================================

<IfModule mod_headers.c>
    # Prevenir clickjacking
    Header always set X-Frame-Options "SAMEORIGIN"
    
    # Prevenir XSS
    Header always set X-XSS-Protection "1; mode=block"
    
    # Prevenir MIME sniffing
    Header always set X-Content-Type-Options "nosniff"
    
    # Política de referrer
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    
    # Content Security Policy básica
    Header always set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' cdn.jsdelivr.net cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline' cdn.jsdelivr.net cdnjs.cloudflare.com; font-src 'self' cdnjs.cloudflare.com; img-src 'self' data:; connect-src 'self';"
    
    # Permissions Policy
    Header always set Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=(), usb=(), autoplay=(), fullscreen=()"
</IfModule>

# ==================================================
# OPTIMIZACIÓN DE RENDIMIENTO
# ==================================================

# Compresión GZIP (compatible HestiaCP)
<IfModule mod_deflate.c>
    <FilesMatch "\.(html|htm|php|css|js|xml|txt|json)$">
        SetOutputFilter DEFLATE
    </FilesMatch>
    
    # Excluir archivos ya comprimidos
    <FilesMatch "\.(zip|gz|rar|7z|jpg|jpeg|png|gif|webp|mp4|mp3|pdf)$">
        SetEnv no-gzip
    </FilesMatch>
</IfModule>

# Cache estático (HestiaCP compatible)
<IfModule mod_expires.c>
    ExpiresActive On
    
    # Archivos CSS y JavaScript
    <FilesMatch "\.(css|js)$">
        ExpiresDefault "access plus 1 month"
    </FilesMatch>
    
    # Imágenes
    <FilesMatch "\.(jpg|jpeg|png|gif|webp|svg|ico)$">
        ExpiresDefault "access plus 6 months"
    </FilesMatch>
    
    # Fuentes
    <FilesMatch "\.(woff|woff2|ttf|eot)$">
        ExpiresDefault "access plus 1 year"
    </FilesMatch>
</IfModule>

# ==================================================
# REGLAS DE REWRITE (HestiaCP)
# ==================================================

# Redirigir HTTP a HTTPS (descomentear en producción)
# RewriteCond %{HTTPS} off
# RewriteCond %{HTTP_HOST} !^localhost [NC]
# RewriteCond %{HTTP_HOST} !^127\.0\.0\.1 [NC]
# RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Redirigir www a no-www (opcional, descomentear si necesario)
# RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
# RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

# Página de inicio personalizada
DirectoryIndex index.php index.html

# ==================================================
# PROTECCIÓN CONTRA ATAQUES COMUNES
# ==================================================

# Bloquear injection attempts
<IfModule mod_rewrite.c>
    # Bloquear SQL injection
    RewriteCond %{QUERY_STRING} (union|select|insert|delete|drop|create|update|or|and) [NC]
    RewriteRule .* - [F,L]
    
    # Bloquear XSS
    RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC]
    RewriteRule .* - [F,L]
    
    # Bloquear file injection
    RewriteCond %{QUERY_STRING} \.\.\/ [NC]
    RewriteRule .* - [F,L]
    
    # Bloquear acceso a wp-admin (si no es WordPress)
    RewriteCond %{REQUEST_URI} wp-admin [NC]
    RewriteRule .* - [F,L]
</IfModule>

# Limitar tamaño de subida (HestiaCP compatible)
<IfModule mod_php.c>
    php_value upload_max_filesize 10M
    php_value post_max_size 10M
    php_value max_execution_time 300
    php_value max_input_vars 3000
</IfModule>

# Para PHP-FPM en HestiaCP
<IfModule mod_fcgid.c>
    FcgidMaxRequestLen 10485760
</IfModule>

# ==================================================
# CONFIGURACIÓN ESPECÍFICA DE APIs
# ==================================================

# Headers para APIs JSON
<FilesMatch "^(api)/.*\.php$">
    <IfModule mod_headers.c>
        Header always set Content-Type "application/json; charset=utf-8"
        Header always set Access-Control-Allow-Origin "*"
        Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
        Header always set Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With"
    </IfModule>
</FilesMatch>

# Webhook específico para WhatsApp
<Files "webhook.php">
    <IfModule mod_headers.c>
        Header always set Access-Control-Allow-Origin "*"
        Header always set Access-Control-Allow-Methods "GET, POST"
    </IfModule>
</Files>

# ==================================================
# CONFIGURACIÓN DE ERRORES PERSONALIZADA
# ==================================================

# Páginas de error personalizadas (opcional)
# ErrorDocument 404 /404.html
# ErrorDocument 500 /500.html
# ErrorDocument 403 /403.html

# Ocultar información del servidor
ServerTokens Prod

# Configuración de charset por defecto
AddDefaultCharset UTF-8