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

# Enable Rewrite Engine
RewriteEngine On
RewriteBase /school/

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

# Handle API requests - must match /school/api/ path
RewriteCond %{REQUEST_URI} ^/school/api/
RewriteRule ^api/(.*)$ api/index.php?endpoint=$1 [L,QSA]

# Handle frontend routes - serve index.html for all non-file requests
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.html [L]

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

# Disable directory browsing
Options -Indexes

# Protect sensitive files
<FilesMatch "\.(env|log|sql|md|json)$">
    Order allow,deny
    Deny from all
</FilesMatch>

# Enable CORS for API
<IfModule mod_headers.c>
    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"
</IfModule>

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

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

# Compression
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json
</IfModule>

# Browser Caching
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/svg+xml "access plus 1 year"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresByType application/pdf "access plus 1 month"
    ExpiresByType text/html "access plus 0 seconds"
</IfModule>
