RewriteEngine On
DirectoryIndex index.php index.html

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

# Remove .php extension from URLs (redirect .php to clean URL)
RewriteCond %{THE_REQUEST} \s/(.+?)\.php[\s?] [NC]
RewriteCond %{REQUEST_URI} !^/api/ [NC]
RewriteRule ^ /%1 [R=301,L]

# Internally rewrite clean URLs to .php files
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ $1.php [L]

# Prevent directory browsing
Options -Indexes

# Security headers
<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"
    Header set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>

# Block access to SQLite databases
<FilesMatch "\.(db|sqlite|sqlite3)$">
    Require all denied
</FilesMatch>

# Block access to log files
<FilesMatch "\.log$">
    Require all denied
</FilesMatch>

# Block access to data directory
RewriteRule ^data/ - [F,L]
RewriteRule ^logs/ - [F,L]

# CORS for API
<FilesMatch "\.php$">
    <IfModule mod_headers.c>
        Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
        Header set Access-Control-Allow-Headers "Content-Type"
    </IfModule>
</FilesMatch>

# PHP settings
<IfModule mod_php.c>
    php_value upload_max_filesize 10M
    php_value post_max_size 12M
    php_value max_execution_time 60
</IfModule>

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

# Cache static files
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType text/css "access plus 1 week"
    ExpiresByType application/javascript "access plus 1 week"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    ExpiresByType image/svg+xml "access plus 1 month"
</IfModule>
