# Enable the rewrite engine
RewriteEngine On
RewriteBase /

# NEW: Force HTTPS and WWW (Moved to the top for best practice)
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,R=301]

# 1. Externally redirect from file.php to /file, ONLY for GET requests
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ %1 [R=301,L]

# 2. Handle specific SEO-friendly URLs first
RewriteRule ^ad/([0-9]+)/([^/]+)/?$ ad_detail.php?id=$1 [L,QSA]
RewriteRule ^ebook/([0-9]+)/([^/]+)/?$ ebook_details.php?id=$1 [L,QSA]

# 3. Internally rewrite general pages (e.g., /login -> login.php)
# This rule only applies if a corresponding .php file exists.
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^\.]+)$ $1.php [L]

# 4. Handle user profiles as a fallback for single-segment URLs
# This rule will only apply if the request does not match a file from the rule above.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9_-]+)/?$ profile.php?username=$1 [L,QSA]

# Rule for Products (add this new line)
RewriteRule ^product/([0-9]+)/([^/]+)/?$ product_detail.php?id=$1&slug=$2 [L,QSA]

# Your existing rule for Ads (it should look something like this)
RewriteRule ^ad/([0-9]+)/([^/]+)/?$ ad_detail.php?id=$1&slug=$2 [L,QSA]

# Other existing rules...
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]