<?php
// LÍNEA 1: INICIO ABSOLUTO
ob_start();

// 1. CONFIGURACIÓN SILENCIOSA
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING & ~E_DEPRECATED);
ini_set('display_errors', '0');

// 2. CONEXIÓN A BD
$hosts = "127.0.0.1";
$basededatoss ="dinerma_dinerfi";
$usuariodb = "dinerma_dinerfi";
$clavedb = "MAlo2020COSA30";

$conexions = new mysqli($hosts, $usuariodb, $clavedb, $basededatoss);
if ($conexions->connect_error) { die("Error DB"); }

// 3. DETECTAR DOMINIO
$host_actual = $_SERVER['HTTP_HOST'];
$host_actual = str_replace('www.', '', $host_actual); 
$dominio_principal = 'nosu.app';

// SE AGREGÓ 'market' A LA LISTA DE RESERVADOS
$reservados = ['www', 'mail', 'ftp', 'cpanel', 'webmail', 'admin', 'creartiendaweb', 'plantilla_uno', 'market'];

// =========================================================
// EXCEPCIÓN HOME PRINCIPAL (nosu.app -> reme/index.php)
// =========================================================
if ($host_actual == $dominio_principal) {
    $uri = $_SERVER['REQUEST_URI'];
    
    // Solo actuamos si piden la raíz
    if ($uri == '/' || $uri == '/index.php') {
        if (is_dir('reme')) {
            chdir('reme'); 
            ob_start();
            include 'index.php';
            $html_home = ob_get_clean();
            
            $url_base_reme = "https://nosu.app/reme/";
            $inyeccion_head = "<base href='" . $url_base_reme . "'>";
            $inyeccion_head .= "
            <script>
            document.addEventListener('click', function(e) {
                var target = e.target.closest('a');
                if (target && target.getAttribute('href') === '#') {
                    e.preventDefault();
                    return false;
                }
            });
            </script>";
            
            $html_home = str_ireplace('<head>', '<head>' . $inyeccion_head, $html_home);
            echo $html_home;
            exit;
        }
    }
}

// =========================================================
// EXCEPCIÓN MARKETPLACE (market.nosu.app -> reme/market.php)
// =========================================================
if ($host_actual == 'market.' . $dominio_principal) {
    $uri = $_SERVER['REQUEST_URI'];
    
    // Solo actuamos si piden la raíz del market
    if ($uri == '/' || $uri == '/index.php' || $uri == '/market.php') {
        if (is_dir('reme') && file_exists('reme/market.php')) {
            chdir('reme'); 
            ob_start();
            
            // AQUÍ FORZAMOS LA CARGA DE MARKET.PHP
            include 'market.php'; 
            
            $html_market = ob_get_clean();
            
            // Inyectamos la base apuntando al market para no romper recursos
            $url_base_reme = "https://market.nosu.app/reme/";
            $inyeccion_head = "<base href='" . $url_base_reme . "'>";
            $inyeccion_head .= "
            <script>
            document.addEventListener('click', function(e) {
                var target = e.target.closest('a');
                if (target && target.getAttribute('href') === '#') {
                    e.preventDefault();
                    return false;
                }
            });
            </script>";
            
            $html_market = str_ireplace('<head>', '<head>' . $inyeccion_head, $html_market);
            echo $html_market;
            exit;
        }
    }
}

// 4. BÚSQUEDA EN BD
$valor_a_buscar = '';
$columna_sql = '';

if (strpos($host_actual, $dominio_principal) !== false) {
    $partes = explode('.', $host_actual);
    $subdominio = $partes[0];
    
    // Si es un subdominio reservado (como www o market pero intentando acceder a una ruta no válida), 
    // enviamos a la raíz limpia
    if (in_array($subdominio, $reservados)) { 
        header("Location: https://nosu.app/", true, 303);
        exit; 
    }
    
    $valor_a_buscar = $subdominio;
    $columna_sql = "pagina_web"; 
} else {
    $valor_a_buscar = $host_actual;
    $columna_sql = "pagina_web_oficial"; 
}

// Consultas
$consult = "SELECT pagina_web FROM empleados WHERE $columna_sql = ? LIMIT 1";
$stmt = $conexions->prepare($consult);
$stmt->bind_param("s", $valor_a_buscar);
$stmt->execute();
$stmt->bind_result($carpeta_destino);
$stmt->fetch();
$stmt->close();

$consult2 = "SELECT inicio_app FROM pagina_web WHERE pagina_web = ? LIMIT 1";
$stmt2 = $conexions->prepare($consult2);
$stmt2->bind_param("s", $carpeta_destino);
$stmt2->execute();
$stmt2->bind_result($archivo_inicio_db);
$stmt2->fetch();
$stmt2->close();
$conexions->close(); 

// =========================================================
// VALIDACIÓN (REDIRECCIÓN DE ERRORES AL HOME)
// =========================================================
if (empty($carpeta_destino) || !is_dir($carpeta_destino)) {
    // Si el subdominio no existe o es un error, los mandamos a nosu.app
    header("Location: https://nosu.app/", true, 303);
    exit;
}
// =========================================================

// =========================================================
// 5. ENRUTADOR INTELIGENTE
// =========================================================

$ruta_fisica = __DIR__ . '/' . $carpeta_destino . '/';
$uri = $_SERVER['REQUEST_URI'];
$archivo_solicitado = ltrim(strtok($uri, '?'), '/');
$archivo_solicitado = str_replace($carpeta_destino . '/', '', $archivo_solicitado);

// TRUCO DE INICIO
if ($archivo_solicitado == 'index.php') { $archivo_solicitado = ''; }

$archivo_final = "";
$es_recurso_especifico = false; 

// A. LÓGICA DE SELECCIÓN
if (!empty($archivo_solicitado)) {
    if (file_exists($ruta_fisica . $archivo_solicitado)) {
        $archivo_final = $archivo_solicitado;
        $es_recurso_especifico = true;
    } else {
        $ext = pathinfo($archivo_solicitado, PATHINFO_EXTENSION);
        if (in_array($ext, ['js', 'css', 'json', 'php', 'png', 'jpg', 'webmanifest'])) {
            http_response_code(404);
            exit;
        }
        $archivo_final = "index.php"; 
    }
} else {
    // Modo confianza en la BD
    if (!empty($archivo_inicio_db)) {
        $archivo_final = trim($archivo_inicio_db);
    } else {
        $archivo_final = "index.php";
    }
}

chdir($carpeta_destino);
$ext = pathinfo($archivo_final, PATHINFO_EXTENSION);

// MODO 1: ESTÁTICOS
if (in_array($ext, ['js', 'css', 'png', 'jpg', 'jpeg', 'gif', 'svg', 'json', 'webmanifest', 'ico'])) {
    $mimes = [
        'js' => 'application/javascript', 'css' => 'text/css', 'json' => 'application/json',
        'svg' => 'image/svg+xml', 'png' => 'image/png', 'jpg' => 'image/jpeg',
        'webmanifest' => 'application/manifest+json'
    ];
    ob_end_clean(); 
    if (isset($mimes[$ext])) { header("Content-Type: " . $mimes[$ext]); }
    if (file_exists($archivo_final)) { readfile($archivo_final); } else { http_response_code(404); }
    exit;
}

// MODO 2: API
if ($es_recurso_especifico && $ext == 'php' && $archivo_final != $archivo_inicio_db && $archivo_final != "index.php") {
    ob_end_clean(); 
    if (file_exists($archivo_final)) { include $archivo_final; }
    exit; 
}

// MODO 3: VISTA WEB (HTML)
ob_end_clean(); 
ob_start();     

if (file_exists($archivo_final)) {
    include $archivo_final;
} else {
    if (file_exists("index.php")) { include "index.php"; }
}

$html = ob_get_clean();

// =========================================================
// CORRECCIÓN CORS (AQUÍ ESTABA EL ERROR DEL SUBDOMINIO)
// =========================================================

// Solo reemplazamos si el dominio actual NO es un subdominio de nosu.app
if (strpos($host_actual, 'nosu.app') === false) {
    $html = str_replace($dominio_principal, $host_actual, $html);
}

// =========================================================

// Inyección BASE
$protocolo = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https://" : "http://";
$url_base = $protocolo . $host_actual . "/" . $carpeta_destino . "/";

$script_hash = "
<script>
document.addEventListener('DOMContentLoaded', function() {
    document.body.addEventListener('click', function(e) {
        var target = e.target.closest('a');
        if (target && target.getAttribute('href') === '#') {
            e.preventDefault(); 
            return false;
        }
    });
});
</script>";

$inyeccion = "<base href='" . $url_base . "'>" . $script_hash;
$html = str_ireplace('<head>', '<head>' . $inyeccion, $html);

echo $html;
exit;
?>