# ============================================
# CineAbierto - Configuración Apache
# Archivo: .htaccess
# Versión: 3.0 PRO - CON SITEMAP DINÁMICO
# ============================================

# ============================================
# SEGURIDAD
# ============================================

# Evitar listado de directorios
Options -Indexes

# Proteger archivos sensibles
<FilesMatch "\.(env|ini|log|sh|sql)$">
    Order allow,deny
    Deny from all
</FilesMatch>

<FilesMatch "^(config\.php|\.env)$">
    Order allow,deny
    Deny from all
</FilesMatch>

# Forzar UTF-8
AddDefaultCharset UTF-8

# ============================================
# PERFORMANCE - COMPRESIÓN GZIP
# ============================================
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml
    AddOutputFilterByType DEFLATE text/css text/javascript
    AddOutputFilterByType DEFLATE application/javascript application/json
    AddOutputFilterByType DEFLATE application/xml application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
</IfModule>

# ============================================
# PERFORMANCE - CACHE DE NAVEGADOR
# ============================================
<IfModule mod_expires.c>
    ExpiresActive On

    # Imágenes (1 año)
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/webp "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/svg+xml "access plus 1 year"

    # CSS y JavaScript (1 mes)
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresByType text/javascript "access plus 1 month"

    # Fuentes (1 año)
    ExpiresByType font/woff "access plus 1 year"
    ExpiresByType font/woff2 "access plus 1 year"

    # HTML (1 hora - para contenido dinámico)
    ExpiresByType text/html "access plus 1 hour"
    
    # ✅ SITEMAP - Caché de 4 horas
    ExpiresByType application/xml "access plus 4 hours"
</IfModule>

# ============================================
# ✅ SITEMAP - Caché específico para archivos
# ============================================
<IfModule mod_expires.c>
    <FilesMatch "sitemap\.(php|xml)">
        ExpiresActive On
        ExpiresDefault "access plus 4 hours"
    </FilesMatch>
</IfModule>

# ============================================
# ✅ SITEMAP - Content-Type correcto
# ============================================
<IfModule mod_headers.c>
    <FilesMatch "sitemap\.(php|xml)">
        Header set Content-Type "application/xml; charset=utf-8"
        Header set X-Robots-Tag "noindex"
    </FilesMatch>
</IfModule>

# ============================================
# URL REWRITING
# ============================================
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    # ============================================
    # ✅ HTTPS Redirect (ACTIVO EN PRODUCCIÓN)
    # ============================================
    # RewriteCond %{HTTPS} off
    # RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

    # ============================================
    # ✅ WWW Redirect (www → no-www)
    # ============================================
    # RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    # RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

    # ============================================
    # ✅ SITEMAP DINÁMICO
    # ============================================
    # /sitemap.xml → sitemap.php (transparente)
    RewriteRule ^sitemap\.xml$ sitemap.php [L]
    
    # ============================================
    # ✅ ROBOTS.TXT DINÁMICO (OPCIONAL)
    # ============================================
    # Si tienes robots.php para generarlo dinámicamente
    # RewriteRule ^robots\.txt$ robots.php [L]

    # ============================================
    # API REST - Rutas limpias
    # ============================================
    # Procesar ANTES de verificar archivos reales
    RewriteRule ^api/v1/movies/([0-9]+)$ api/v1/movies.php?id=$1 [QSA,L]
    RewriteRule ^api/v1/movies$ api/v1/movies.php [QSA,L]
    RewriteRule ^api/v1/genres$ api/v1/genres.php [QSA,L]
    RewriteRule ^api/v1/stats$ api/v1/stats.php [QSA,L]

    # ============================================
    # EVITAR REESCRITURA DE ARCHIVOS REALES
    # ============================================
    # Si el archivo existe, no reescribir
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule ^ - [L]

    # Si el directorio existe, no reescribir
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]

    # ============================================
    # REDIRECCIONES 301 - URLs ANTIGUAS → NUEVAS
    # ============================================
    # /index.php?genero=X → /genero/X
    RewriteCond %{QUERY_STRING} ^genero=([^&]+)
    RewriteRule ^index\.php$ /genero/%1? [R=301,L]

    # /pelicula.php?slug=X → /pelicula/X
    RewriteCond %{QUERY_STRING} ^slug=([^&]+)
    RewriteRule ^pelicula\.php$ /pelicula/%1? [R=301,L]

    # ============================================
    # URLs LIMPIAS - NIVEL PRO
    # ============================================
    # /genero/ciencia-ficcion → index.php?genero=ciencia-ficcion
    RewriteRule ^genero/([a-z0-9-]+)/?$ index.php?genero=$1 [L,QSA]

    # /pelicula/vengadores-endgame → pelicula.php?slug=vengadores-endgame
    RewriteRule ^pelicula/([a-z0-9-]+)/?$ pelicula.php?slug=$1 [L,QSA]

    # /buscar/termino → index.php?q=termino
    RewriteRule ^buscar/([^/]+)/?$ index.php?q=$1 [L,QSA]

    # Página de inicio limpia: / → index.php
    RewriteRule ^$ index.php [L]

</IfModule>

# ============================================
# HEADERS DE SEGURIDAD
# ============================================
<IfModule mod_headers.c>
    # Prevenir clickjacking
    Header always set X-Frame-Options "SAMEORIGIN"

    # Prevenir MIME sniffing
    Header always set X-Content-Type-Options "nosniff"

    # XSS Protection
    Header always set X-XSS-Protection "1; mode=block"

    # Referrer Policy
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    
    # ✅ Content Security Policy (Opcional - ajustar según necesites)
    # Header always set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; img-src 'self' data: https:; font-src 'self' https://cdnjs.cloudflare.com;"
</IfModule>

# ============================================
# ✅ ERROR PAGES PERSONALIZADAS (OPCIONAL)
# ============================================
# ErrorDocument 404 /404.php
# ErrorDocument 403 /403.php
# ErrorDocument 500 /500.php

# ============================================
# ✅ LÍMITE DE TAMAÑO DE SUBIDA (OPCIONAL)
# ============================================
# php_value upload_max_filesize 20M
# php_value post_max_size 20M
# php_value max_execution_time 300
# php_value max_input_time 300

