# API .htaccess for Divine Grace School Management System
# Production: https://4102009823.ceiscy.com

# Enable CORS
<IfModule mod_headers.c>
    # Set CORS based on origin
    SetEnvIf Origin "^https://dgsch\.vercel\.app$" ORIGIN_ALLOWED=$0
    SetEnvIf Origin "^https://4102009823\.ceiscy\.com$" ORIGIN_ALLOWED=$0
    SetEnvIf Origin "^http://localhost(:[0-9]+)?$" ORIGIN_ALLOWED=$0
    SetEnvIf Origin "^http://127\.0\.0\.1(:[0-9]+)?$" ORIGIN_ALLOWED=$0
    
    Header always set Access-Control-Allow-Origin "%{ORIGIN_ALLOWED}e" env=ORIGIN_ALLOWED
    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 "true"
    Header always set Access-Control-Max-Age "3600"
</IfModule>

# Handle preflight OPTIONS requests
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]

# Allow PUT and DELETE methods
<Limit GET POST PUT DELETE OPTIONS>
    Order allow,deny
    Allow from all
</Limit>

# Route all requests to index.php (including PUT/DELETE)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?endpoint=$1 [L,QSA,E=REQUEST_METHOD:%{REQUEST_METHOD}]

# Security
<FilesMatch "\.(env|log|sql)$">
    Order allow,deny
    Deny from all
</FilesMatch>

# PHP Settings
<IfModule mod_php7.c>
    php_value upload_max_filesize 10M
    php_value post_max_size 10M
    php_value max_execution_time 300
</IfModule>
