<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$settings = include(__DIR__ . '/config.php');

function http_get($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $out = curl_exec($ch);
    $err = curl_error($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return [$out, $err, $code];
}

function http_post($url, $payload) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $out = curl_exec($ch);
    $err = curl_error($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return [$out, $err, $code];
}

$token = $settings['bot_url'];
$chatId = $settings['chat_id'];
$base = "https://api.telegram.org/bot{$token}";

// 1) Check token validity via getMe
list($getMeOut, $getMeErr, $getMeCode) = http_get($base . '/getMe');

// 2) Try sending a test message
$testMsg = "Test: visit diagnostics\nToken: " . substr($token, 0, 10) . "...\nChatID: " . $chatId;
list($sendOut, $sendErr, $sendCode) = http_post($base . '/sendMessage', [
    'chat_id' => $chatId,
    'text' => $testMsg,
]);

// 3) Output results
header('Content-Type: application/json');
echo json_encode([
    'config' => [
        'chat_id' => $chatId,
        'bot_token_prefix' => substr($token, 0, 10) . '...'
    ],
    'getMe' => [
        'http_code' => $getMeCode,
        'error' => $getMeErr,
        'response' => json_decode($getMeOut, true)
    ],
    'sendMessage' => [
        'http_code' => $sendCode,
        'error' => $sendErr,
        'response' => json_decode($sendOut, true)
    ]
], JSON_PRETTY_PRINT);