<?php
require_once '../includes/config.php';
require_once '../includes/telegram.php';
requireLogin();
header('Content-Type: application/json');

$user  = getCurrentUser();
$db    = getDB();
$input = json_decode(file_get_contents('php://input'), true);
$tgId  = trim($input['telegram_id'] ?? '');

// Add column if not exists
try { $db->exec("ALTER TABLE users ADD COLUMN telegram_id VARCHAR(50) DEFAULT NULL"); } catch(Exception $e) {}

// Save
$db->prepare("UPDATE users SET telegram_id=? WHERE id=?")->execute([$tgId ?: null, $user['id']]);

// Send test message if ID provided
if ($tgId) {
    $result = sendUserTelegram($tgId,
        "✅ <b>Telegram Connected!</b>\n\n".
        "👤 <b>Name:</b> ".htmlspecialchars($user['name'])."\n".
        "📱 <b>Phone:</b> ".$user['phone']."\n\n".
        "এখন থেকে আপনার recharge ও drive সফল হলে এখানে notification আসবে! 🎉"
    );
    if (!$result || empty($result['ok'])) {
        echo json_encode(['success'=>false,'message'=>'Invalid Telegram ID or bot blocked. Please message @userinfobot to get your correct ID.']);
        exit;
    }
}

echo json_encode(['success'=>true,'message'=>'Saved!']);
