<?php
// spp_admin/test_telegram.php
header('Content-Type: application/json');

// Coba beberapa path database
foreach (['config/db.php', 'config/database.php'] as $p) {
    if (file_exists($p)) { require_once $p; break; }
}

$token  = trim($_GET['token']   ?? '');
$chatId = trim($_GET['chat_id'] ?? '');

// Ambil dari DB jika kosong
if ((empty($token) || empty($chatId)) && isset($pdo)) {
    try {
        $rows = $pdo->query("SELECT kunci, nilai FROM pengaturan WHERE kunci IN ('telegram_bot_token','telegram_admin_chat_id')")->fetchAll(PDO::FETCH_KEY_PAIR);
        if (empty($token))  $token  = $rows['telegram_bot_token']     ?? '';
        if (empty($chatId)) $chatId = $rows['telegram_admin_chat_id'] ?? '';
    } catch (Exception $e) {}
}

if (empty($token))  { echo json_encode(['ok'=>false,'description'=>'Bot Token belum diisi di Pengaturan']); exit; }
if (empty($chatId)) { echo json_encode(['ok'=>false,'description'=>'Chat ID Admin belum diisi di Pengaturan']); exit; }

$ch = curl_init("https://api.telegram.org/bot{$token}/sendMessage");
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => http_build_query([
        'chat_id'    => $chatId,
        'text'       => "✅ *Test Notifikasi SPP*\n\nBot Telegram berhasil terhubung!\nWaktu: " . date('d/m/Y H:i') . " WIB\n\nSistem siap mengirim notifikasi keterlambatan SPP 🎉",
        'parse_mode' => 'Markdown',
    ]),
    CURLOPT_TIMEOUT        => 15,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/x-www-form-urlencoded'],
]);
$res = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);

echo $res ?: json_encode(['ok'=>false,'description'=>'cURL error: '.$err]);