<?php
// get_chat_id.php
// Mendapatkan Chat ID Telegram

include "telegram_config.php";

echo "========================================\n";
echo "     GET TELEGRAM CHAT ID\n";
echo "========================================\n\n";

echo "Bot: " . TELEGRAM_BOT_NAME . "\n";
echo "Token: " . TELEGRAM_BOT_TOKEN . "\n\n";

echo "LANGKAH:\n";
echo "1. Buka Telegram dan cari @NotifikasiSekolahBot\n";
echo "2. Kirim pesan: /start atau 'Halo'\n";
echo "3. Klik link di bawah ini:\n\n";

$url = "https://api.telegram.org/bot" . TELEGRAM_BOT_TOKEN . "/getUpdates";
echo "🔗 <a href='$url' target='_blank'>$url</a>\n\n";

// Ambil chat ID
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);

if ($result && $result['ok'] && !empty($result['result'])) {
    echo "========================================\n";
    echo "     CHAT ID DITEMUKAN!\n";
    echo "========================================\n\n";
    
    $found = false;
    foreach ($result['result'] as $update) {
        $chat_id = null;
        $chat_type = 'unknown';
        $chat_title = 'Unknown';
        
        if (isset($update['message']['chat']['id'])) {
            $chat_id = $update['message']['chat']['id'];
            $chat_type = $update['message']['chat']['type'] ?? 'unknown';
            $chat_title = $update['message']['chat']['title'] ?? 
                         $update['message']['chat']['first_name'] ?? 'Unknown';
        } elseif (isset($update['callback_query']['message']['chat']['id'])) {
            $chat_id = $update['callback_query']['message']['chat']['id'];
            $chat_type = $update['callback_query']['message']['chat']['type'] ?? 'unknown';
            $chat_title = $update['callback_query']['message']['chat']['title'] ?? 'Unknown';
        }
        
        if ($chat_id) {
            $found = true;
            echo "✅ Chat ID: <strong style='color:green;font-size:20px;'>{$chat_id}</strong>\n";
            echo "   Tipe: {$chat_type}\n";
            echo "   Nama: {$chat_title}\n";
            echo "   ----------------------------------------\n";
        }
    }
    
    if ($found) {
        echo "\n========================================\n";
        echo "     UPDATE TELEGRAM_CONFIG.PHP\n";
        echo "========================================\n\n";
        echo "Ganti baris ini:\n";
        echo "define('TELEGRAM_CHAT_ID', 'GANTI_DENGAN_CHAT_ID_ANDA');\n\n";
        echo "Menjadi:\n";
        echo "define('TELEGRAM_CHAT_ID', 'CHAT_ID_ANDA');\n";
    } else {
        echo "❌ Tidak ada chat_id ditemukan.\n";
        echo "Pastikan Anda sudah mengirim pesan ke bot.\n";
    }
    
} else {
    echo "❌ Belum ada pesan yang dikirim ke bot.\n";
    echo "Silakan kirim pesan ke @NotifikasiSekolahBot di Telegram.\n";
    echo "Lalu refresh halaman ini.\n";
}
?>