<?php
namespace Bot\Commands\UserCommands;

use Bot\Config;
use Bot\Database;
use Bot\Localization;
use Bot\Services\ReferralService;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Entities\Keyboard;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Request;

class StartCommand extends UserCommand
{
    protected $name = 'start';
    protected $description = 'Start the bot';
    protected $usage = '/start [referral_code]';
    protected $version = '2.0.0';

    public function execute(): ServerResponse
    {
        $message    = $this->getMessage();
        $chat       = $message->getChat();
        $chatId     = $chat->getId();
        $user       = $message->getFrom();
        $telegramId = $user->getId();
        $username   = $user->getUsername() ?? '';
        $firstName  = $user->getFirstName() ?? '';
        $lastName   = $user->getLastName() ?? '';
        $langCode   = $user->getLanguageCode() ?? 'en';
        $param      = trim($message->getText(true) ?? '');

        $pdo = Database::connection();
        $config = Config::get();
        $defaults = $config->getValue('limits_defaults', []);
        $limitsJson = json_encode($defaults);
        $defaultNetwork = $config->getValue('default_network', 'ERC20');
        $referralService = new ReferralService();

        $stmt = $pdo->prepare('SELECT * FROM users WHERE telegram_id = ?');
        $stmt->execute([$telegramId]);
        $row = $stmt->fetch();

        if (!$row) {
            $refCode = $referralService->generateCode();
            $insert = $pdo->prepare(
                'INSERT INTO users (telegram_id, username, first_name, last_name, language, default_network, referral_code, limits, created_at)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())'
            );
            $insert->execute([
                $telegramId,
                $username,
                $firstName,
                $lastName,
                $langCode,
                $defaultNetwork,
                $refCode,
                $limitsJson,
            ]);
            $stmt = $pdo->prepare('SELECT * FROM users WHERE telegram_id = ?');
            $stmt->execute([$telegramId]);
            $row = $stmt->fetch();
        } else {
            if (empty($row['referral_code'])) {
                $newCode = $referralService->generateCode();
                $pdo->prepare('UPDATE users SET referral_code = ? WHERE id = ?')->execute([$newCode, $row['id']]);
                $row['referral_code'] = $newCode;
            }
            if (empty($row['limits'])) {
                $pdo->prepare('UPDATE users SET limits = ? WHERE id = ?')->execute([$limitsJson, $row['id']]);
            }
        }
        if (!empty($row['is_banned'])) {
            return Request::sendMessage([
                'chat_id' => $chatId,
                'text'    => Localization::t($row['language'] ?? 'en', 'account_banned_message'),
            ]);
        }

        if ($param !== '') {
            $referralService->linkReferrer((int) $row['id'], $param);
        }

        $lang = $row['language'] ?: 'en';
        // Group buttons by intent (buy, sell, account, support) so the menu feels structured.
        $keyboard = new Keyboard(
            ['🅿️ P2P', '👛 Wallet'],
            ['💳 Virtual Card', '👤 My Profile'],
            ['🎁 Free', '🆘 Help & Support']
        );
        $keyboard->setResizeKeyboard(true)
                 ->setOneTimeKeyboard(false)
                 ->setSelective(false);

        return Request::sendMessage([
            'chat_id'      => $chatId,
            'text'         => Localization::t($lang, 'main_menu_prompt'),
            'reply_markup' => $keyboard,
        ]);
    }
}
