<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    # Force HTTPS
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

    # Force www → non-www (choose one; this uses non-www canonical)
    RewriteCond %{HTTP_HOST} ^www\.swadeshidata\.com$ [NC]
    RewriteRule ^(.*)$ https://swadeshidata.com/$1 [R=301,L]

    # Remove trailing slash from non-directory URLs
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [R=301,L]

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

    # Block direct access to PHP files in /api except through intended use
    # (handled below via FilesMatch)
</IfModule>

# ── Security Headers ─────────────────────────────────────────
<IfModule mod_headers.c>

    # Prevent clickjacking
    Header always set X-Frame-Options "SAMEORIGIN"

    # Stop MIME-type sniffing
    Header always set X-Content-Type-Options "nosniff"

    # XSS protection (legacy browsers)
    Header always set X-XSS-Protection "1; mode=block"

    # Referrer policy
    Header always set Referrer-Policy "strict-origin-when-cross-origin"

    # Permissions policy — disable unused browser features
    Header always set Permissions-Policy "geolocation=(), microphone=(), camera=(), payment=(), usb=(), magnetometer=(), gyroscope=(), accelerometer=()"

    # HTTP Strict Transport Security (HSTS) — 1 year
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"

    # Content Security Policy
    # Allows: own origin, Google Fonts, Stripe, Anthropic API
    Header always set Content-Security-Policy "default-src 'self'; \
        script-src 'self' 'unsafe-inline' https://js.stripe.com; \
        style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; \
        font-src 'self' https://fonts.gstatic.com; \
        img-src 'self' data: https:; \
        connect-src 'self' https://api.anthropic.com https://api.stripe.com https://swadeshidata.com; \
        frame-src https://js.stripe.com https://hooks.stripe.com; \
        object-src 'none'; \
        base-uri 'self'; \
        form-action 'self'; \
        upgrade-insecure-requests"

    # Remove server info headers
    Header always unset X-Powered-By
    Header always unset Server

    # Cache-Control for static assets
    <FilesMatch "\.(css|js|woff2?|ttf|eot|otf|svg)$">
        Header set Cache-Control "public, max-age=31536000, immutable"
    </FilesMatch>

    # Cache HTML pages for short time (fresh content)
    <FilesMatch "\.(html|htm)$">
        Header set Cache-Control "public, max-age=3600, must-revalidate"
    </FilesMatch>

    # No cache for API responses
    <FilesMatch "\.php$">
        Header set Cache-Control "no-store, no-cache, must-revalidate, max-age=0"
        Header set Pragma "no-cache"
    </FilesMatch>

</IfModule>

# ── Block Sensitive Files ─────────────────────────────────────
<FilesMatch "(^\.env|\.htpasswd|composer\.(json|lock)|package\.json|package-lock\.json|\.git|\.gitignore|\.DS_Store|Thumbs\.db|error_log|access_log|debug\.log|phpinfo\.php)$">
    Order allow,deny
    Deny from all
</FilesMatch>

# Block access to data/ directory entirely
<IfModule mod_rewrite.c>
    RewriteRule ^data(/.*)?$ - [F,L]
</IfModule>

# Block access to raw xlsx/xls data files by extension
<FilesMatch "\.(xlsx|xls|csv|sql|bak|backup|log|sh|bash|py|rb|go|rs)$">
    Order allow,deny
    Deny from all
</FilesMatch>

# ── Block Common Attack Patterns ─────────────────────────────
<IfModule mod_rewrite.c>

    # Block SQL injection attempts in query strings
    RewriteCond %{QUERY_STRING} (\bunion\b.+\bselect\b|\bselect\b.+\bfrom\b|\bdrop\b.+\btable\b) [NC]
    RewriteRule .* - [F,L]

    # Block XSS attempts
    RewriteCond %{QUERY_STRING} (<script|%3Cscript|javascript:|vbscript:) [NC]
    RewriteRule .* - [F,L]

    # Block common exploit scanners
    RewriteCond %{HTTP_USER_AGENT} (nikto|sqlmap|masscan|nmap|dirbuster|burpsuite|w3af|acunetix|nessus|openvas|zgrab) [NC]
    RewriteRule .* - [F,L]

    # Block access to wp-admin / common CMS probes (not WordPress, but stops noise)
    RewriteRule ^(wp-admin|wp-login|wp-config|xmlrpc|phpmyadmin|pma|phpMyAdmin|adminer|setup\.php) - [F,L]

</IfModule>

# ── PHP Security Settings ─────────────────────────────────────
<IfModule mod_php.c>
    php_flag display_errors Off
    php_flag log_errors On
    php_flag expose_php Off
    php_value upload_max_filesize 5M
    php_value post_max_size 8M
    php_value max_execution_time 30
    php_value session.cookie_httponly 1
    php_value session.cookie_secure 1
    php_value session.use_strict_mode 1
    php_value session.cookie_samesite "Strict"
</IfModule>

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

# ── Compression ───────────────────────────────────────────────
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/css text/javascript
    AddOutputFilterByType DEFLATE application/javascript application/json application/xml
    AddOutputFilterByType DEFLATE image/svg+xml font/woff2
</IfModule>

# ── Custom Error Pages ─────────────────────────────────────────
ErrorDocument 403 /index.html
ErrorDocument 404 /index.html
ErrorDocument 500 /index.html

# ── Rate Limiting (basic via mod_evasive if available) ─────────
<IfModule mod_evasive24.c>
    DOSHashTableSize    3097
    DOSPageCount        5
    DOSSiteCount        50
    DOSPageInterval     1
    DOSSiteInterval     1
    DOSBlockingPeriod   10
</IfModule>
