<?php
// telegram_helper.php
require_once 'config.php';

function sendTelegramMessage($message) {
    if (TELEGRAM_BOT_TOKEN == 'YOUR_BOT_TOKEN_HERE' || TELEGRAM_CHAT_ID == 'YOUR_CHAT_ID_HERE') {
        // Do not send if not configured
        return false;
    }
    
    $url = "https://api.telegram.org/bot" . TELEGRAM_BOT_TOKEN . "/sendMessage";
    $data = [
        'chat_id' => TELEGRAM_CHAT_ID,
        'text' => $message,
        'parse_mode' => 'HTML'
    ];

    // use HTTP POST
    $options = [
        'http' => [
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($data)
        ]
    ];
    $context  = stream_context_create($options);
    
    // Suppress warnings in case of connection issues
    $result = @file_get_contents($url, false, $context);
    
    return $result !== false;
}

// Function to get visitor IP address safely
function getVisitorIp() {
    $ip = '';
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
?>
