<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /

  # Exclude ACME / SSL Domain Control Validation
  RewriteRule ^\.well-known/ - [L]

  # 1. Force HTTPS Redirect (Redirect http:// to https://)
  RewriteCond %{HTTPS} off
  RewriteCond %{HTTP:X-Forwarded-Proto} !https
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

  # 2. Contact form API
  RewriteRule ^api/contact/?$ api/contact.php [L,QSA]

  # 3. Admin, 2FA TOTP, Articles, Catalogues & Analytics API
  RewriteRule ^api/admin/(.*)$ api/admin.php?endpoint=$1 [L,QSA]
  RewriteRule ^api/admin/?$ api/admin.php [L,QSA]
  RewriteRule ^api/analytics/?$ api/admin.php?endpoint=analytics [L,QSA]
  RewriteRule ^api/articles/?(.*)$ api/admin.php?endpoint=articles/$1 [L,QSA]
  RewriteRule ^api/catalogues/?(.*)$ api/admin.php?endpoint=catalogues/$1 [L,QSA]

  # 4. If the requested file or directory exists, serve it directly
  RewriteCond %{REQUEST_FILENAME} -f [OR]
  RewriteCond %{REQUEST_FILENAME} -d
  RewriteRule ^ - [L]

  # 5. All other URLs route to index.html (React SPA routing)
  RewriteCond %{REQUEST_URI} !^/\.well-known
  RewriteRule ^ index.html [L]
</IfModule>

# Protect database.json from direct public download
<Files "database.json">
  Order Allow,Deny
  Deny from all
</Files>

# Security & Gzip Compression
<IfModule mod_headers.c>
  Header set X-Content-Type-Options "nosniff"
  Header set X-Frame-Options "SAMEORIGIN"
  Header set X-XSS-Protection "1; mode=block"
</IfModule>

<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
</IfModule>
