# .htaccess para as APIs PHP
RewriteEngine On

# Enable CORS for all API requests
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, X-Requested-With"

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

# API Routes
RewriteBase /backend/

# Login API
RewriteRule ^api/login/?$ api/login.php [L,QSA]

# Pedidos API
RewriteRule ^api/pedidos/([0-9]+)/?$ api/pedidos.php/$1 [L,QSA]
RewriteRule ^api/pedidos/([0-9]+)/todos/?$ api/pedidos.php/$1/todos [L,QSA]
RewriteRule ^api/pedidos/([0-9]+)/entregar/?$ api/pedidos.php/$1/entregar [L,QSA]

# Push notifications API
RewriteRule ^api/push/register/?$ api/push.php/register [L,QSA]
RewriteRule ^api/push/check/([0-9]+)/?$ api/push.php/$1/check [L,QSA]

# Security headers
<IfModule mod_headers.c>
    # Prevent access to sensitive files
    <FilesMatch "\.(php|inc|conf)$">
        Header set X-Content-Type-Options "nosniff"
        Header set X-Frame-Options "DENY"
        Header set X-XSS-Protection "1; mode=block"
    </FilesMatch>
    
    # JSON responses
    <FilesMatch "\.php$">
        Header set Content-Type "application/json; charset=utf-8"
    </FilesMatch>
</IfModule>

# Deny access to config files
<Files "config.php">
    Order allow,deny
    Deny from all
</Files>

# Deny access to .htaccess
<Files ".htaccess">
    Order allow,deny
    Deny from all
</Files>

# Enable compression
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE application/json
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
</IfModule>

# Error pages
ErrorDocument 404 /backend/api/error.php?code=404
ErrorDocument 500 /backend/api/error.php?code=500