<?php
// Telegram notification helper — reads bot token & chat id from settings table
function tg_send($pdo, $text){
    $token = trim(setting($pdo, 'telegram_bot_token', ''));
    $chat  = trim(setting($pdo, 'telegram_chat_id', ''));
    if ($token === '' || $chat === '') return false;

    $url = 'https://api.telegram.org/bot'.$token.'/sendMessage';
    $post = http_build_query([
        'chat_id' => $chat,
        'text'    => $text,
        'parse_mode' => 'HTML',
        'disable_web_page_preview' => true,
    ]);

    // Prefer cURL; fallback to file_get_contents
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $post,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 6,
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
        @curl_exec($ch);
        curl_close($ch);
        return true;
    }
    @file_get_contents($url, false, stream_context_create([
        'http' => ['method'=>'POST','header'=>"Content-Type: application/x-www-form-urlencoded\r\n",'content'=>$post,'timeout'=>6],
    ]));
    return true;
}

function tg_notify_new_order($pdo, $order_id){
    $q = $pdo->prepare("SELECT o.*, u.name AS uname, u.email AS uemail, u.phone AS uphone,
                               s.name AS sname, s.kind AS skind
                        FROM orders o
                        LEFT JOIN users u ON u.id=o.user_id
                        LEFT JOIN services s ON s.id=o.service_id
                        WHERE o.id=?");
    $q->execute([$order_id]);
    $o = $q->fetch();
    if (!$o) return;

    // Skip Auto Server Copy (API) orders per requirement
    if (($o['skind'] ?? '') === 'api') return;

    $site = defined('SITE_NAME') ? SITE_NAME : 'Website';
    $host = ($_SERVER['HTTP_HOST'] ?? '');
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off') ? 'https' : 'http';
    $siteUrl = $host ? ($scheme.'://'.$host) : '';

    $lines = [];
    $lines[] = "🔔 <b>নতুন অর্ডার</b> — ".htmlspecialchars($site, ENT_QUOTES, 'UTF-8');
    $lines[] = "🆔 অর্ডার: <b>#".$o['id']."</b>";
    $lines[] = "🛒 সার্ভিস: <b>".htmlspecialchars($o['sname'] ?? '-', ENT_QUOTES, 'UTF-8')."</b>";
    $lines[] = "👤 কাস্টমার: ".htmlspecialchars($o['uname'] ?? '-', ENT_QUOTES, 'UTF-8');
    $lines[] = "📧 ইমেইল: ".htmlspecialchars($o['uemail'] ?? '-', ENT_QUOTES, 'UTF-8');
    if (!empty($o['uphone'])) $lines[] = "📱 ফোন: ".htmlspecialchars($o['uphone'], ENT_QUOTES, 'UTF-8');
    $lines[] = "💰 মূল্য: ".(defined('CURRENCY')?CURRENCY:'')." ".number_format((float)$o['price'], 2);
    $lines[] = "📌 স্ট্যাটাস: ".htmlspecialchars($o['status'], ENT_QUOTES, 'UTF-8');
    $lines[] = "🕒 সময়: ".htmlspecialchars($o['created_at'] ?? date('Y-m-d H:i:s'), ENT_QUOTES, 'UTF-8');

    if (!empty($o['custom_data'])) {
        $cd = json_decode($o['custom_data'], true);
        if (is_array($cd) && count($cd)) {
            $lines[] = "\n📝 <b>বিস্তারিত:</b>";
            foreach ($cd as $k => $v) {
                if (is_array($v)) $v = json_encode($v, JSON_UNESCAPED_UNICODE);
                $lines[] = "• ".htmlspecialchars($k, ENT_QUOTES, 'UTF-8').": ".htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
            }
        }
    }

    if ($siteUrl) $lines[] = "\n🌐 ".$siteUrl;

    tg_send($pdo, implode("\n", $lines));
}

function tg_notify_new_recharge($pdo, $recharge_id){
    $q = $pdo->prepare("SELECT r.*, u.name AS uname, u.email AS uemail, u.phone AS uphone
                        FROM recharges r
                        LEFT JOIN users u ON u.id=r.user_id
                        WHERE r.id=?");
    $q->execute([$recharge_id]);
    $r = $q->fetch();
    if (!$r) return;

    $site = defined('SITE_NAME') ? SITE_NAME : 'Website';
    $host = ($_SERVER['HTTP_HOST'] ?? '');
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off') ? 'https' : 'http';
    $siteUrl = $host ? ($scheme.'://'.$host) : '';

    $lines = [];
    $lines[] = "💰 <b>নতুন রিচার্জ রিকোয়েস্ট</b> — ".htmlspecialchars($site, ENT_QUOTES, 'UTF-8');
    $lines[] = "🆔 রিচার্জ: <b>#".$r['id']."</b>";
    $lines[] = "👤 কাস্টমার: ".htmlspecialchars($r['uname'] ?? '-', ENT_QUOTES, 'UTF-8');
    $lines[] = "📧 ইমেইল: ".htmlspecialchars($r['uemail'] ?? '-', ENT_QUOTES, 'UTF-8');
    if (!empty($r['uphone'])) $lines[] = "📱 ফোন: ".htmlspecialchars($r['uphone'], ENT_QUOTES, 'UTF-8');
    $lines[] = "💳 মেথড: ".htmlspecialchars($r['method'] ?? '-', ENT_QUOTES, 'UTF-8');
    $lines[] = "💵 এমাউন্ট: ".(defined('CURRENCY')?CURRENCY:'')." ".number_format((float)$r['amount'], 2);
    $lines[] = "🧾 TxnID: <code>".htmlspecialchars($r['txn_id'] ?? '-', ENT_QUOTES, 'UTF-8')."</code>";
    if (!empty($r['sender_number'])) $lines[] = "📞 Sender: ".htmlspecialchars($r['sender_number'], ENT_QUOTES, 'UTF-8');
    $lines[] = "📌 স্ট্যাটাস: ".htmlspecialchars($r['status'], ENT_QUOTES, 'UTF-8');
    $lines[] = "🕒 সময়: ".htmlspecialchars($r['created_at'] ?? date('Y-m-d H:i:s'), ENT_QUOTES, 'UTF-8');
    if ($siteUrl) $lines[] = "\n🌐 ".$siteUrl;

    tg_send($pdo, implode("\n", $lines));
}
