<?php
/**
 * SMM Paket Satış Scripti - Telegram Bildirim Fonksiyonları
 * iyzico Ödeme Bildirimi Dahil
 * @version 1.1.0
 */

// Doğrudan erişimi engelle
if (!defined('SITE_VERSION')) {
    die('Doğrudan erişim yasak!');
}

/**
 * Telegram API üzerinden mesaj gönder
 * 
 * @param string $message Gönderilecek mesaj (HTML destekli)
 * @param string|null $botToken Bot token (null ise ayarlardan alır)
 * @param string|null $chatId Chat ID (null ise ayarlardan alır)
 * @return array ['success' => bool, 'error' => string|null, 'message_id' => int|null]
 */
function sendTelegramNotification($message, $botToken = null, $chatId = null) {
    global $settings, $db;
    
    // Ayarları al
    if ($botToken === null) {
        $botToken = $settings->get('telegram_bot_token', '');
    }
    if ($chatId === null) {
        $chatId = $settings->get('telegram_chat_id', '');
    }
    
    // Kontroller
    if (empty($botToken) || empty($chatId)) {
        return ['success' => false, 'error' => 'Bot token veya Chat ID eksik'];
    }
    
    // Telegram bot aktif mi?
    $enabled = $settings->get('telegram_bot_enabled', '0');
    if ($enabled !== '1') {
        return ['success' => false, 'error' => 'Telegram bildirimleri kapalı'];
    }
    
    // API URL
    $url = "https://api.telegram.org/bot{$botToken}/sendMessage";
    
    // Veri
    $data = [
        'chat_id' => $chatId,
        'text' => $message,
        'parse_mode' => 'HTML',
        'disable_web_page_preview' => true
    ];
    
    // cURL isteği
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query($data),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);
    
    // cURL hatası
    if ($curlError) {
        logTelegramError('curl_error', $curlError);
        return ['success' => false, 'error' => 'Bağlantı hatası: ' . $curlError];
    }
    
    // Yanıtı parse et
    $result = json_decode($response, true);
    
    // Başarılı
    if ($httpCode === 200 && isset($result['ok']) && $result['ok'] === true) {
        return [
            'success' => true, 
            'error' => null,
            'message_id' => $result['result']['message_id'] ?? null
        ];
    }
    
    // Hata
    $errorMsg = $result['description'] ?? 'Bilinmeyen hata (HTTP ' . $httpCode . ')';
    logTelegramError('api_error', $errorMsg);
    
    return ['success' => false, 'error' => $errorMsg];
}

/**
 * Telegram hatasını logla
 */
function logTelegramError($type, $message) {
    global $db;
    
    try {
        // api_logs tablosu varsa logla
        $stmt = $db->prepare("
            INSERT INTO api_logs (provider_id, action, request_data, response_data, error, created_at)
            VALUES (NULL, ?, 'telegram', NULL, ?, NOW())
        ");
        $stmt->execute(['telegram_' . $type, $message]);
    } catch (PDOException $e) {
        // Log tablosu yoksa sessizce devam et
    }
}

/**
 * Yeni sipariş bildirimi gönder
 */
function sendNewOrderNotification($order, $package) {
    global $settings;
    
    // Bu bildirim tipi açık mı?
    if ($settings->get('telegram_notify_new_order', '1') !== '1') {
        return ['success' => false, 'error' => 'Bu bildirim tipi kapalı'];
    }
    
    $siteName = defined('SITE_NAME') ? SITE_NAME : 'SMM Panel';
    $currencySymbol = $settings->get('currency_symbol', '₺');
    
    // Mesaj oluştur
    $message = "🛒 <b>Yeni Sipariş!</b>\n\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "📋 <b>Sipariş No:</b> {$order['order_number']}\n";
    $message .= "📦 <b>Paket:</b> {$package['name']}\n";
    $message .= "💰 <b>Tutar:</b> " . number_format($order['amount'], 2, ',', '.') . "{$currencySymbol}\n";
    
    // KDV varsa göster
    if (!empty($order['kdv_amount']) && $order['kdv_amount'] > 0) {
        $message .= "📊 <b>KDV:</b> " . number_format($order['kdv_amount'], 2, ',', '.') . "{$currencySymbol}\n";
    }
    
    // İndirim varsa göster
    if (!empty($order['discount_amount']) && $order['discount_amount'] > 0) {
        $message .= "🏷 <b>İndirim:</b> -" . number_format($order['discount_amount'], 2, ',', '.') . "{$currencySymbol}";
        if (!empty($order['coupon_code'])) {
            $message .= " ({$order['coupon_code']})";
        }
        $message .= "\n";
    }
    
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "👤 <b>Müşteri:</b> {$order['customer_name']}\n";
    $message .= "📧 <b>E-posta:</b> {$order['customer_email']}\n";
    
    if (!empty($order['customer_phone'])) {
        $message .= "📱 <b>Telefon:</b> {$order['customer_phone']}\n";
    }
    
    $message .= "🔗 <b>Hedef:</b> <code>{$order['social_media_link']}</code>\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "📅 <b>Tarih:</b> " . date('d.m.Y H:i') . "\n";
    $message .= "🌐 <b>Site:</b> {$siteName}";
    
    return sendTelegramNotification($message);
}

/**
 * Ödeme/Dekont yükleme bildirimi (Havale/EFT için)
 */
function sendPaymentNotification($order, $package) {
    global $settings;
    
    // Bu bildirim tipi açık mı?
    if ($settings->get('telegram_notify_payment', '1') !== '1') {
        return ['success' => false, 'error' => 'Bu bildirim tipi kapalı'];
    }
    
    $siteName = defined('SITE_NAME') ? SITE_NAME : 'SMM Panel';
    $currencySymbol = $settings->get('currency_symbol', '₺');
    
    $message = "💳 <b>Dekont Yüklendi!</b>\n\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "📋 <b>Sipariş No:</b> {$order['order_number']}\n";
    $message .= "📦 <b>Paket:</b> {$package['name']}\n";
    $message .= "💰 <b>Tutar:</b> " . number_format($order['amount'], 2, ',', '.') . "{$currencySymbol}\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "👤 <b>Müşteri:</b> {$order['customer_name']}\n";
    $message .= "📧 <b>E-posta:</b> {$order['customer_email']}\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "⚠️ <b>Ödeme onayı bekliyor!</b>\n";
    $message .= "📅 " . date('d.m.Y H:i') . " | {$siteName}";
    
    return sendTelegramNotification($message);
}

/**
 * iyzico Kredi Kartı Ödeme Bildirimi
 * 
 * @param array $order Sipariş bilgileri
 * @param array $package Paket bilgileri
 * @param array $paymentData iyzico ödeme detayları
 * @return array
 */
function sendIyzicoPaymentNotification($order, $package, $paymentData = []) {
    global $settings;
    
    // Bu bildirim tipi açık mı?
    if ($settings->get('telegram_notify_payment', '1') !== '1') {
        return ['success' => false, 'error' => 'Bu bildirim tipi kapalı'];
    }
    
    $siteName = defined('SITE_NAME') ? SITE_NAME : 'SMM Panel';
    $currencySymbol = $settings->get('currency_symbol', '₺');
    
    // Kart bilgilerini hazırla
    $cardInfo = '';
    if (!empty($paymentData['card_association'])) {
        $cardAssoc = $paymentData['card_association'];
        // Kart birliği ikonları
        $cardIcons = [
            'VISA' => '💳 VISA',
            'MASTER_CARD' => '💳 MasterCard',
            'TROY' => '💳 Troy',
            'AMERICAN_EXPRESS' => '💳 Amex'
        ];
        $cardInfo = $cardIcons[$cardAssoc] ?? "💳 {$cardAssoc}";
    }
    
    if (!empty($paymentData['card_family'])) {
        $cardInfo .= ' ' . $paymentData['card_family'];
    }
    
    if (!empty($paymentData['last_four_digits'])) {
        $cardInfo .= ' (**** ' . $paymentData['last_four_digits'] . ')';
    }
    
    // Taksit bilgisi
    $installment = $paymentData['installment'] ?? 1;
    $installmentText = $installment > 1 ? "{$installment} Taksit" : "Tek Çekim";
    
    // Mesaj oluştur
    $message = "💳 <b>Kredi Kartı ile Ödeme Alındı!</b>\n\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "📋 <b>Sipariş No:</b> {$order['order_number']}\n";
    $message .= "📦 <b>Paket:</b> {$package['name']}\n";
    $message .= "📂 <b>Kategori:</b> {$package['category_name']}\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "👤 <b>Müşteri:</b> {$order['customer_name']}\n";
    $message .= "📧 <b>E-posta:</b> {$order['customer_email']}\n";
    
    if (!empty($order['customer_phone'])) {
        $message .= "📱 <b>Telefon:</b> {$order['customer_phone']}\n";
    }
    
    $message .= "🔗 <b>Hedef:</b> <code>{$order['social_media_link']}</code>\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "💰 <b>Tutar:</b> " . number_format($order['amount'], 2, ',', '.') . "{$currencySymbol}\n";
    
    // İndirim varsa göster
    if (!empty($order['discount_amount']) && $order['discount_amount'] > 0) {
        $message .= "🏷 <b>İndirim:</b> -" . number_format($order['discount_amount'], 2, ',', '.') . "{$currencySymbol}";
        if (!empty($order['coupon_code'])) {
            $message .= " ({$order['coupon_code']})";
        }
        $message .= "\n";
    }
    
    if (!empty($cardInfo)) {
        $message .= "<b>Kart:</b> {$cardInfo}\n";
    }
    
    $message .= "💳 <b>Taksit:</b> {$installmentText}\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "✅ <b>Durum:</b> ÖDEME BAŞARILI\n";
    $message .= "🔐 <b>Ödeme:</b> iyzico Güvencesi\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "📅 " . date('d.m.Y H:i') . " | {$siteName}";
    
    return sendTelegramNotification($message);
}

/**
 * Sipariş tamamlandı bildirimi
 */
function sendCompletedNotification($order, $package) {
    global $settings;
    
    // Bu bildirim tipi açık mı?
    if ($settings->get('telegram_notify_completed', '1') !== '1') {
        return ['success' => false, 'error' => 'Bu bildirim tipi kapalı'];
    }
    
    $siteName = defined('SITE_NAME') ? SITE_NAME : 'SMM Panel';
    $currencySymbol = $settings->get('currency_symbol', '₺');
    
    $message = "✅ <b>Sipariş Tamamlandı!</b>\n\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "📋 <b>Sipariş No:</b> {$order['order_number']}\n";
    $message .= "📦 <b>Paket:</b> {$package['name']}\n";
    $message .= "💰 <b>Tutar:</b> " . number_format($order['amount'], 2, ',', '.') . "{$currencySymbol}\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "👤 <b>Müşteri:</b> {$order['customer_name']}\n";
    $message .= "🔗 <b>Hedef:</b> <code>{$order['social_media_link']}</code>\n";
    
    // API siparişi ise ek bilgi
    if (!empty($order['api_order_id'])) {
        $message .= "━━━━━━━━━━━━━━━━━━━━\n";
        $message .= "🤖 <b>API Order:</b> #{$order['api_order_id']}\n";
        if (!empty($order['api_charge'])) {
            $message .= "💵 <b>API Maliyet:</b> " . number_format($order['api_charge'], 4, ',', '.') . "{$currencySymbol}\n";
            $profit = $order['amount'] - $order['api_charge'];
            $message .= "📈 <b>Kar:</b> " . number_format($profit, 2, ',', '.') . "{$currencySymbol}\n";
        }
    }
    
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "📅 " . date('d.m.Y H:i') . " | {$siteName}";
    
    return sendTelegramNotification($message);
}

/**
 * Sipariş iptal bildirimi
 */
function sendCancelledNotification($order, $package, $reason = '') {
    global $settings;
    
    // Tamamlandı bildirimi ayarını kullan
    if ($settings->get('telegram_notify_completed', '1') !== '1') {
        return ['success' => false, 'error' => 'Bu bildirim tipi kapalı'];
    }
    
    $siteName = defined('SITE_NAME') ? SITE_NAME : 'SMM Panel';
    $currencySymbol = $settings->get('currency_symbol', '₺');
    
    $message = "❌ <b>Sipariş İptal Edildi!</b>\n\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "📋 <b>Sipariş No:</b> {$order['order_number']}\n";
    $message .= "📦 <b>Paket:</b> {$package['name']}\n";
    $message .= "💰 <b>Tutar:</b> " . number_format($order['amount'], 2, ',', '.') . "{$currencySymbol}\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "👤 <b>Müşteri:</b> {$order['customer_name']}\n";
    
    if (!empty($reason)) {
        $message .= "📝 <b>Sebep:</b> {$reason}\n";
    }
    
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "📅 " . date('d.m.Y H:i') . " | {$siteName}";
    
    return sendTelegramNotification($message);
}

/**
 * İletişim formu bildirimi
 */
function sendContactNotification($name, $email, $subject, $messageContent) {
    global $settings;
    
    // Bu bildirim tipi açık mı?
    if ($settings->get('telegram_notify_contact', '1') !== '1') {
        return ['success' => false, 'error' => 'Bu bildirim tipi kapalı'];
    }
    
    $siteName = defined('SITE_NAME') ? SITE_NAME : 'SMM Panel';
    
    // Mesaj içeriğini kısalt (çok uzunsa)
    if (mb_strlen($messageContent) > 500) {
        $messageContent = mb_substr($messageContent, 0, 500) . '...';
    }
    
    // HTML özel karakterlerini escape et
    $messageContent = htmlspecialchars($messageContent, ENT_QUOTES, 'UTF-8');
    
    $message = "📬 <b>Yeni İletişim Mesajı!</b>\n\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "👤 <b>Ad:</b> {$name}\n";
    $message .= "📧 <b>E-posta:</b> {$email}\n";
    $message .= "📌 <b>Konu:</b> {$subject}\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "💬 <b>Mesaj:</b>\n{$messageContent}\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "📅 " . date('d.m.Y H:i') . " | {$siteName}";
    
    return sendTelegramNotification($message);
}

/**
 * Düşük API bakiyesi uyarısı
 */
function sendLowBalanceNotification($providerName, $balance, $currency = 'TRY') {
    global $settings;
    
    $siteName = defined('SITE_NAME') ? SITE_NAME : 'SMM Panel';
    
    $message = "⚠️ <b>Düşük API Bakiyesi!</b>\n\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "🔌 <b>Sağlayıcı:</b> {$providerName}\n";
    $message .= "💰 <b>Bakiye:</b> " . number_format($balance, 2, ',', '.') . " {$currency}\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "⚠️ Bakiyenizi kontrol edin!\n";
    $message .= "📅 " . date('d.m.Y H:i') . " | {$siteName}";
    
    return sendTelegramNotification($message);
}

/**
 * Şüpheli aktivite bildirimi
 */
function sendSuspiciousActivityNotification($ip, $orderCount, $totalAmount, $emails) {
    global $settings;
    
    $siteName = defined('SITE_NAME') ? SITE_NAME : 'SMM Panel';
    $currencySymbol = $settings->get('currency_symbol', '₺');
    
    $message = "🚨 <b>Şüpheli Aktivite Tespit Edildi!</b>\n\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "🌐 <b>IP Adresi:</b> <code>{$ip}</code>\n";
    $message .= "📊 <b>Sipariş Sayısı:</b> {$orderCount}\n";
    $message .= "💰 <b>Toplam Tutar:</b> " . number_format($totalAmount, 2, ',', '.') . "{$currencySymbol}\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "📧 <b>E-postalar:</b>\n{$emails}\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "⚠️ Lütfen kontrol edin!\n";
    $message .= "📅 " . date('d.m.Y H:i') . " | {$siteName}";
    
    return sendTelegramNotification($message);
}

/**
 * Genel bildirim gönder (özelleştirilebilir)
 */
function sendCustomNotification($title, $content, $emoji = '📢') {
    global $settings;
    
    $siteName = defined('SITE_NAME') ? SITE_NAME : 'SMM Panel';
    
    $message = "{$emoji} <b>{$title}</b>\n\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= $content . "\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "📅 " . date('d.m.Y H:i') . " | {$siteName}";
    
    return sendTelegramNotification($message);
}

/**
 * Günlük özet raporu
 */
function sendDailySummaryNotification($stats) {
    global $settings;
    
    $siteName = defined('SITE_NAME') ? SITE_NAME : 'SMM Panel';
    $currencySymbol = $settings->get('currency_symbol', '₺');
    
    $message = "📊 <b>Günlük Özet Raporu</b>\n\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "📅 <b>Tarih:</b> " . date('d.m.Y') . "\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "🛒 <b>Toplam Sipariş:</b> {$stats['total_orders']}\n";
    $message .= "✅ <b>Tamamlanan:</b> {$stats['completed_orders']}\n";
    $message .= "⏳ <b>Bekleyen:</b> {$stats['pending_orders']}\n";
    $message .= "❌ <b>İptal:</b> {$stats['cancelled_orders']}\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "💰 <b>Toplam Gelir:</b> " . number_format($stats['total_revenue'], 2, ',', '.') . "{$currencySymbol}\n";
    
    if (isset($stats['api_cost'])) {
        $message .= "💵 <b>API Maliyet:</b> " . number_format($stats['api_cost'], 2, ',', '.') . "{$currencySymbol}\n";
        $message .= "📈 <b>Net Kar:</b> " . number_format($stats['total_revenue'] - $stats['api_cost'], 2, ',', '.') . "{$currencySymbol}\n";
    }
    
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "🌐 {$siteName}";
    
    return sendTelegramNotification($message);
}