<?php
declare(strict_types=1);

$config = require __DIR__ . '/config.php';
require __DIR__ . '/functions.php';

date_default_timezone_set('UTC');

ensureDirectories($config);

$raw = file_get_contents('php://input');
if (!$raw) {
    http_response_code(200);
    exit('OK');
}

// Log the update (but limit size to prevent log spam)
$logData = $raw;
if (strlen($logData) > 500) {
    $logData = substr($logData, 0, 500) . '... (truncated)';
}
logLine($config, $logData);

$update = json_decode($raw, true);
if (!is_array($update)) {
    logLine($config, 'Invalid JSON payload');
    exit;
}

$message = $update['message'] ?? null;
if (!$message) {
    exit;
}

$chat = $message['chat'] ?? [];
$chatType = $chat['type'] ?? '';
if (!in_array($chatType, ['group', 'supergroup'], true)) {
    exit;
}

$text = trim($message['text'] ?? '');
if ($text === '') {
    exit;
}

$chatId = $chat['id'];
$userId = $message['from']['id'] ?? 0;

if (isFlood($config, $chatId, $userId)) {
    sendTelegram('sendMessage', [
        'chat_id' => $chatId,
        'text' => "⏱ لطفاً کمی صبر کنید و دوباره تلاش کنید.",
    ], $config);
    exit;
}

$handled = false;
$normalized = mb_strtolower($text, 'UTF-8');

// Check for transaction links first
[$txHash, $networkHint] = extractTransactionHash($text);
if ($txHash) {
    try {
        $handled = handleTransactionLookup($txHash, $networkHint, $config, $chatId);
    } catch (Exception $e) {
        logError($config, 'Exception in handleTransactionLookup: ' . $e->getMessage());
        $handled = true; // Mark as handled to prevent infinite loop
    } catch (Error $e) {
        logError($config, 'Fatal error in handleTransactionLookup: ' . $e->getMessage());
        $handled = true; // Mark as handled to prevent infinite loop
    }
}

if (!$handled) {
    // Check for card info request (reply with "اطلاعات")
    if (
        isset($message['reply_to_message']) &&
        isset($message['reply_to_message']['text']) &&
        $text === 'اطلاعات'
    ) {
        $replyText = $message['reply_to_message']['text'] ?? '';
        
        // Extract 16-digit card number from replied message
        if (preg_match('/\b(\d{16})\b/', $replyText, $matches)) {
            $cardNumber = $matches[1];
            $cardInfo = fetchCardInfo($cardNumber, $config);
            
            if ($cardInfo) {
                $bank = $cardInfo['bankName'] ?? '-';
                $bank = str_replace('_', ' ', $bank);
                $name = $cardInfo['depositOwners'] ?? '-';
                $deposit = $cardInfo['deposit'] ?? '-';
                $iban = $cardInfo['IBAN'] ?? '-';
                $depositStatus = $cardInfo['depositStatus'] ?? '-';
                $bankCode = $cardInfo['bankCode'] ?? '-';
                
                $depositStatusText = $depositStatus;
                if ($depositStatus === '01') $depositStatusText = 'فعال';
                elseif ($depositStatus === '02') $depositStatusText = 'مسدود';
                elseif ($depositStatus === '03') $depositStatusText = 'راکد';
                
                // Card info message
                $messageText = "💳 <b>اطلاعات کامل کارت بانکی</b> 💳\n";
                $messageText .= "━━━━━━━━━━━━━━━━━━\n";
                $messageText .= "🏦 <b>بانک:</b> <code>" . htmlspecialchars($bank) . "</code>\n";
                $messageText .= "👤 <b>دارنده:</b> <code>" . htmlspecialchars($name) . "</code>\n";
                $messageText .= "💳 <b>شماره کارت:</b> <code>" . htmlspecialchars($cardNumber) . "</code>\n";
                $messageText .= "🏦 <b>شماره شبا:</b> <code>" . htmlspecialchars($iban) . "</code>\n";
                $messageText .= "📄 <b>شماره سپرده:</b> <code>" . htmlspecialchars($deposit) . "</code>\n";
                $messageText .= "━━━━━━━━━━━━━━━━━━\n";
                $messageText .= "🟢 <i>اطلاعات فوق جهت بررسی و استعلام ارائه شده است.</i>";
                
                // Add inline keyboard with channel button
                $inlineKeyboard = [
                    [
                        [
                            'text' => "📢 عضویت در کانال ما",
                            'url' => "https://t.me/PolVasete"
                        ]
                    ]
                ];
                
                sendTelegram('sendMessage', [
                    'chat_id' => $chatId,
                    'reply_to_message_id' => $message['message_id'],
                    'text' => $messageText,
                    'parse_mode' => 'HTML',
                    'reply_markup' => json_encode(['inline_keyboard' => $inlineKeyboard]),
                ], $config);
            } else {
                sendTelegram('sendMessage', [
                    'chat_id' => $chatId,
                    'reply_to_message_id' => $message['message_id'],
                    'text' => "❌ اطلاعاتی برای این شماره کارت یافت نشد یا کارت نامعتبر است.",
                    'parse_mode' => 'HTML',
                ], $config);
            }
        } else {
            sendTelegram('sendMessage', [
                'chat_id' => $chatId,
                'reply_to_message_id' => $message['message_id'],
                'text' => "❌ شماره کارت معتبر در پیام ریپلای‌شده پیدا نشد.",
                'parse_mode' => 'HTML',
            ], $config);
        }
        $handled = true;
    } elseif ($normalized === '/start') {
        $text = "👋 ربات فعال است.\n- لینک تراکنش TRX یا TON بفرست تا جزئیات تراکنش برگردد.\n- کلمه‌های tron / trx / ton / usdt را بفرست تا قیمت‌ها را ببینی.";
        sendTelegram('sendMessage', [
            'chat_id' => $chatId,
            'parse_mode' => 'HTML',
            'text' => $text,
        ], $config);
        $handled = true;
    } elseif (containsKeyword($normalized, ['tron', 'trx', '/trx', '/tron', 'ترون'])) {
        $data = fetchTrxMarketSnapshot($config);
        if ($data) {
            $caption = sprintf(
                "<b>TRX / USDT</b>\nقیمت لحظه‌ای: <b>$%s</b>\nتغییر ۲۴ساعته: %s%%",
                number_format($data['price'], 4),
                number_format($data['percent'], 2)
            );
            if (!empty($data['price_toman'])) {
                $caption .= sprintf(
                    "\nقیمت به تومان: <b>%s تومان</b>",
                    number_format($data['price_toman'], 0)
                );
            }
            if (!empty($data['chart_error'])) {
                $caption .= "\n⚠️ " . htmlspecialchars($data['chart_error']);
            }
            $sent = false;
            $imageUrl = null;
            try {
                logLine($config, 'Generating TRX card with candles count: ' . count($data['candles'] ?? []));
                $imageUrl = generateTrxCard($data, $config);
                logLine($config, 'TRX card generated, result: ' . ($imageUrl ?? 'null'));
            } catch (Exception $e) {
                logError($config, 'Exception in generateTrxCard: ' . $e->getMessage());
            } catch (Error $e) {
                logError($config, 'Fatal error in generateTrxCard: ' . $e->getMessage());
            }
            
            if ($imageUrl) {
                // Check if it's a file path or URL
                if (file_exists($imageUrl)) {
                    logLine($config, 'Sending TRX image file: ' . $imageUrl);
                    // It's a local file, send it directly
                    $sent = sendTelegram('sendPhoto', [
                        'chat_id' => $chatId,
                        'photo' => $imageUrl,
                        'caption' => $caption,
                        'parse_mode' => 'HTML',
                    ], $config);
                } else {
                    logLine($config, 'Sending TRX image URL: ' . $imageUrl);
                    // It's a URL
                    $sent = sendTelegram('sendPhoto', [
                        'chat_id' => $chatId,
                        'photo' => $imageUrl,
                        'caption' => $caption,
                        'parse_mode' => 'HTML',
                    ], $config);
                }
            }
            
            if (!$sent) {
                logError($config, 'TRX photo send failed, falling back to text. ImageUrl was: ' . ($imageUrl ?? 'null'));
                sendTelegram('sendMessage', [
                    'chat_id' => $chatId,
                    'parse_mode' => 'HTML',
                    'text' => $caption,
                ], $config);
            }
        } else {
            logError($config, 'TRX snapshot fetch failed');
            sendTelegram('sendMessage', [
                'chat_id' => $chatId,
                'text' => "❌ خطا در دریافت قیمت TRX.",
            ], $config);
        }
        $handled = true;
    } elseif (containsKeyword($normalized, ['/ton', 'ton', 'تون'])) {
        $ton = fetchTonPrice($config);
        if ($ton) {
            $caption = sprintf(
                "<b>TON / USDT</b>\nقیمت: <b>$%s</b>\nتغییر ۲۴ساعته: %s%%",
                number_format($ton['price'], 3),
                number_format($ton['percent'], 2)
            );
            if (!empty($ton['price_toman'])) {
                $caption .= sprintf(
                    "\nقیمت به تومان: <b>%s تومان</b>",
                    number_format($ton['price_toman'], 0)
                );
            }
            if (!empty($ton['chart_error'])) {
                $caption .= "\n⚠️ " . htmlspecialchars($ton['chart_error']);
            }
            $sent = false;
            $imageUrl = generateTonCard($ton, $config);
            if ($imageUrl) {
                $sent = sendTelegram('sendPhoto', [
                    'chat_id' => $chatId,
                    'photo' => $imageUrl,
                    'caption' => $caption,
                    'parse_mode' => 'HTML',
                ], $config);
            }
            if (!$sent) {
                logError($config, 'TON photo send failed, falling back to text');
                sendTelegram('sendMessage', [
                    'chat_id' => $chatId,
                    'parse_mode' => 'HTML',
                    'text' => $caption,
                ], $config);
            }
        } else {
            logError($config, 'TON price fetch failed');
            sendTelegram('sendMessage', [
                'chat_id' => $chatId,
                'text' => "خطا در دریافت قیمت TON",
            ], $config);
        }
        $handled = true;
    } elseif (containsKeyword($normalized, ['usdt', '/tether', 'تتر', 'دلار'])) {
        $usdt = fetchUsdtToman($config);
        if ($usdt) {
            $caption = sprintf(
                "<b>USDT / IRT</b>\nقیمت لحظه‌ای: <b>%s تومان</b>\nتغییر ۲۴ساعته: %s%%",
                number_format($usdt['price']),
                number_format($usdt['change'], 2)
            );
            $sent = false;
            $imageUrl = generateUsdtCard($usdt, $config);
            if ($imageUrl) {
                $sent = sendTelegram('sendPhoto', [
                    'chat_id' => $chatId,
                    'photo' => $imageUrl,
                    'caption' => $caption,
                    'parse_mode' => 'HTML',
                ], $config);
            }
            if (!$sent) {
                logError($config, 'USDT photo send failed, falling back to text');
                sendTelegram('sendMessage', [
                    'chat_id' => $chatId,
                    'parse_mode' => 'HTML',
                    'text' => $caption,
                ], $config);
            }
        } else {
            logError($config, 'USDT price fetch failed');
            sendTelegram('sendMessage', [
                'chat_id' => $chatId,
                'text' => "❌ خطا در دریافت قیمت USDT.",
            ], $config);
        }
        $handled = true;
    }
}

if (!$handled) {
    logLine($config, 'No action for message: ' . $text);
}
