<?php
// Filename: test_telegram.php
require 'config.php';

echo "<h2>Telegram Connection Test (cURL)</h2>";

// 1. Get Settings
$token = getSetting('telegram_bot_token');
$chat_id = getSetting('telegram_chat_id');

echo "<b>Bot Token:</b> " . ($token ? "Found (Ends with ...".substr($token, -5).")" : "<span style='color:red'>MISSING</span>") . "<br>";
echo "<b>Chat ID:</b> " . ($chat_id ? $chat_id : "<span style='color:red'>MISSING</span>") . "<br><br>";

if (!$token || !$chat_id) {
    die("❌ Error: Please save your Bot Token and Chat ID in Admin Settings first.");
}

// 2. Prepare Data
$url = "https://api.telegram.org/bot$token/sendMessage";
$data = [
    'chat_id' => $chat_id,
    'text' => "✅ <b>Success!</b>\nThis is a test message from your School Attendance System.",
    'parse_mode' => 'HTML'
];

// 3. Execute cURL
echo "Connecting to Telegram API...<br>";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 15); // 15 seconds timeout
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Fixes common SSL issues on local/shared hosting

$result = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);

curl_close($ch);

// 4. Analyze Result
if ($result === false) {
    echo "<div style='background:#f8d7da; color:#842029; padding:15px; border-radius:5px;'>";
    echo "<h3>❌ Connection Failed</h3>";
    echo "<b>cURL Error:</b> " . $curl_error . "<br>";
    echo "<br><strong>Possible Causes:</strong>";
    echo "<ul>";
    echo "<li>Your server firewall is blocking outgoing connections to port 443.</li>";
    echo "<li>DNS issues (Server cannot resolve 'api.telegram.org').</li>";
    echo "<li>No internet access on this server.</li>";
    echo "</ul></div>";
} else {
    echo "<b>HTTP Status:</b> $http_code<br>";
    echo "<b>Raw Response:</b> <pre>" . htmlspecialchars($result) . "</pre>";

    $json = json_decode($result, true);

    if ($http_code == 200 && isset($json['ok']) && $json['ok']) {
        echo "<h3 style='color:green'>✅ SUCCESS: Message sent!</h3>";
    } else {
        echo "<h3 style='color:red'>❌ API Error</h3>";
        echo "<b>Telegram Info:</b> " . ($json['description'] ?? 'Unknown error');
    }
}
?>