# ============================================
# .htaccess - CGN Autocenter System
# Configurações de segurança, rewrite e desempenho
# ============================================

# ============================================
# CONFIGURAÇÕES BÁSICAS
# ============================================

# Ativar Rewrite Engine
RewriteEngine On

# Base URL (ajuste conforme necessário)
# RewriteBase /cgnautocenter/

# Definir charset padrão
AddDefaultCharset UTF-8

# ============================================
# SEGURANÇA
# ============================================

# Impedir listagem de diretórios
Options -Indexes

# Proteger arquivos sensíveis
<FilesMatch "\.(sql|log|ini|env|config|json|lock|md|bak|backup|old|swp|sh|zip|rar|tar|gz)$">
    Order allow,deny
    Deny from all
</FilesMatch>

# Proteger arquivos do sistema
<FilesMatch "(composer\.|package\.|web\.config|php\.ini|\.htaccess|\.htpasswd)">
    Order allow,deny
    Deny from all
</FilesMatch>

# Proteger diretórios sensíveis
<IfModule mod_authz_core.c>
    <DirectoryMatch "^.*/(config|includes|backups|vendor|storage|logs)/">
        Require all denied
    </DirectoryMatch>
</IfModule>

# Prevenir acesso a arquivos ocultos
RedirectMatch 404 /\..*$

# Proteger contra SQL Injection e XSS (filtro básico)
<IfModule mod_rewrite.c>
    RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
    RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
    RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
    RewriteRule .* - [F,L]
</IfModule>

# Prevenir acesso direto a arquivos PHP sensíveis
<FilesMatch "^(config|database|constants|auth)\.php$">
    Order allow,deny
    Deny from all
</FilesMatch>

# ============================================
# REDIRECIONAMENTOS E URLS AMIGÁVEIS
# ============================================

# Forçar HTTPS (descomente se tiver SSL)
# RewriteCond %{HTTPS} off
# RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

# Redirecionar WWW para não-WWW (ou vice-versa)
# RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
# RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

# Remover barra no final da URL
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]

# URL Amigáveis para páginas do sistema
# (descomente se quiser URLs como /produtos em vez de products.php)
# RewriteRule ^produtos$ products.php [L,QSA]
# RewriteRule ^produtos/([0-9]+)$ product.php?id=$1 [L,QSA]
# RewriteRule ^cotacoes$ quotes.php [L,QSA]
# RewriteRule ^cotacoes/([0-9]+)$ view_quote.php?id=$1 [L,QSA]
# RewriteRule ^clientes$ customers.php [L,QSA]
# RewriteRule ^vendas$ sales.php [L,QSA]
# RewriteRule ^relatorios$ reports.php [L,QSA]

# Redirecionar index.php para raiz
RewriteCond %{THE_REQUEST} ^.*/index\.php
RewriteRule ^(.*)index\.php$ /$1 [R=301,L]

# ============================================
# CACHE E COMPRESSÃO
# ============================================

# Compressão GZIP
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/x-javascript application/json
    AddOutputFilterByType DEFLATE application/rss+xml application/atom+xml
    AddOutputFilterByType DEFLATE image/svg+xml
    AddOutputFilterByType DEFLATE text/x-component
    
    # Remover cabeçalhos de navegadores antigos
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
    
    <IfModule mod_setenvif.c>
        SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|ico|zip|gz|rar|exe|mp3|mp4|pdf|swf)$ no-gzip
    </IfModule>
</IfModule>

# Cache de navegador
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresDefault "access plus 1 month"
    
    # Imagens
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/webp "access plus 1 year"
    ExpiresByType image/svg+xml "access plus 1 year"
    ExpiresByType image/x-icon "access plus 1 year"
    ExpiresByType image/vnd.microsoft.icon "access plus 1 year"
    
    # CSS e JavaScript
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType text/javascript "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresByType application/x-javascript "access plus 1 month"
    
    # Fontes
    ExpiresByType font/ttf "access plus 1 year"
    ExpiresByType font/otf "access plus 1 year"
    ExpiresByType font/woff "access plus 1 year"
    ExpiresByType font/woff2 "access plus 1 year"
    ExpiresByType application/font-woff "access plus 1 year"
    ExpiresByType application/font-woff2 "access plus 1 year"
    
    # HTML, XML e outros textos
    ExpiresByType text/html "access plus 1 hour"
    ExpiresByType application/xml "access plus 1 hour"
    ExpiresByType application/xhtml+xml "access plus 1 hour"
</IfModule>

# Cache de arquivos estáticos (alternativa)
<IfModule mod_headers.c>
    <FilesMatch "\.(ico|jpe?g|png|gif|swf|css|gz|js|webp)$">
        Header set Cache-Control "max-age=2592000, public"
    </FilesMatch>
    <FilesMatch "\.(x?html?|php)$">
        Header set Cache-Control "max-age=600, private, must-revalidate"
    </FilesMatch>
    <FilesMatch "\.(pdf|flv|mp3|mp4)$">
        Header set Cache-Control "max-age=604800, public"
    </FilesMatch>
    
    # Desabilitar cache para arquivos de desenvolvimento
    <FilesMatch "\.(sql|log|ini|config)$">
        Header set Cache-Control "max-age=0, private, no-store, no-cache, must-revalidate"
    </FilesMatch>
</IfModule>

# ============================================
# SEGURANÇA ADICIONAL
# ============================================

# Prevenir Clickjacking
<IfModule mod_headers.c>
    Header always append X-Frame-Options SAMEORIGIN
    Header set X-Content-Type-Options "nosniff"
    Header set X-XSS-Protection "1; mode=block"
    Header set Referrer-Policy "strict-origin-when-cross-origin"
    Header set Permissions-Policy "geolocation=(), microphone=(), camera=()"
</IfModule>

# Prevenir acesso a includes por URL
<IfModule mod_rewrite.c>
    RewriteRule ^includes/ - [F,L]
    RewriteRule ^config/ - [F,L]
    RewriteRule ^backups/ - [F,L]
    RewriteRule ^vendor/ - [F,L]
</IfModule>

# Bloquear IPs maliciosos (descomente para adicionar)
# <Limit GET POST>
#     order allow,deny
#     deny from 123.45.67.89
#     allow from all
# </Limit>

# ============================================
# ERROS PÁGINA PERSONALIZADA
# ============================================

# ErrorDocument 400 /error.php?code=400
# ErrorDocument 401 /error.php?code=401
# ErrorDocument 403 /error.php?code=403
ErrorDocument 404 /error.php?code=404
# ErrorDocument 500 /error.php?code=500
# ErrorDocument 503 /error.php?code=503

# ============================================
# PHP CONFIGURAÇÕES
# ============================================

# Limites de upload
<IfModule mod_php7.c>
    php_value upload_max_filesize 10M
    php_value post_max_size 10M
    php_value max_execution_time 300
    php_value max_input_time 300
    php_value memory_limit 256M
    php_value session.gc_maxlifetime 7200
</IfModule>

<IfModule mod_php8.c>
    php_value upload_max_filesize 10M
    php_value post_max_size 10M
    php_value max_execution_time 300
    php_value max_input_time 300
    php_value memory_limit 256M
    php_value session.gc_maxlifetime 7200
</IfModule>

# ============================================
# BLOQUEIO DE USER AGENTS MALICIOSOS
# ============================================

# RewriteCond %{HTTP_USER_AGENT} ^$ [OR]
# RewriteCond %{HTTP_USER_AGENT} (bot|crawl|spider|scraper|wget|curl|libwww|python|perl|java|php|ruby|go|axel|httpie) [NC]
# RewriteRule .* - [F,L]

# ============================================
# REDIRECIONAMENTO DE ERROS 404
# ============================================

# Redirecionar URLs quebradas para a página inicial
# <IfModule mod_rewrite.c>
#     RewriteCond %{REQUEST_FILENAME} !-f
#     RewriteCond %{REQUEST_FILENAME} !-d
#     RewriteRule ^(.*)$ index.php [L,QSA]
# </IfModule>