<?php
/**
 * Simple Telegram Test
 * Test if Telegram bot is working
 */

require_once 'config.php';
$config = include 'config.php';

$botToken = $config['telegram']['bot_token'];
$chatId = $config['telegram']['chat_id'];

if (empty($botToken) || empty($chatId)) {
    echo "❌ Telegram not configured. Please set bot_token and chat_id in config.php";
    exit;
}

echo "🤖 Testing Telegram Bot...\n";
echo "Bot Token: " . substr($botToken, 0, 10) . "...\n";
echo "Chat ID: $chatId\n\n";

// Test bot info
$url = "https://api.telegram.org/bot{$botToken}/getMe";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

if ($error) {
    echo "❌ cURL Error: $error\n";
    exit;
}

if ($httpCode !== 200) {
    echo "❌ HTTP Error: $httpCode\n";
    echo "Response: $response\n";
    exit;
}

$data = json_decode($response, true);
if (!$data['ok']) {
    echo "❌ Bot API Error: " . ($data['description'] ?? 'Unknown error') . "\n";
    exit;
}

echo "✅ Bot is working!\n";
echo "Bot Username: @" . $data['result']['username'] . "\n";
echo "Bot Name: " . $data['result']['first_name'] . "\n\n";

// Test sending message
echo "📤 Sending test message...\n";

$message = "🧪 *TEST MESSAGE*\n\n";
$message .= "✅ Telegram integration is working correctly!\n";
$message .= "🤖 Bot: @" . $data['result']['username'] . "\n";
$message .= "⏰ Test time: " . date('Y-m-d H:i:s');

$url = "https://api.telegram.org/bot{$botToken}/sendMessage";
$data = [
    'chat_id' => $chatId,
    'text' => $message,
    'parse_mode' => 'Markdown'
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

if ($error) {
    echo "❌ Send Error: $error\n";
    exit;
}

if ($httpCode !== 200) {
    echo "❌ Send HTTP Error: $httpCode\n";
    echo "Response: $response\n";
    exit;
}

$result = json_decode($response, true);
if (!$result['ok']) {
    echo "❌ Send API Error: " . ($result['description'] ?? 'Unknown error') . "\n";
    exit;
}

echo "✅ Test message sent successfully!\n";
echo "Message ID: " . $result['result']['message_id'] . "\n";
echo "\n🎉 Telegram integration is working perfectly!\n";
?>
