# =====================================================
# MULTI-TENANT SCHOOL SYSTEM - CLEAN URLS & SECURITY
# =====================================================
# Version: 2.0-Safe (Fixed)
# Date: 2025-01-16
# =====================================================

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /Multi-Tanent/
    
    # -----------------------
    # OPTIONAL: HTTPS ENFORCEMENT
    # -----------------------
    # Uncomment to force HTTPS
    # RewriteCond %{HTTPS} off
    # RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

    # -----------------------
    # REDIRECT .PHP TO CLEAN URLS (force clean URLs)
    # Redirect .php → clean URLs (ONLY when directly typed in browser)
    # Prevents loops by checking THE_REQUEST (original browser request) and REDIRECT_STATUS
    # IMPORTANT: Exclude POST requests to prevent form submission issues
    # -----------------------
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteCond %{REQUEST_METHOD} !POST [NC]
    RewriteCond %{THE_REQUEST} \s[^\s]*/(admin|super_admin|parent|student)/[^\s]*\.php [NC]
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule ^(admin|super_admin|parent|student)/(.+)\.php$ $1/$2 [R=301,L,QSA]

    # -----------------------
    # TENANT ISOLATION - SCHOOL-SPECIFIC URLS
    # IMPORTANT: These must come AFTER admin/super_admin/parent/student rules
    # Exclude admin, super_admin, parent, student, school from school code patterns
    # -----------------------
    # Student Registration: /school-code/register -> register_student.php?school=school-code
    RewriteCond %{REQUEST_URI} !^/Multi-Tanent/(admin|super_admin|parent|student|school)/ [NC]
    RewriteRule ^([A-Za-z0-9_-]+)/register/?$ register_student.php?school=$1 [L,QSA]

    # Parent Registration/Login
    RewriteCond %{REQUEST_URI} !^/Multi-Tanent/(admin|super_admin|parent|student|school)/ [NC]
    RewriteRule ^([A-Za-z0-9_-]+)/parent/register/?$ parent_register.php?school=$1 [L,QSA]
    RewriteCond %{REQUEST_URI} !^/Multi-Tanent/(admin|super_admin|parent|student|school)/ [NC]
    RewriteRule ^([A-Za-z0-9_-]+)/parent/login/?$ parent_login.php?school=$1 [L,QSA]

    # Student Login & School Info
    # CRITICAL: This rule was matching /admin/login and redirecting to student login
    RewriteCond %{REQUEST_URI} !^/Multi-Tanent/(admin|super_admin|parent|student|school)/ [NC]
    RewriteRule ^([A-Za-z0-9_-]+)/login/?$ student_login.php?school=$1 [L,QSA]
    RewriteCond %{REQUEST_URI} !^/Multi-Tanent/(admin|super_admin|parent|student|school)/ [NC]
    RewriteRule ^([A-Za-z0-9_-]+)/info/?$ index.php?school=$1 [L,QSA]

    # Tenant-style admin/super_admin shortcuts:
    # /school/{code}/admin/{page}  -> admin/{page}.php?school={code}
    RewriteRule ^school/([A-Za-z0-9_-]+)/admin/([A-Za-z0-9_/-]+)/?$ admin/$2.php?school=$1 [L,QSA]
    RewriteRule ^school/([A-Za-z0-9_-]+)/super_admin/([A-Za-z0-9_/-]+)/?$ super_admin/$2.php?school=$1 [L,QSA]

    # -----------------------
    # CLEAN URLS - REMOVE .PHP EXTENSIONS
    # Check if target file exists before rewriting to prevent loops
    # -----------------------

    # CRITICAL: Handle URLs with trailing slash when both directory and .php file exist
    # Redirect /admin/settings/ -> /admin/settings (will then be rewritten to admin/settings.php)
    # Handle single-segment URLs: /admin/settings/ -> /admin/settings
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteCond %{THE_REQUEST} \s[^\s]*/(admin|super_admin|parent|student)/([^/\s]+)/\s [NC]
    RewriteCond %{REQUEST_URI} ^/Multi-Tanent/(admin|super_admin|parent|student)/([^/]+)/$ [NC]
    RewriteCond %{DOCUMENT_ROOT}/Multi-Tanent/%1/%2.php -f
    RewriteRule ^(admin|super_admin|parent|student)/([^/]+)/$ /Multi-Tanent/$1/$2 [R=301,L]
    
    # Handle multi-segment URLs: /admin/moodle/sync_students/ -> /admin/moodle/sync_students
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteCond %{THE_REQUEST} \s[^\s]*/(admin|super_admin|parent|student)/([^/\s]+)/([^/\s]+)/\s [NC]
    RewriteCond %{REQUEST_URI} ^/Multi-Tanent/(admin|super_admin|parent|student)/([^/]+)/([^/]+)/$ [NC]
    RewriteCond %{DOCUMENT_ROOT}/Multi-Tanent/%1/%2/%3.php -f
    RewriteRule ^(admin|super_admin|parent|student)/([^/]+)/([^/]+)/$ /Multi-Tanent/$1/$2/$3 [R=301,L]
    
    # CRITICAL: Prevent Apache's DirectorySlash redirect by rewriting directories to .php files
    # This handles /admin/settings when admin/settings/ directory exists
    # Must come BEFORE the rewrite rules to catch directory requests first
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteCond %{REQUEST_URI} ^/Multi-Tanent/(admin|super_admin|parent|student)/([^/]+)$ [NC]
    RewriteCond %{DOCUMENT_ROOT}/Multi-Tanent/%1/%2.php -f
    RewriteRule ^(admin|super_admin|parent|student)/([^/]+)$ $1/$2.php [L,QSA]

    # Admin single segment: /admin/settings -> admin/settings.php (MUST come before subdirectory rule)
    # This handles /admin/settings -> admin/settings.php even if admin/settings/ directory exists
    # IMPORTANT: Check if .php file exists and rewrite to it, even if directory also exists
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteCond %{THE_REQUEST} !\.php [NC]
    RewriteCond %{REQUEST_URI} !\.php$ [NC]
    RewriteCond %{REQUEST_URI} !/$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{DOCUMENT_ROOT}/Multi-Tanent/admin/$1.php -f
    RewriteRule ^admin/([^/]+)$ admin/$1.php [L,QSA]

    # Admin subdirectory: /admin/subdir/page -> admin/subdir/page.php
    # This handles /admin/moodle/sync_students -> admin/moodle/sync_students.php
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteCond %{THE_REQUEST} !\.php [NC]
    RewriteCond %{REQUEST_URI} !\.php$ [NC]
    RewriteCond %{REQUEST_URI} !/$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{DOCUMENT_ROOT}/Multi-Tanent/admin/$1/$2.php -f
    RewriteRule ^admin/([^/]+)/([^/]+)$ admin/$1/$2.php [L,QSA]

    # Super admin: /super_admin/page -> super_admin/page.php
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteCond %{THE_REQUEST} !\.php [NC]
    RewriteCond %{REQUEST_URI} !\.php$ [NC]
    RewriteCond %{REQUEST_URI} !/$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{DOCUMENT_ROOT}/Multi-Tanent/super_admin/$1.php -f
    RewriteRule ^super_admin/([^/]+)$ super_admin/$1.php [L,QSA]

    # Super admin subdirectory: /super_admin/subdir/page -> super_admin/subdir/page.php
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteCond %{THE_REQUEST} !\.php [NC]
    RewriteCond %{REQUEST_URI} !\.php$ [NC]
    RewriteCond %{REQUEST_URI} !/$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{DOCUMENT_ROOT}/Multi-Tanent/super_admin/$1/$2.php -f
    RewriteRule ^super_admin/([^/]+)/([^/]+)$ super_admin/$1/$2.php [L,QSA]

    # Parent: /parent/page -> parent/page.php
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteCond %{THE_REQUEST} !\.php [NC]
    RewriteCond %{REQUEST_URI} !\.php$ [NC]
    RewriteCond %{REQUEST_URI} !/$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{DOCUMENT_ROOT}/Multi-Tanent/parent/$1.php -f
    RewriteRule ^parent/([^/]+)$ parent/$1.php [L,QSA]

    # Student: /student/page -> student/page.php
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteCond %{THE_REQUEST} !\.php [NC]
    RewriteCond %{REQUEST_URI} !\.php$ [NC]
    RewriteCond %{REQUEST_URI} !/$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{DOCUMENT_ROOT}/Multi-Tanent/student/$1.php -f
    RewriteRule ^student/([^/]+)$ student/$1.php [L,QSA]

    # Skip actual directories that don't have matching .php files (AFTER clean URL rewrites)
    # This prevents 403 on legitimate directory access but allows clean URLs to work first
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteCond %{REQUEST_URI} !^/Multi-Tanent/(admin|super_admin|parent|student)/ [NC]
    RewriteRule . - [L]

    # -----------------------
    # PROTECT SENSITIVE DIRECTORIES
    # -----------------------
    RewriteCond %{REQUEST_URI} /vendor/ [NC]
    RewriteRule .* - [F,L]

    RewriteCond %{REQUEST_URI} /database/ [NC]
    RewriteRule .* - [F,L]

    RewriteCond %{REQUEST_URI} /logs/ [NC]
    RewriteRule .* - [F,L]

    # Protect includes directory (allow static assets)
    RewriteCond %{REQUEST_URI} /includes/ [NC]
    RewriteCond %{REQUEST_URI} !\.(css|js|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot)$ [NC]
    RewriteRule .* - [F,L]
    
</IfModule>

# =====================================================
# SECURITY - DIRECTORY BROWSING
# =====================================================
Options -Indexes

# =====================================================
# SECURITY - SENSITIVE FILES PROTECTION
# =====================================================
<FilesMatch "\.(sql|log|bak|backup|old|orig|save|swp|tmp|temp|ini|env|htaccess|htpasswd|git|svn|DS_Store)$">
    <IfModule mod_authz_core.c>
        Require all denied
    </IfModule>
    <IfModule !mod_authz_core.c>
        Order allow,deny
        Deny from all
    </IfModule>
</FilesMatch>

# Block version control dirs
<IfModule mod_rewrite.c>
    RewriteRule ^\.git - [F,L]
    RewriteRule ^\.svn - [F,L]
    RewriteRule ^\.hg - [F,L]
</IfModule>

# Protect root-level config files
<FilesMatch "^(config|database)\.php$">
    <IfModule mod_authz_core.c>
        Require all denied
    </IfModule>
    <IfModule !mod_authz_core.c>
    Order allow,deny
    Deny from all
    </IfModule>
</FilesMatch>

# Protect upload directories from executing scripts
<IfModule mod_rewrite.c>
    RewriteCond %{REQUEST_URI} /(uploads|tenants)/.*\.(php|phtml|php3|php4|php5|pl|py|jsp|asp|sh|cgi)$ [NC]
    RewriteRule .* - [F,L]
</IfModule>

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

# 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 image/x-icon "access plus 1 year"
</IfModule>

AddDefaultCharset UTF-8
<IfModule mod_mime.c>
    AddCharset UTF-8 .html .css .js .xml .json .rss .atom
</IfModule>

# =====================================================
# END
# =====================================================

