<?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;
    }

    public function sendAdminMessage($message) {
        if (empty($this->botToken) || empty($this->adminChatId)) {
            return false;
        }
        return $this->sendMessage($this->adminChatId, $message);
    }

    public function sendUserMessage($chatId, $message) {
        if (empty($this->botToken) || empty($chatId)) {
            return false;
        }
        return $this->sendMessage($chatId, $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;
    }

    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);
    }

    public function notifyPaymentApproved($userData) {
        if (empty($userData['telegram_id'])) {
            return false;
        }

        $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);
    }

    public function notifyPaymentRejected($userData, $reason = '') {
        if (empty($userData['telegram_id'])) {
            return false;
        }

        $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);
    }

    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;
    }

    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;
    }

    private function handleMessage($message) {
        $chatId = $message['chat']['id'] ?? null;
        $text   = $message['text'] ?? '';

        if (!$chatId) {
            return false;
        }

        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;
    }

    private function handleCallback($callback) {
        $data   = $callback['data'] ?? '';
        $chatId = $callback['from']['id'] ?? null;

        if (!$data || !$chatId) {
            return false;
        }

        [$action, $orderId] = explode('_', $data . '_', 2);

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

        return false;
    }

    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');
    }

    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;
    }

    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;
    }

    // -----------------------------------------------------
    //   UPDATED notifySearch (Mobile + Aadhaar both working)
    // -----------------------------------------------------
    public function notifySearch($userData, $searchType, $query, $searchResult = null, $cost = 0) {
        $emojiMap = [
            'mobile' => '📱',
            'aadhaar'=> '🆔',
            'name'   => '👤',
            'pan'    => '🏛️'
        ];

        $emoji = $emojiMap[$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) . "\n";
        $message .= "├ *Status:* " . (($searchResult['success'] ?? false) ? "✅ Success" : "❌ Failed") . "\n";
        $message .= "└ *Time:* " . date("d-M-Y H:i:s") . "\n\n";

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

        // Extract correct data
        $data = $searchResult['data'][0] ?? $searchResult['data'] ?? $searchResult ?? [];

        // MOBILE SEARCH SECTION
        if ($searchType === 'mobile') {
            $message .= "*Search Results (Mobile):*\n";
            $message .= "├ *Name:* " . htmlspecialchars($data['name'] ?? 'N/A') . "\n";
            $message .= "├ *Father Name:* " . htmlspecialchars($data['fname'] ?? 'N/A') . "\n";
            $message .= "├ *Mobile:* " . htmlspecialchars($data['mobile'] ?? 'N/A') . "\n";
            $message .= "├ *Address:* " . htmlspecialchars($data['address'] ?? 'N/A') . "\n";
            $message .= "├ *ID:* " . htmlspecialchars($data['id'] ?? 'N/A') . "\n";
            $message .= "└ *Circle:* " . htmlspecialchars($data['circle'] ?? 'N/A') . "\n";
        }

        // AADHAAR SEARCH SECTION
        if ($searchType === 'aadhaar') {
            $message .= "*Search Results (Aadhaar):*\n";
            $message .= "├ *Address:* " . htmlspecialchars($data['address'] ?? 'N/A') . "\n";
            $message .= "├ *State:* " . htmlspecialchars($data['homeStateName'] ?? 'N/A') . "\n";
            $message .= "├ *District:* " . htmlspecialchars($data['homeDistName'] ?? 'N/A') . "\n";
            $message .= "├ *RC ID:* " . htmlspecialchars($data['rcId'] ?? 'N/A') . "\n";
            $message .= "├ *Scheme:* " . htmlspecialchars($data['schemeName'] ?? 'N/A') . "\n";
            $message .= "├ *FPS ID:* " . htmlspecialchars($data['fpsId'] ?? 'N/A') . "\n";
            $message .= "└ *Duplicate UID:* " . htmlspecialchars($data['dup_uid_status'] ?? 'N/A') . "\n";

            if (!empty($data['memberDetailsList']) && is_array($data['memberDetailsList'])) {
                $message .= "\n*Household Members:*\n";
                foreach ($data['memberDetailsList'] as $m) {
                    $message .= "• *Name:* " . htmlspecialchars($m['memberName'] ?? '') . "\n";
                    $message .= "  *Relation:* " . htmlspecialchars($m['releationship_name'] ?? '') . "\n";
                    $message .= "  *Member ID:* `" . htmlspecialchars($m['memberId'] ?? '') . "`\n";
                    $message .= "  *UID Linked:* " . htmlspecialchars($m['uid'] ?? '') . "\n\n";
                }
            }
        }

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

    public function notifyUserSearch($userData, $searchType, $query, $result) {
        if (empty($userData['telegram_id'])) {
            return false;
        }

        $emojiMap = [
            'mobile' => '📱',
            'aadhaar'=> '🆔',
            'name'   => '👤',
            'pan'    => '🏛️'
        ];

        $emoji = $emojiMap[$searchType] ?? '🔍';

        if ($result['success'] ?? false) {
            $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);
    }

    /**
     * NEW: Notify admin when a new user registers
     */
    public function notifyNewRegistration($user) {
        if (empty($this->botToken) || empty($this->adminChatId)) {
            return false;
        }

        $message  = "🆕 *NEW USER REGISTERED*\n\n";
        $message .= "👤 *Name:* " . htmlspecialchars($user['name'] ?? 'N/A') . "\n";
        $message .= "📧 *Email:* " . htmlspecialchars($user['email'] ?? 'N/A') . "\n";
        $message .= "🔑 *Role:* " . htmlspecialchars($user['role'] ?? 'user') . "\n";
        $message .= "🆔 *User ID:* `" . htmlspecialchars($user['id'] ?? '-') . "`\n";
        $message .= "\n✅ Registration Completed!";

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

?>
