# CORS Headers for API requests
<IfModule mod_headers.c>
    # Handle CORS preflight requests
    <If "%{REQUEST_METHOD} == 'OPTIONS'">
        Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
        Header always set Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With"
        Header always set Access-Control-Max-Age "86400"
        Header always set Content-Length "0"
        Header always set Content-Type "text/plain"
        
        # Set specific origin for CORS (not wildcard)
        SetEnvIf Origin "^https?://(www\.)?(channamix\.org|hallobundapedia\.id)$" ORIGIN_SUB=$0
        SetEnvIf Origin "^http://localhost:300[0-9]$" ORIGIN_SUB=$0
        Header always set Access-Control-Allow-Origin "%{ORIGIN_SUB}e" env=ORIGIN_SUB
    </If>
    
    # Handle actual API requests
    <ElseIf "%{REQUEST_URI} =~ m#^/api/#">
        # Set specific origin for CORS (not wildcard)
        SetEnvIf Origin "^https?://(www\.)?(channamix\.org|hallobundapedia\.id)$" ORIGIN_SUB=$0
        SetEnvIf Origin "^http://localhost:300[0-9]$" ORIGIN_SUB=$0
        Header always set Access-Control-Allow-Origin "%{ORIGIN_SUB}e" env=ORIGIN_SUB
        Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
        Header always set Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With"
        Header always set Access-Control-Allow-Credentials "false"
    </ElseIf>
</IfModule>

RewriteEngine On

RewriteCond expr "tolower(%{REQUEST_URI}) =~ /(.*)/"
RewriteRule [A-Z] %1 [R=301,L]
# Redirect any URL containing index.php to clean URL without it
RewriteCond %{REQUEST_URI} ^/index.php$
RewriteRule ^(.*)$ / [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

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