RewriteEngine On

# === Forcer HTTPS ===
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# === URL Rewriting ===
# Ne pas réécrire les fichiers et dossiers existants (css, js, images...)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Tout rediriger vers index.php
RewriteRule ^(.*)$ index.php [QSA,L]

# === Exception : page d'installation (à retirer après install) ===
# install.php est accessible directement car il existe physiquement

# === Empêcher l'accès aux fichiers sensibles ===
<FilesMatch "\.(php|sql|log|env|md)$">
    # Autoriser seulement index.php et install.php
    RewriteCond %{REQUEST_URI} !^/index\.php$
    RewriteCond %{REQUEST_URI} !^/install\.php$
    RewriteCond %{REQUEST_URI} \.php$
    RewriteRule ^ - [F]
</FilesMatch>

# === Headers de sécurité ===
<IfModule mod_headers.c>
    # Protection XSS
    Header always set X-Content-Type-Options "nosniff"
    Header always set X-Frame-Options "DENY"
    Header always set X-XSS-Protection "1; mode=block"
    
    # HSTS — Forcer HTTPS pendant 1 an
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
    
    # Referrer Policy
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    
    # Permissions Policy
    Header always set Permissions-Policy "camera=(), microphone=(), geolocation=(self)"
    
    # Content Security Policy (à affiner selon les CDN utilisés)
    Header always set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdn.jsdelivr.net; font-src 'self' https://fonts.gstatic.com https://cdn.jsdelivr.net; img-src 'self' data: https://*.cartocdn.com https://d1uuj3mi6rzwpm.cloudfront.net https://*.saltedge.com https://image.tmdb.org https://covers.openlibrary.org https://books.google.com https://openweathermap.org https://cdn.rebrickable.com https://*.archive.org; connect-src 'self' https://cdn.jsdelivr.net https://fonts.googleapis.com https://fonts.gstatic.com;"
</IfModule>

# === Compression ===
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/css application/javascript application/json
</IfModule>

# === Cache navigateur — DÉSACTIVÉ par défaut ===
# Le cache est géré exclusivement par le Service Worker
# quand l'admin active le paramètre "cache_enabled".
<IfModule mod_headers.c>
    Header set Cache-Control "no-cache, no-store, must-revalidate"
    Header set Pragma "no-cache"
    Header set Expires "0"
</IfModule>
