<?php

namespace App\Http\Controllers;

use App\Services\TelegramService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Telegram\Bot\Objects\Update;

class TelegramWebhookController extends Controller
{
    protected $telegramService;

    public function __construct(TelegramService $telegramService)
    {
        $this->telegramService = $telegramService;
    }

    /**
     * Handle incoming webhook from Telegram
     */
    public function handle(Request $request)
    {
        $update = new Update($request->all());

        Log::info('Telegram Webhook Received', $request->all());

        // Handle callback query (inline keyboard clicks)
        if ($update->has('callback_query')) {
            return $this->telegramService->handleCallbackQuery($update);
        }

        // Handle regular messages
        if ($update->has('message')) {
            $message = $update->getMessage();
            $chatId = $message->getChat()->getId();
            $text = $message->getText();

            return $this->handleCommand($chatId, $text, $update);
        }

        return response('OK', 200);
    }

    /**
     * Handle bot commands
     */
    protected function handleCommand($chatId, $text, Update $update)
    {
        $command = explode(' ', $text)[0];

        switch ($command) {
            case '/start':
                $this->telegramService->sendWelcomeMessage($chatId);
                break;

            case '/status':
                $this->telegramService->sendStatusSummary($chatId);
                break;

            case '/pending':
                $this->telegramService->sendPendingExtensions($chatId);
                break;

            case '/help':
                $this->telegramService->sendWelcomeMessage($chatId);
                break;

            default:
                $this->telegramService->sendMessage($chatId, 'Perintah tidak dikenal. Ketik /help untuk bantuan.');
        }

        return response('OK', 200);
    }

    /**
     * Set webhook URL
     */
    public function setWebhook()
    {
        $url = config('telegram.webhook_url');
        
        if (empty($url)) {
            return $this->errorResponse('Webhook URL not configured', 400);
        }

        $result = $this->telegramService->setWebhook($url);

        if ($result) {
            return $this->successResponse([
                'message' => 'Webhook set successfully',
                'url' => $url,
                'result' => $result
            ]);
        }

        return $this->errorResponse('Failed to set webhook', 500);
    }

    /**
     * Remove webhook
     */
    public function removeWebhook()
    {
        $result = $this->telegramService->removeWebhook();

        if ($result) {
            return $this->successResponse([
                'message' => 'Webhook removed successfully',
                'result' => $result
            ]);
        }

        return $this->errorResponse('Failed to remove webhook', 500);
    }

    /**
     * Get bot info (for testing)
     */
    public function getBotInfo()
    {
        $info = $this->telegramService->getMe();

        if ($info) {
            return $this->successResponse([
                'bot_info' => $info->toArray()
            ]);
        }

        return $this->errorResponse('Failed to get bot info', 500);
    }
}