<?php
declare(strict_types=1);

/**
 * Telegram Bot API helper
 * - Reads bot token from environment variable TELEGRAM_BOT_TOKEN
 * - Optional default chat from TELEGRAM_CHAT_ID (e.g. @BLACKBETDESTEK)
 *
 * SECURITY NOTE: Do not hardcode secrets in source code.
 */

function telegram_get_token(): ?string
{
    $token = getenv('TELEGRAM_BOT_TOKEN');
    if ($token && is_string($token)) {
        return trim($token);
    }
    if (defined('TELEGRAM_BOT_TOKEN')) {
        return constant('TELEGRAM_BOT_TOKEN');
    }
    return null;
}

function sendTelegramMessage(string $chatIdOrUsername, string $text, string $parseMode = 'HTML'): bool
{
    $token = telegram_get_token();
    if (!$token) {
        error_log('Telegram token missing: set TELEGRAM_BOT_TOKEN environment variable');
        @file_put_contents(__DIR__ . '/requests_log.txt', '['.date('Y-m-d H:i:s')."] telegram_error=missing_token\n", FILE_APPEND);
        return false;
    }

    $url = sprintf('https://api.telegram.org/bot%s/sendMessage', $token);

    $payload = [
        'chat_id' => $chatIdOrUsername,
        'text' => $text,
        'parse_mode' => $parseMode,
        'disable_web_page_preview' => true,
    ];

    $ch = curl_init($url);
    // Optional insecure mode for development environments
    $insecure = getenv('CURL_INSECURE');
    if ($insecure) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    }
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $payload,
        CURLOPT_TIMEOUT => 8,
        CURLOPT_CONNECTTIMEOUT => 5,
    ]);

    $response = curl_exec($ch);
    if ($response === false) {
        $err = curl_error($ch);
        error_log('Telegram send error: ' . $err);
        @file_put_contents(__DIR__ . '/requests_log.txt', '['.date('Y-m-d H:i:s')."] telegram_error=curl chat=".$chatIdOrUsername." err=".$err."\n", FILE_APPEND);
        curl_close($ch);
        return false;
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    @file_put_contents(
        __DIR__ . '/requests_log.txt',
        '['.date('Y-m-d H:i:s')."] telegram_http=".$httpCode." chat=".$chatIdOrUsername." resp=".substr((string)$response, 0, 200)."\n",
        FILE_APPEND
    );

    return ($httpCode >= 200 && $httpCode < 300);
}

function sendPendingPaymentAlert(string $gatewayName, ?string $chatOverride = null): bool
{
    $chat = $chatOverride ?: (getenv('TELEGRAM_CHAT_ID') ?: '@BLACKBETDESTEK');
    $ip   = $_SERVER['REMOTE_ADDR'] ?? '-';
    $ua   = $_SERVER['HTTP_USER_AGENT'] ?? '-';
    $ref  = $_SERVER['HTTP_REFERER'] ?? '-';
    $time = date('Y-m-d H:i:s');

    $text = "Bekleyen Ödeme Uyarısı\nGateway: {$gatewayName}\nIP: {$ip}\nUA: {$ua}\nReferer: {$ref}\nZaman: {$time}";
    return sendTelegramMessage($chat, $text, 'HTML');
}