# Enable CORS for specific domains
SetEnvIf Origin "^http(s)?://(.+\.)?(localhost:3000|helgehaukeland.com|helgehaukeland.no)$" ALLOWED_ORIGIN=$0
Header always set Access-Control-Allow-Origin %{ALLOWED_ORIGIN}e env=ALLOWED_ORIGIN
Header always set Access-Control-Allow-Methods "GET, POST, OPTIONS"
Header always set Access-Control-Allow-Headers "Content-Type, Authorization"
Header always set Access-Control-Allow-Credentials "true"

# Block direct access to videos directory
RewriteCond %{REQUEST_URI} ^/secure_storage/videos/
RewriteCond %{HTTP_REFERER} !^http(s)?://(.+\.)?(localhost:3000|helgehaukeland.com|helgehaukeland.no)/ [NC]
RewriteRule .* - [F]

# Handle Authorization header
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

# Enable rewrite engine
RewriteEngine On
RewriteBase /

# Handle OPTIONS requests
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule .* - [R=200,L]

# API routes
RewriteRule ^api/storage/?(.*)$ api/storage/index.php [L,QSA]

# Debug - log all requests
php_value error_log /home/natasun/helgehaukeland.com/secure_storage/logs/php-error.log
php_flag log_errors on
php_value error_reporting 2147483647

php_value memory_limit 256M
php_value upload_max_filesize 1000M
php_value post_max_size 1000M
php_value max_execution_time 300
php_value max_input_time 300
# Protect sensitive directories
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_URI} ^/secure_storage/.*$ [NC]
    RewriteRule .* - [F,L]
</IfModule>

# Route all API requests to index.php
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^api/.* api/storage/index.php [L]
</IfModule>

# Handle media files through API for authorized requests
RewriteCond %{REQUEST_URI} ^/secure_storage/.*\.(mp4|webm|ogg|mp3|wav|m4a)$ [NC]
RewriteCond %{HTTP_AUTHORIZATION} ^Bearer
RewriteRule ^(.*)$ api/storage/index.php [L,QSA]

# Block direct access to secure_storage
RewriteCond %{REQUEST_URI} ^/secure_storage/
RewriteCond %{REQUEST_URI} !\.(mp4|webm|ogg|mp3|wav|m4a)$ [NC]
RewriteRule .* - [F,L]
