<?php
// telegram_config.php
// Konfigurasi untuk Telegram Bot

// Gunakan token bot Anda
define('TELEGRAM_BOT_TOKEN', '8925753263:AAGPy5CusOTnYmEbmhm_LJtW0bc1sqZZOPQ');

// Chat ID admin (dari getUpdates)
define('TELEGRAM_CHAT_ID', '8611512964');

// Nama bot untuk ditampilkan
define('TELEGRAM_BOT_NAME', 'Notifikasi Sekolah');

// ============================================
// FUNGSI KIRIM TELEGRAM
// ============================================

function kirimTelegram($pesan, $chat_id = null) {
    if ($chat_id === null) {
        $chat_id = TELEGRAM_CHAT_ID;
    }
    
    // Validasi chat_id
    if (empty($chat_id) || !preg_match('/^[0-9]+$/', $chat_id)) {
        return "⚠️ Chat ID tidak valid: " . ($chat_id ?: 'kosong');
    }
    
    $token = TELEGRAM_BOT_TOKEN;
    $url = "https://api.telegram.org/bot{$token}/sendMessage";
    
    // Gunakan plain text
    $clean_pesan = strip_tags($pesan);
    $clean_pesan = str_replace(['*', '_', '`'], '', $clean_pesan);
    
    $data = [
        'chat_id' => $chat_id,
        'text' => $clean_pesan,
        'disable_web_page_preview' => true
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/x-www-form-urlencoded',
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($httpCode == 200) {
        $result = json_decode($response, true);
        if ($result && isset($result['ok']) && $result['ok']) {
            return "✅ Telegram berhasil dikirim ke " . $chat_id;
        }
        $desc = $result['description'] ?? 'Unknown error';
        return "⚠️ Gagal kirim Telegram: " . $desc;
    }
    
    if ($error) {
        return "⚠️ Gagal kirim Telegram: " . $error;
    }
    
    return "⚠️ Gagal kirim Telegram. HTTP: {$httpCode}";
}

function kirimTelegramToUser($pesan, $telegram_id) {
    if (empty($telegram_id) || !preg_match('/^[0-9]+$/', $telegram_id)) {
        return "⚠️ Telegram ID tidak valid: " . ($telegram_id ?: 'kosong');
    }
    return kirimTelegram($pesan, $telegram_id);
}
?>