<?php

namespace Modules\Bot\Http\Controllers;

use App\Modules\Bot\Http\Interfaces\MessengerBotInterface;
use App\Models\User;
use App\Modules\Bot\Models\UserBot;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class TelegramBot implements MessengerBotInterface
{
    private $botIdentifier;
    private $botToken;

    public function __construct()
    {
            $this->botIdentifier = config('bot.telegram_bot_identifier');
            $this->botToken = config('bot.telegram_bot_token');
    }

    public function handleWebhook(Request $request) 
    {
        $update = $request->all();

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

    private function handleMessage($message)
    {
        if (isset($message['text'])) {
            $text = $message['text'];
            $chatId = $message['chat']['id'];
            $command = strtolower(explode(' ', $text)[0]);

            switch ($command) {
                case '/start':
                    $this->handleStart($text, $chatId);
                    break;
                case '/stop':
                    $this->handleUnsubscribe($chatId);
                    break;
            }
        }
    }

    private function handleChatMemberUpdate($chatMember)
    {
        $chatId = $chatMember['chat']['id'];
        $newStatus = $chatMember['new_chat_member']['status'];

        if ($newStatus === 'kicked' || $newStatus === 'left') {
            $this->stopBot($chatId);
        }
    }

    private function handleStart($text, $chatId)
    {
        $parts = explode(' ', $text);
        if (count($parts) > 1) {
            $encryptedUserId = $parts[1];
            try {
                $userId = base64_decode($encryptedUserId);
                
                $user = User::find($userId);
                if ($user) {
                    UserBot::updateOrCreate(
                        ['user_id' => $userId, 'bot_id' => config('bot.telegram_bot_id')],
                        ['user_bot_id' => $chatId]
                    );
                    
                    $this->sendMessage($chatId, "Здравствуйте, {$user->name}! Вы успешно подписались на уведомления.");
                } else {
                    $this->sendMessage($chatId, "Извините, не удалось найти вашу учетную запись.");
                }
            } catch (\Exception $e) {
                Log::error('Error decrypting user ID', ['error' => $e->getMessage()]);
                $this->sendMessage($chatId, "Произошла ошибка при обработке вашего запроса.");
            }
        } else {
            $this->sendMessage($chatId, "Добро пожаловать! Для подписки на уведомления, пожалуйста, используйте ссылку с нашего сайта.");
        }
    }

    private function stopBot($chatId)
    {
        try {
            $userBot = UserBot::where('user_bot_id', $chatId)
                            ->where('bot_id', config('bot.telegram_bot_id'))
                            ->first();

            if ($userBot) {
                $userBot->delete();
                Log::info('User unsubscribed', ['chatId' => $chatId]);
            } else {
                Log::info('Unsubscribe attempt for non-subscribed user', ['chatId' => $chatId]);
            }
        } catch (\Exception $e) {
            Log::error('Error during unsubscribe process', ['error' => $e->getMessage(), 'chatId' => $chatId]);
        }
    }

    private function handleUnsubscribe($chatId)
    {
        try {
            $userBot = UserBot::where('user_bot_id', $chatId)
                            ->where('bot_id', config('bot.telegram_bot_id'))
                            ->first();

            if ($userBot) {
                $userBot->delete();
                $this->sendMessage($chatId, "Вы успешно отписались от уведомлений. Если захотите подписаться снова, воспользуйтесь ссылкой на нашем сайте.");
                Log::info('User unsubscribed', ['chatId' => $chatId]);
            } else {
                $this->sendMessage($chatId, "Вы не были подписаны на уведомления.");
                Log::info('Unsubscribe attempt for non-subscribed user', ['chatId' => $chatId]);
            }
        } catch (\Exception $e) {
            Log::error('Error during unsubscribe process', ['error' => $e->getMessage(), 'chatId' => $chatId]);
            $this->sendMessage($chatId, "Произошла ошибка при обработке вашего запроса. Пожалуйста, попробуйте позже.");
        }
    }

    public function subscribe() :mixed
    {
        $userId = Auth::id();
        $encryptedUserId = base64_encode($userId);
        
        $telegramUrl = "https://t.me/$this->botIdentifier?start=$encryptedUserId";
    
        return redirect($telegramUrl);
    }


    public static function sendMessage(string $userBotId, string $message): void
    {
        $botToken = config('bot.telegram_bot_token');
        Http::withoutVerifying()
        ->post("https://api.telegram.org/bot{$botToken}/sendMessage", [
            'chat_id' => $userBotId, 
            'text' => $message,
            'parse_mode' => 'HTML'
        ]);
    }

    public function setHook() 
    {
        $response = Http::withoutVerifying()
            ->post("https://api.telegram.org/bot{$this->botToken}/setWebhook", [
            'url' => 'https://naviom.iro38.ru/api/telegramWebhook',
            'allowed_updates' => ['message', 'my_chat_member']
        ])->json();
        dd($response);
    }
}