<?php

class TelegramBot {
    private $botToken;
    private $adminChatId;
    private $apiUrl = 'https://api.telegram.org/bot';

    public function __construct($botToken = '', $adminChatId = '') {
        $this->botToken = $botToken;
        $this->adminChatId = $adminChatId;
    }

    /**
     * Send message to admin
     */
    public function sendAdminMessage($message) {
        if (empty($this->botToken) || empty($this->adminChatId)) {
            return false;
        }

        return $this->sendMessage($this->adminChatId, $message);
    }

    /**
     * Send message to user
     */
    public function sendUserMessage($chatId, $message) {
        if (empty($this->botToken)) {
            return false;
        }

        return $this->sendMessage($chatId, $message);
    }

    /**
     * Send generic message
     */
    private function sendMessage($chatId, $message) {
        $url = $this->apiUrl . $this->botToken . '/sendMessage';

        $data = [
            'chat_id' => $chatId,
            'text' => $message,
            'parse_mode' => 'Markdown'
        ];

        $options = [
            'http' => [
                'method' => 'POST',
                'header' => 'Content-type: application/x-www-form-urlencoded',
                'content' => http_build_query($data),
                'timeout' => 10
            ]
        ];

        $context = stream_context_create($options);
        $response = @file_get_contents($url, false, $context);

        return $response !== false;
    }

    /**
     * Send payment notification to admin
     */
    public function notifyPaymentSubmission($userData, $orderData) {
        $message = "💳 *NEW PAYMENT SUBMITTED*\n\n";
        $message .= "👤 *User:* " . htmlspecialchars($userData['name']) . "\n";
        $message .= "📧 *Email:* " . htmlspecialchars($userData['email']) . "\n";
        $message .= "📦 *Package:* " . htmlspecialchars($orderData['package_name']) . "\n";
        $message .= "💰 *Amount:* ₹" . number_format($orderData['amount'], 2) . "\n";
        $message .= "🔢 *UTR:* " . htmlspecialchars($orderData['transaction_id']) . "\n";
        $message .= "🆔 *Order:* `" . htmlspecialchars($orderData['order_id']) . "`\n\n";
        $message .= "_Go to admin panel to approve/reject_";

        return $this->sendAdminMessage($message);
    }

    /**
     * Send approval confirmation
     */
    public function notifyPaymentApproved($userData) {
        $message = "✅ *PAYMENT APPROVED*\n\n";
        $message .= "Hello " . htmlspecialchars($userData['name']) . ",\n";
        $message .= "Your payment has been verified and credits have been added to your account!";

        return $this->sendUserMessage($userData['telegram_id'] ?? '', $message);
    }

    /**
     * Send rejection notification
     */
    public function notifyPaymentRejected($userData, $reason = '') {
        $message = "❌ *PAYMENT REJECTED*\n\n";
        $message .= "Hello " . htmlspecialchars($userData['name']) . ",\n";
        $message .= "Your payment could not be verified.\n\n";
        
        if (!empty($reason)) {
            $message .= "*Reason:* " . htmlspecialchars($reason) . "\n\n";
        }
        
        $message .= "Please contact support for more information.";

        return $this->sendUserMessage($userData['telegram_id'] ?? '', $message);
    }

    /**
     * Set webhook for receiving messages
     */
    public function setWebhook($webhookUrl) {
        $url = $this->apiUrl . $this->botToken . '/setWebhook';

        $data = [
            'url' => $webhookUrl
        ];

        $options = [
            'http' => [
                'method' => 'POST',
                'header' => 'Content-type: application/x-www-form-urlencoded',
                'content' => http_build_query($data)
            ]
        ];

        $context = stream_context_create($options);
        $response = @file_get_contents($url, false, $context);

        return $response !== false;
    }

    /**
     * Handle incoming webhook
     */
    public function handleUpdate() {
        $update = json_decode(file_get_contents('php://input'), true);

        if (!$update) {
            return false;
        }

        if (isset($update['message'])) {
            return $this->handleMessage($update['message']);
        }

        if (isset($update['callback_query'])) {
            return $this->handleCallback($update['callback_query']);
        }

        return false;
    }

    /**
     * Process incoming message
     */
    private function handleMessage($message) {
        $chatId = $message['chat']['id'];
        $text = $message['text'] ?? '';

        // Handle /start command
        if ($text === '/start') {
            $startMessage = "🤖 Welcome to Payment Bot!\n\n";
            $startMessage .= "This bot sends you payment notifications and updates.\n";
            $startMessage .= "_Your Chat ID: `" . $chatId . "`_";

            $this->sendMessage($chatId, $startMessage);
            return true;
        }

        return false;
    }

    /**
     * Process callback queries (button clicks)
     */
    private function handleCallback($callback) {
        $data = $callback['data'];
        $chatId = $callback['from']['id'];

        // Parse callback data format: action_orderId
        [$action, $orderId] = explode('_', $data . '_');

        if ($action === 'approve') {
            return $this->processApproval($orderId);
        } elseif ($action === 'reject') {
            return $this->processRejection($orderId);
        }

        return false;
    }

    /**
     * Process approval from Telegram
     */
    private function processApproval($orderId) {
        require_once(__DIR__ . '/../config/config.php');
        require_once(__DIR__ . '/Database.php');
        require_once(__DIR__ . '/Payment.php');

        $db = Database::getInstance();
        $payment = new Payment();

        return $payment->confirmPayment($orderId, 'TELEGRAM_APPROVED', 'telegram');
    }

    /**
     * Process rejection from Telegram
     */
    private function processRejection($orderId) {
        require_once(__DIR__ . '/../config/config.php');
        require_once(__DIR__ . '/Database.php');

        $db = Database::getInstance();

        $result = $db->query(
            'UPDATE payment_orders SET status = "failed" WHERE order_id = ?',
            [$orderId]
        );

        return $result !== false;
    }

    /**
     * Send inline keyboard with approval buttons
     */
    public function sendApprovalButtons($chatId, $message, $orderId) {
        $url = $this->apiUrl . $this->botToken . '/sendMessage';

        $keyboard = [
            'inline_keyboard' => [
                [
                    [
                        'text' => '✅ Approve',
                        'callback_data' => 'approve_' . $orderId
                    ],
                    [
                        'text' => '❌ Reject',
                        'callback_data' => 'reject_' . $orderId
                    ]
                ]
            ]
        ];

        $data = [
            'chat_id' => $chatId,
            'text' => $message,
            'parse_mode' => 'Markdown',
            'reply_markup' => json_encode($keyboard)
        ];

        $options = [
            'http' => [
                'method' => 'POST',
                'header' => 'Content-type: application/x-www-form-urlencoded',
                'content' => http_build_query($data)
            ]
        ];

        $context = stream_context_create($options);
        @file_get_contents($url, false, $context);

        return true;
    }

    /**
     * Notify admin of new user registration
     */
    public function notifyNewRegistration($userData) {
        $message = "👤 *NEW USER REGISTRATION*\n\n";
        $message .= "🎉 A new user has joined the platform!\n\n";
        $message .= "*User Details:*\n";
        $message .= "├ *Name:* " . htmlspecialchars($userData['name']) . "\n";
        $message .= "├ *Email:* `" . htmlspecialchars($userData['email']) . "`\n";
        $message .= "├ *Role:* " . ucfirst($userData['role']) . "\n";
        $message .= "├ *Wallet:* ₹0.00\n";
        $message .= "└ *Joined:* " . date('d-M-Y H:i:s') . "\n\n";
        $message .= "_New user is now ready to start searching_";

        return $this->sendAdminMessage($message);
    }

    /**
     * Notify admin of user search activity with complete details
     */
    public function notifySearch($userData, $searchType, $query, $searchResult = null, $cost = 0) {
        $statusEmoji = ['mobile' => '📱', 'aadhaar' => '🆔', 'name' => '👤', 'pan' => '🏛️'];
        $emoji = $statusEmoji[$searchType] ?? '🔍';

        $message = $emoji . " *USER SEARCH ACTIVITY*\n\n";
        $message .= "*Search Details:*\n";
        $message .= "├ *Type:* " . strtoupper($searchType) . "\n";
        $message .= "├ *Query:* `" . htmlspecialchars($query) . "`\n";
        $message .= "├ *Cost:* ₹" . number_format($cost, 2) . " credits\n";
        $message .= "├ *Status:* " . (($searchResult && isset($searchResult['success']) && $searchResult['success']) ? "✅ Success" : "❌ Failed") . "\n";
        $message .= "├ *Timestamp:* " . date('d-M-Y H:i:s') . "\n";

        $message .= "\n*User Details:*\n";
        $message .= "├ *Name:* " . htmlspecialchars($userData['name']) . "\n";
        $message .= "├ *Email:* `" . htmlspecialchars($userData['email']) . "`\n";
        $message .= "├ *User ID:* `" . htmlspecialchars($userData['id']) . "`\n";
        $phone = $userData['phone'] ?? $userData['phone_number'] ?? $userData['mobile'] ?? 'N/A';
        $message .= "└ *Phone:* " . htmlspecialchars($phone) . "\n";

        // Add result details if available and search was successful
        if ($searchResult && isset($searchResult['success']) && $searchResult['success'] && isset($searchResult['data'])) {
            $resultData = $searchResult['data'];
            $message .= "\n*Search Results:*\n";

            if ($searchType === 'mobile') {
                $message .= "├ *Network:* " . htmlspecialchars($resultData['network'] ?? 'N/A') . "\n";
                $message .= "├ *Operator:* " . htmlspecialchars($resultData['operator'] ?? 'N/A') . "\n";
                $message .= "├ *Circle:* " . htmlspecialchars($resultData['circle'] ?? 'N/A') . "\n";
                $message .= "├ *State:* " . htmlspecialchars($resultData['state'] ?? 'N/A') . "\n";
                $message .= "└ *Type:* " . htmlspecialchars($resultData['type'] ?? 'N/A') . "\n";
            } elseif ($searchType === 'aadhaar') {
                // Extract data from nested structure if it exists
                $data = isset($resultData['data']) ? $resultData['data'] : $resultData;
                
                $message .= "├ *Name:* " . htmlspecialchars($data['name'] ?? $data['fullName'] ?? $data['name_'] ?? 'N/A') . "\n";
                $message .= "├ *DOB:* " . htmlspecialchars($data['dob'] ?? $data['dateOfBirth'] ?? 'N/A') . "\n";
                $message .= "├ *Gender:* " . htmlspecialchars($data['gender'] ?? 'N/A') . "\n";
                $message .= "├ *Address:* " . htmlspecialchars($data['address'] ?? $data['addressLine1'] ?? 'N/A') . "\n";
                $message .= "└ *State:* " . htmlspecialchars($data['state'] ?? $data['homeStateName'] ?? $data['stateUI'] ?? 'N/A') . "\n";
            } elseif ($searchType === 'name') {
                $message .= "├ *First Name:* " . htmlspecialchars($resultData['first_name'] ?? 'N/A') . "\n";
                $message .= "├ *Last Name:* " . htmlspecialchars($resultData['last_name'] ?? 'N/A') . "\n";
                $message .= "├ *Father Name:* " . htmlspecialchars($resultData['father_name'] ?? 'N/A') . "\n";
                $message .= "├ *Age:* " . htmlspecialchars($resultData['age'] ?? 'N/A') . "\n";
                $message .= "├ *Gender:* " . htmlspecialchars($resultData['gender'] ?? 'N/A') . "\n";
                $message .= "├ *Village:* " . htmlspecialchars($resultData['village'] ?? 'N/A') . "\n";
                $message .= "├ *District:* " . htmlspecialchars($resultData['district'] ?? 'N/A') . "\n";
                $message .= "└ *State:* " . htmlspecialchars($resultData['state'] ?? 'N/A') . "\n";
            }
        } else {
            $message .= "\n*Results:* N/A (Search failed or no data returned)\n";
        }

        return $this->sendAdminMessage($message);
    }

    /**
     * Notify user (to their telegram) about search completion
     */
    public function notifyUserSearch($userData, $searchType, $query, $result) {
        if (empty($userData['telegram_id'])) {
            return false;
        }

        $statusEmoji = ['mobile' => '📱', 'aadhaar' => '🆔', 'name' => '👤', 'pan' => '🏛️'];
        $emoji = $statusEmoji[$searchType] ?? '🔍';

        if (isset($result['success']) && $result['success']) {
            $message = $emoji . " *Search Completed Successfully*\n\n";
            $message .= "*Type:* " . strtoupper($searchType) . "\n";
            $message .= "*Query:* `" . htmlspecialchars($query) . "`\n";
            $message .= "*Status:* ✅ Results Found\n\n";
            $message .= "_Check your dashboard for detailed results_";
        } else {
            $message = $emoji . " *Search Failed*\n\n";
            $message .= "*Type:* " . strtoupper($searchType) . "\n";
            $message .= "*Query:* `" . htmlspecialchars($query) . "`\n";
            $message .= "*Status:* ❌ " . ($result['message'] ?? 'Search failed') . "\n";
        }

        return $this->sendUserMessage($userData['telegram_id'], $message);
    }
}

?>
