# Enable rewrite engine
RewriteEngine On

# Remove trailing slashes
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Security Headers
<IfModule mod_headers.c>
    # Basic security headers
    Header always set X-XSS-Protection "1; mode=block"
    Header always set X-Content-Type-Options "nosniff"
    Header always set X-Frame-Options "SAMEORIGIN"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>

# Block access to sensitive files
<FilesMatch "\.(env|json|config|md|gitignore|gitattributes|lock)$">
    Order allow,deny
    Deny from all
</FilesMatch>

<Files "(.htaccess|.htpasswd)">
    Order allow,deny
    Deny from all
</Files>

# Prevent directory listing
Options -Indexes

# Custom error pages
ErrorDocument 404 /404.php
ErrorDocument 403 /403.php
ErrorDocument 500 /500.php

# URL Rewriting for clean URLs
# Home page
RewriteRule ^home/?$ index.php?action=home [L,QSA]

# Placement test
RewriteRule ^placement-test/?$ index.php?action=placement-test [L,QSA]

# Dashboard
RewriteRule ^dashboard/?$ index.php?action=dashboard [L,QSA]

# Learning sections
RewriteRule ^learning/([a-zA-Z-]+)/?$ index.php?action=learning&skill=$1 [L,QSA]
RewriteRule ^learning/([a-zA-Z-]+)/([0-9]+)/?$ index.php?action=learning&skill=$1&lesson=$2 [L,QSA]

# Profile and progress
RewriteRule ^profile/?$ index.php?action=profile [L,QSA]
RewriteRule ^progress/?$ index.php?action=progress [L,QSA]

# API routes
RewriteRule ^api/([a-zA-Z-]+)/?$ app/api/$1.php [L,QSA]

# Remove .php extension from URLs
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]

# If the request is for a file that exists, serve it
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# Otherwise, route to index.php
RewriteRule ^(.*)$ index.php [L,QSA]