<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Telegram\Bot\Api;
use App\Services\TelegramBotService;

class TelegramPolling extends Command
{
    protected $signature = 'telegram:poll';
    protected $description = 'Start Telegram Bot Polling (Long Polling)';

    public function handle()
    {
        $this->info('🚀 Elite Crypto Bot Started...');
        $this->info('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');

        $telegram = new Api(env('TELEGRAM_BOT_TOKEN'));

        // SSL verification disable for development
        $client = new \GuzzleHttp\Client(['verify' => false]);
        $telegram->setHttpClientHandler(
            new \Telegram\Bot\HttpClients\GuzzleHttpClient($client)
        );

        $botService = new TelegramBotService();
        $offset = 0;

        while (true) {
            try {
                $updates = $telegram->getUpdates([
                    'offset' => $offset,
                    'timeout' => 30,
                    'limit' => 100
                ]);

                foreach ($updates as $update) {
                    $offset = $update->getUpdateId() + 1;

                    $this->processUpdate($update, $botService);
                }
            } catch (\Exception $e) {
                $this->error('❌ Error: ' . $e->getMessage());
                $this->info('⏳ Retrying in 5 seconds...');
                sleep(5);
            }
        }
    }

    protected function processUpdate($update, $botService)
    {
        try {
            if (!$update->getMessage()) {
                return;
            }

            $message = $update->getMessage();
            $from = $message->getFrom();
            $text = $message->getText() ?? 'Media';

            $this->info("📨 Message from {$from->getFirstName()} ({$from->getId()}): {$text}");

            $botService->handleUpdate($update);

            $this->info("✅ Processed successfully");
            $this->info("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
        } catch (\Exception $e) {
            $this->error("❌ Failed to process update: {$e->getMessage()}");
        }
    }
}