# ============================================================
#  FunAI — Bảo vệ thư mục API
# ============================================================

# Chặn truy cập trực tiếp vào các file nhạy cảm
<FilesMatch "^(config\.php|config\.local\.php|db\.php|rate_limit\.php|user_core\.php|landing_config\.json)$|\.sql$">
    Require all denied
</FilesMatch>

# Chặn mọi file thử nghiệm/tạm (test_*.php, *_test.php, *.bak, *.old) — phòng rò rỉ
# dữ liệu do file debug bị bỏ quên trên server (vd test_exp.php từng lộ email user).
<FilesMatch "^(test_.*\.php|.*_test\.php)$|\.(bak|old|orig|save|swp)$">
    Require all denied
</FilesMatch>

# Chỉ cho phép PHP chạy (không serve raw PHP source)
Options -Indexes

# Security headers
Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "DENY"
Header always set X-XSS-Protection "1; mode=block"

# CORS — chỉ cho phép Extension và localhost (dev)
# Chrome Extension sẽ gửi Origin: chrome-extension://<id>
# Nếu không có Origin header (server-to-server), cho phép qua
SetEnvIf Origin "^(chrome-extension://[a-z]+|http://localhost)" CORS_ORIGIN=$0
Header always set Access-Control-Allow-Origin "%{CORS_ORIGIN}e" env=CORS_ORIGIN
Header always set Access-Control-Allow-Methods "GET, POST, OPTIONS" env=CORS_ORIGIN
Header always set Access-Control-Allow-Headers "Content-Type, X-Admin-Token" env=CORS_ORIGIN

# Xử lý preflight OPTIONS nhanh tại Apache (không cần PHP)
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
