<IfModule mod_rewrite.c>
    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Handle X-XSRF-Token Header
    RewriteCond %{HTTP:x-xsrf-token} .
    RewriteRule .* - [E=HTTP_X_XSRF_TOKEN:%{HTTP:X-XSRF-Token}]

    # Serve existing files directly
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule ^ - [L]

    # Serve assets and static files from public/ directory
    RewriteRule ^(assets/.*)$ public/$1 [L]
    RewriteRule ^(build/.*)$ public/$1 [L]
    RewriteRule ^(favicon\.ico)$ public/$1 [L]
    RewriteRule ^(robots\.txt)$ public/$1 [L]
    RewriteRule ^(manifest\.json)$ public/$1 [L]
    RewriteRule ^(sw\.js)$ public/$1 [L]
    RewriteRule ^(offline\.html)$ public/$1 [L]
    RewriteRule ^(storage/.*)$ public/$1 [L]
    RewriteRule ^smfix\.php$ public/smfix.php [L]

    # Redirect trailing slashes if not a folder
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Everything else goes through root index.php -> public/index.php
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L,QSA]
</IfModule>

# Block access to sensitive files
<FilesMatch "^(\.env|\.env\.example|composer\.json|composer\.lock|\.git|artisan|package\.json|package-lock\.json|vite\.config\.js|\.editorconfig|test_credentials\.txt|clear-cache\.php|cpanel-deploy\.ps1|schedule-cron\.bat|resources\.zip|MAGIC\.zip|WORKINGG\.zip|SETUP_GUIDE\.md|README\.md|\.gitignore|\.gitattributes|post-deploy\.php|generate-icons\.php|database\.sqlite|crawled_data\.json)">
    Require all denied
</FilesMatch>

# Block archives, database dumps, logs, and backup files regardless of name
<FilesMatch "\.(zip|tar|gz|bz2|7z|rar|sql|sqlite|db|bak|old|log|env)$">
    Require all denied
</FilesMatch>

# Block access to sensitive directories
<IfModule mod_rewrite.c>
    RewriteRule ^(database|config|routes|resources|scripts|app|bootstrap|storage/framework|storage/logs) - [F,L]
</IfModule>

# Security headers
<IfModule mod_headers.c>
    Header always set X-Content-Type-Options "nosniff"
    Header always set X-Frame-Options "DENY"
    Header always set X-XSS-Protection "1; mode=block"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    Header always set Permissions-Policy "camera=(), microphone=(), geolocation=()"
    # HSTS only on HTTPS
    # Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
    Header always set X-Permitted-Cross-Domain-Policies "none"
</IfModule>

# Disable directory listing
Options -Indexes
