<?php
// includes/telegram.php
// Telegram Bot Notification System

function sendTelegram($message) {
    $token   = getSetting('telegram_bot_token');
    $chat_id = getSetting('telegram_chat_id');

    if (!$token || !$chat_id) return false;

    $url  = "https://api.telegram.org/bot{$token}/sendMessage";
    $data = [
        'chat_id'    => $chat_id,
        'text'       => $message,
        'parse_mode' => 'HTML',
    ];

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => http_build_query($data),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_SSL_VERIFYPEER => false,
    ]);
    $result = curl_exec($ch);
    $err    = curl_error($ch);
    curl_close($ch);

    return $err ? false : json_decode($result, true);
}

// ✅ Universal Pending Notifier
// যেকোনো ধরনের pending transaction হলে এই function call করো
function notifyPending($type, $user, $details = []) {
    $icons = [
        'recharge' => '📱',
        'drive'    => '⚡',
        'deposit'  => '💳',
        'mbanking' => '🏦',
        'other'    => '🔔',
    ];
    $labels = [
        'recharge' => 'রিচার্জ রিকোয়েস্ট',
        'drive'    => 'Drive রিকোয়েস্ট',
        'deposit'  => 'ডিপোজিট রিকোয়েস্ট',
        'mbanking' => 'M.Banking রিকোয়েস্ট',
        'other'    => 'নতুন রিকোয়েস্ট',
    ];

    $icon  = $icons[$type]  ?? '🔔';
    $label = $labels[$type] ?? 'নতুন রিকোয়েস্ট';

    $msg = "{$icon} <b>⏳ Pending: {$label}!</b>\n\n";
    $msg .= "👤 ইউজার: <b>{$user}</b>\n";

    foreach ($details as $k => $v) {
        if ($v) $msg .= "{$k}: <b>{$v}</b>\n";
    }

    $msg .= "🕐 সময়: " . date('d M Y, h:i A') . "\n\n";
    $msg .= "⚡ <a href='https://p1.enotice.top/telecom/admin/transactions.php'>Admin Panel এ দেখুন</a>";

    sendTelegram($msg);
}

// ⚡ নতুন Drive (Package) রিকোয়েস্ট
function notifyDriveRequest($user, $phone, $package, $amount, $operator, $ref) {
    if (getSetting('telegram_notify_recharge') !== '1') return;
    $msg = "⚡ <b>নতুন Drive রিকোয়েস্ট!</b>\n\n"
         . "👤 ইউজার: <b>{$user}</b>\n"
         . "📱 নম্বর: <b>{$phone}</b>\n"
         . "📡 অপারেটর: <b>{$operator}</b>\n"
         . "📦 প্যাকেজ: <b>{$package}</b>\n"
         . "💰 মূল্য: <b>৳{$amount}</b>\n"
         . "🔖 Ref: <code>{$ref}</code>\n"
         . "🕐 সময়: " . date('d M Y, h:i A') . "\n\n"
         . "⚡ Admin Panel → Transactions থেকে অনুমোদন করুন।";
    sendTelegram($msg);
}

// ✅ Drive সফল + কমিশন
function notifyDriveSuccess($user, $phone, $package, $amount, $ref, $commission = 0) {
    if (getSetting('telegram_notify_recharge') !== '1') return;
    $msg = "✅ <b>Drive সফল হয়েছে!</b>\n\n"
         . "👤 ইউজার: <b>{$user}</b>\n"
         . "📱 নম্বর: <b>{$phone}</b>\n"
         . "📦 প্যাকেজ: <b>{$package}</b>\n"
         . "💰 মূল্য: <b>৳{$amount}</b>\n"
         . ($commission > 0 ? "🎁 কমিশন: <b>৳{$commission}</b> যোগ হয়েছে\n" : "")
         . "🔖 Ref: <code>{$ref}</code>\n"
         . "🕐 সময়: " . date('d M Y, h:i A');
    sendTelegram($msg);
}

// ✅ নতুন রিচার্জ রিকোয়েস্ট
function notifyRechargeRequest($user, $phone, $amount, $operator, $ref) {
    if (getSetting('telegram_notify_recharge') !== '1') return;
    $msg = "🔔 <b>নতুন রিচার্জ রিকোয়েস্ট!</b>\n\n"
         . "👤 ইউজার: <b>{$user}</b>\n"
         . "📱 নম্বর: <b>{$phone}</b>\n"
         . "📡 অপারেটর: <b>{$operator}</b>\n"
         . "💰 পরিমাণ: <b>৳{$amount}</b>\n"
         . "🔖 Ref: <code>{$ref}</code>\n"
         . "🕐 সময়: " . date('d M Y, h:i A') . "\n\n"
         . "⚡ Admin Panel থেকে অনুমোদন করুন।";
    sendTelegram($msg);
}

// ✅ রিচার্জ সফল
function notifyRechargeSuccess($user, $phone, $amount, $ref) {
    if (getSetting('telegram_notify_recharge') !== '1') return;
    $msg = "✅ <b>রিচার্জ সফল হয়েছে!</b>\n\n"
         . "👤 ইউজার: <b>{$user}</b>\n"
         . "📱 নম্বর: <b>{$phone}</b>\n"
         . "💰 পরিমাণ: <b>৳{$amount}</b>\n"
         . "🔖 Ref: <code>{$ref}</code>\n"
         . "🕐 সময়: " . date('d M Y, h:i A');
    sendTelegram($msg);
}

// ❌ রিচার্জ রিজেক্ট ও রিফান্ড
function notifyRechargeRefund($user, $phone, $amount, $ref, $note = '') {
    if (getSetting('telegram_notify_refund') !== '1') return;
    $msg = "↩️ <b>রিচার্জ রিজেক্ট - Refund!</b>\n\n"
         . "👤 ইউজার: <b>{$user}</b>\n"
         . "📱 নম্বর: <b>{$phone}</b>\n"
         . "💰 Refund: <b>৳{$amount}</b>\n"
         . "🔖 Ref: <code>{$ref}</code>\n"
         . ($note ? "📝 কারণ: {$note}\n" : "")
         . "🕐 সময়: " . date('d M Y, h:i A');
    sendTelegram($msg);
}

// 💳 নতুন ডিপোজিট রিকোয়েস্ট
function notifyDepositRequest($user, $amount, $method, $ref) {
    if (getSetting('telegram_notify_deposit') !== '1') return;
    $msg = "💳 <b>নতুন ডিপোজিট রিকোয়েস্ট!</b>\n\n"
         . "👤 ইউজার: <b>{$user}</b>\n"
         . "💰 পরিমাণ: <b>৳{$amount}</b>\n"
         . "🏦 পদ্ধতি: <b>" . strtoupper($method) . "</b>\n"
         . "🔖 Ref: <code>{$ref}</code>\n"
         . "🕐 সময়: " . date('d M Y, h:i A') . "\n\n"
         . "⚡ Admin Panel থেকে অনুমোদন করুন।";
    sendTelegram($msg);
}

// ✅ ডিপোজিট অনুমোদন
function notifyDepositApproved($user, $amount) {
    if (getSetting('telegram_notify_deposit') !== '1') return;
    $msg = "✅ <b>ডিপোজিট অনুমোদন হয়েছে!</b>\n\n"
         . "👤 ইউজার: <b>{$user}</b>\n"
         . "💰 পরিমাণ: <b>৳{$amount}</b>\n"
         . "🕐 সময়: " . date('d M Y, h:i A');
    sendTelegram($msg);
}

// 👤 নতুন রেজিস্ট্রেশন
function notifyNewUser($name, $username, $phone) {
    $msg = "👤 <b>নতুন ইউজার রেজিস্ট্রেশন!</b>\n\n"
         . "📛 নাম: <b>{$name}</b>\n"
         . "🔑 Username: <b>@{$username}</b>\n"
         . "📱 ফোন: <b>{$phone}</b>\n"
         . "🕐 সময়: " . date('d M Y, h:i A');
    sendTelegram($msg);
}

// Send to specific user's Telegram
function sendUserTelegram($telegramId, $message) {
    $token = getSetting('telegram_bot_token');
    if (!$token || !$telegramId) return false;

    $url  = "https://api.telegram.org/bot{$token}/sendMessage";
    $data = [
        'chat_id'    => $telegramId,
        'text'       => $message,
        'parse_mode' => 'HTML',
    ];

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => http_build_query($data),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_SSL_VERIFYPEER => false,
    ]);
    $result = curl_exec($ch);
    curl_close($ch);
    return json_decode($result, true);
}

// Notify user about recharge success
function notifyUserRechargeSuccess($userId, $phone, $amount, $ref, $operator='') {
    try {
        $db = getDB();
        $u  = $db->prepare("SELECT telegram_id FROM users WHERE id=?");
        $u->execute([$userId]);
        $tgId = $u->fetchColumn();
        if (!$tgId) return;

        $msg  = "✅ <b>রিচার্জ সফল!</b>\n\n";
        $msg .= "📱 <b>নম্বর:</b> {$phone}\n";
        if ($operator) $msg .= "📡 <b>অপারেটর:</b> {$operator}\n";
        $msg .= "💰 <b>পরিমাণ:</b> ৳{$amount}\n";
        $msg .= "🔖 <b>Ref:</b> <code>{$ref}</code>\n";
        $msg .= "🕐 <b>সময়:</b> ".date('d M Y, h:i A');
        sendUserTelegram($tgId, $msg);
    } catch(Exception $e) {}
}

// Notify user about recharge failed/refund
function notifyUserRechargeFailed($userId, $amount, $ref) {
    try {
        $db = getDB();
        $u  = $db->prepare("SELECT telegram_id FROM users WHERE id=?");
        $u->execute([$userId]);
        $tgId = $u->fetchColumn();
        if (!$tgId) return;

        $msg  = "❌ <b>রিচার্জ Failed — Refunded</b>\n\n";
        $msg .= "💰 <b>Refund:</b> ৳{$amount}\n";
        $msg .= "🔖 <b>Ref:</b> <code>{$ref}</code>\n";
        $msg .= "💳 Balance এ ফেরত দেওয়া হয়েছে।";
        sendUserTelegram($tgId, $msg);
    } catch(Exception $e) {}
}

// Notify user about drive success
function notifyUserDriveSuccess($userId, $phone, $pkgName, $amount, $ref, $cashback=0) {
    try {
        $db = getDB();
        $u  = $db->prepare("SELECT telegram_id FROM users WHERE id=?");
        $u->execute([$userId]);
        $tgId = $u->fetchColumn();
        if (!$tgId) return;

        $msg  = "⚡ <b>Drive সফল!</b>\n\n";
        $msg .= "📦 <b>Package:</b> {$pkgName}\n";
        $msg .= "📱 <b>নম্বর:</b> {$phone}\n";
        $msg .= "💰 <b>পরিমাণ:</b> ৳{$amount}\n";
        if ($cashback > 0) $msg .= "🎁 <b>Cashback:</b> ৳{$cashback}\n";
        $msg .= "🔖 <b>Ref:</b> <code>{$ref}</code>";
        sendUserTelegram($tgId, $msg);
    } catch(Exception $e) {}
}

// Universal user notification — call after any successful service
function notifyUser($userId, $title, $details = [], $type = 'success') {
    try {
        $db  = getDB();
        $row = $db->prepare("SELECT telegram_id FROM users WHERE id=?");
        $row->execute([$userId]);
        $tgId = $row->fetchColumn();
        if (!$tgId) return;

        $icons = ['success'=>'✅','warning'=>'⚠️','error'=>'❌','info'=>'ℹ️'];
        $icon  = $icons[$type] ?? '✅';

        $msg = $icon.' <b>'.htmlspecialchars($title)."</b>\n\n";
        foreach ($details as $k => $v) {
            if ($v !== '' && $v !== null) {
                $msg .= "{$k}: <b>".htmlspecialchars($v)."</b>\n";
            }
        }
        $msg .= "\n🕐 ".date('d M Y, h:i A');
        sendUserTelegram($tgId, $msg);
    } catch(Exception $e) {}
}
