RewriteEngine On

# Redirect all requests to index.html to login page
RewriteCond %{REQUEST_URI} /index\.html$ [NC]
RewriteRule ^(.*)$ login.html [R=302,L]

# Make PHP files the priority
DirectoryIndex index.php index.html

# Block direct access to the main application
RewriteCond %{REQUEST_URI} ^/emergency-system/?$ [NC]
RewriteRule ^(.*)$ login.html [R=302,L]

# تمكين CORS للواجهات البرمجية
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header always set Access-Control-Allow-Headers "Content-Type, Authorization"

# إعادة التوجيه لصفحة الفهرس
RewriteRule ^$ login.html [L]

# حماية الملفات الحساسة
<Files "*.php">
    Order Allow,Deny
    Allow from all
</Files>

<Files "config/*">
    Order Deny,Allow
    Deny from all
</Files>

<Files "api/*">
    Order Allow,Deny
    Allow from all
</Files>

# حماية الملفات الحساسة الأخرى
<Files "*.sql">
    Order Deny,Allow
    Deny from all
</Files>

<Files ".env">
    Order Deny,Allow
    Deny from all
</Files>

# ضغط الملفات لتحسين الأداء
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json
</IfModule>

# caching لتحسين الأداء
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/pdf "access plus 1 month"
    ExpiresByType text/javascript "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresByType application/json "access plus 1 month"
    ExpiresByType text/html "access plus 600 seconds"
</IfModule>

# منع الوصول المباشر لملفات معينة
RewriteRule ^config/ - [F,L]
RewriteRule ^\.htaccess$ - [F,L]
RewriteRule ^README\.md$ - [F,L]
RewriteRule ^CHANGELOG\.txt$ - [F,L]

# إعادة توجيه API requests للـ PHP files
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^api/(.*)$ api/$1.php [L,QSA]

# معالجة أخطاء الصفحات
ErrorDocument 404 /login.html
ErrorDocument 403 /login.html
ErrorDocument 500 /login.html