<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use DefStudio\Telegraph\Models\TelegraphBot;

class TelegramSetup extends Command
{
    /**
     * The name and signature of the console command.
     */
    protected $signature = 'telegram:setup 
                           {--webhook-url= : Custom webhook URL}
                           {--delete-webhook : Delete the current webhook}
                           {--check-webhook : Check webhook status}
                           {--set-commands : Set bot commands}';

    /**
     * The console command description.
     */
    protected $description = 'Setup and manage Telegram bot configuration';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        if ($this->option('delete-webhook')) {
            return $this->deleteWebhook();
        }

        if ($this->option('check-webhook')) {
            return $this->checkWebhook();
        }

        if ($this->option('set-commands')) {
            return $this->setBotCommands();
        }

        // Default: setup webhook
        return $this->setupWebhook();
    }

    /**
     * Setup Telegram webhook
     */
    private function setupWebhook(): void
    {
        $this->info('🤖 Setting up Telegram Bot Webhook');
        $this->line('==================================');

        $botToken = config('telegram.bot_token');
        if (!$botToken) {
            $this->error('❌ TELEGRAM_BOT_TOKEN not found in configuration');
            $this->line('Get your bot token from @BotFather and add it to your .env file');
            return;
        }

        $webhookUrl = $this->option('webhook-url') ?: config('telegram.webhook_url');
        if (!$webhookUrl) {
            $webhookUrl = config('app.url') . '/api/telegram/webhook';
        }

        $this->line("Bot Token: " . substr($botToken, 0, 10) . "...");
        $this->line("Webhook URL: {$webhookUrl}");

        if (!$this->confirm('Do you want to proceed with webhook setup?')) {
            $this->info('Setup cancelled');
            return;
        }

        try {
            // Set webhook
            $response = Http::timeout(30)->get("https://api.telegram.org/bot{$botToken}/setWebhook", [
                'url' => $webhookUrl,
                'allowed_updates' => json_encode(['message', 'callback_query']),
                'drop_pending_updates' => true,
            ]);

            if ($response->successful()) {
                $data = $response->json();
                if ($data['ok']) {
                    $this->info('✅ Webhook set successfully!');
                    $this->line("Description: {$data['description']}");
                } else {
                    $this->error("❌ Failed to set webhook: {$data['description']}");
                }
            } else {
                $this->error('❌ HTTP request failed: ' . $response->status());
            }

            // Verify webhook
            $this->newLine();
            $this->checkWebhook();

            // Setup bot commands
            $this->newLine();
            if ($this->confirm('Do you want to set up bot commands?')) {
                $this->setBotCommands();
            }

        } catch (\Exception $e) {
            $this->error("❌ Error setting webhook: " . $e->getMessage());
            Log::error('Telegram webhook setup failed', [
                'error' => $e->getMessage(),
                'webhook_url' => $webhookUrl
            ]);
        }
    }

    /**
     * Delete webhook
     */
    private function deleteWebhook(): void
    {
        $this->info('🗑️ Deleting Telegram Webhook');
        $this->line('============================');

        $botToken = config('telegram.bot_token');
        if (!$botToken) {
            $this->error('❌ TELEGRAM_BOT_TOKEN not found');
            return;
        }

        try {
            $response = Http::timeout(30)->get("https://api.telegram.org/bot{$botToken}/deleteWebhook", [
                'drop_pending_updates' => true
            ]);

            if ($response->successful()) {
                $data = $response->json();
                if ($data['ok']) {
                    $this->info('✅ Webhook deleted successfully!');
                } else {
                    $this->error("❌ Failed to delete webhook: {$data['description']}");
                }
            } else {
                $this->error('❌ HTTP request failed: ' . $response->status());
            }
        } catch (\Exception $e) {
            $this->error("❌ Error deleting webhook: " . $e->getMessage());
        }
    }

    /**
     * Check webhook status
     */
    private function checkWebhook(): void
    {
        $this->info('🔍 Checking Webhook Status');
        $this->line('=========================');

        $botToken = config('telegram.bot_token');
        if (!$botToken) {
            $this->error('❌ TELEGRAM_BOT_TOKEN not found');
            return;
        }

        try {
            $response = Http::timeout(30)->get("https://api.telegram.org/bot{$botToken}/getWebhookInfo");

            if ($response->successful()) {
                $data = $response->json();
                if ($data['ok']) {
                    $info = $data['result'];
                    
                    $this->table(['Property', 'Value'], [
                        ['URL', $info['url'] ?: 'Not set'],
                        ['Has Custom Certificate', $info['has_custom_certificate'] ? 'Yes' : 'No'],
                        ['Pending Update Count', $info['pending_update_count']],
                        ['Last Error Date', $info['last_error_date'] ? date('Y-m-d H:i:s', $info['last_error_date']) : 'None'],
                        ['Last Error Message', $info['last_error_message'] ?: 'None'],
                        ['Max Connections', $info['max_connections'] ?: 'Default (40)'],
                        ['Allowed Updates', implode(', ', $info['allowed_updates'] ?? ['all'])],
                    ]);

                    if ($info['url']) {
                        $this->info('✅ Webhook is configured');
                        if ($info['last_error_message']) {
                            $this->warn("⚠️ Last error: {$info['last_error_message']}");
                        }
                    } else {
                        $this->warn('⚠️ No webhook configured');
                    }
                } else {
                    $this->error("❌ API Error: {$data['description']}");
                }
            } else {
                $this->error('❌ HTTP request failed: ' . $response->status());
            }
        } catch (\Exception $e) {
            $this->error("❌ Error checking webhook: " . $e->getMessage());
        }
    }

    /**
     * Set bot commands
     */
    private function setBotCommands(): void
    {
        $this->info('⚙️ Setting Bot Commands');
        $this->line('======================');

        $botToken = config('telegram.bot_token');
        if (!$botToken) {
            $this->error('❌ TELEGRAM_BOT_TOKEN not found');
            return;
        }

        $commands = [
            ['command' => 'start', 'description' => 'شروع استفاده از ربات'],
            ['command' => 'help', 'description' => 'راهنمای استفاده'],
            ['command' => 'settings', 'description' => 'تنظیمات کاربری'],
            ['command' => 'notifications', 'description' => 'مدیریت اعلان‌ها'],
            ['command' => 'payment', 'description' => 'مدیریت پرداخت‌ها'],
            ['command' => 'subscribe', 'description' => 'عضویت در اعلان‌ها'],
            ['command' => 'unsubscribe', 'description' => 'لغو عضویت اعلان‌ها'],
        ];

        try {
            $response = Http::timeout(30)->post("https://api.telegram.org/bot{$botToken}/setMyCommands", [
                'commands' => json_encode($commands)
            ]);

            if ($response->successful()) {
                $data = $response->json();
                if ($data['ok']) {
                    $this->info('✅ Bot commands set successfully!');
                    
                    $this->table(['Command', 'Description'], array_map(function($cmd) {
                        return ['/' . $cmd['command'], $cmd['description']];
                    }, $commands));
                } else {
                    $this->error("❌ Failed to set commands: {$data['description']}");
                }
            } else {
                $this->error('❌ HTTP request failed: ' . $response->status());
            }
        } catch (\Exception $e) {
            $this->error("❌ Error setting commands: " . $e->getMessage());
        }
    }

    /**
     * Get bot information
     */
    private function getBotInfo(): void
    {
        $botToken = config('telegram.bot_token');
        if (!$botToken) {
            return;
        }

        try {
            $response = Http::timeout(30)->get("https://api.telegram.org/bot{$botToken}/getMe");
            
            if ($response->successful()) {
                $data = $response->json();
                if ($data['ok']) {
                    $bot = $data['result'];
                    
                    $this->newLine();
                    $this->info('🤖 Bot Information');
                    $this->line('=================');
                    
                    $this->table(['Property', 'Value'], [
                        ['ID', $bot['id']],
                        ['Name', $bot['first_name']],
                        ['Username', '@' . ($bot['username'] ?? 'not_set')],
                        ['Can Join Groups', $bot['can_join_groups'] ? 'Yes' : 'No'],
                        ['Can Read All Group Messages', $bot['can_read_all_group_messages'] ? 'Yes' : 'No'],
                        ['Supports Inline Queries', $bot['supports_inline_queries'] ? 'Yes' : 'No'],
                    ]);
                }
            }
        } catch (\Exception $e) {
            // Silently fail for bot info
        }
    }
}