<?php
namespace App\Controller;
use App\Controller\Classes\Telegram;
use App\Entity\Adressen;
use App\Entity\City;
use App\Entity\OrderUkraine;
use App\Entity\User;
use App\Entity\RegistrationStep;
use App\Service\RegistrationHandlerTelegram;
use Borsaco\TelegramBotApiBundle\Service\Bot;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
class TelegramBotController extends AbstractController
{
public EntityManagerInterface $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
#[Route('/admin/sendToTelegramUser', name: 'testDVB2222222')]
public function sendToTelegramUser(Bot $bot, EntityManagerInterface $entityManager): Response
{
$users = $entityManager->getRepository(User::class)->findAll();
foreach ($users as $user) {
if($user->getTelegramID()) {
$telegramBotFunction = new Telegram($this->entityManager);
$orders = $entityManager->getRepository(OrderUkraine::class)->findBy(['phoneInGermany'=> $user->getPhoneNumber(), 'statusDelivery' => "У німетчині" ]);
if($orders) {
$sendMessageHTML = "Увага до Вас прямує посилочка з України\n";
foreach ($orders as $item) {
$trackNumber = $item->getTracknumberInGermany();
$status = $item->getStatusDelivery();
$city = $item->getCityInGermany();
$getFactWeight = $item->getFactWeight();
$priceToPay = $item->priceToPay();
$address = $entityManager->getRepository(Adressen::class)->findOneBy(['city'=> $item->getCityInGermany()]);
$sendMessageHTML .= "━━━━━━━━━━━━━━━━━━━━━━\n";
$sendMessageHTML .= "📦 <b>Номер посилки:</b> $trackNumber\n";
$sendMessageHTML .= "🔄 <b>Статус:</b> $status\n";
$sendMessageHTML .= "🏙️ <b>Місто отримання:</b> $city\n";
if($address) {
$sendMessageHTML .= "📍 <b>Адресса отримання:</b> $address\n";
} else {
$sendMessageHTML .= "📍 <b>Адресса отримання:</b> Не вказана\n";
}
$sendMessageHTML .= "⚖ <b>Фактична вага:</b> $getFactWeight кг\n";
$sendMessageHTML .= "💰 <b>Ціна до сплати:</b> $priceToPay грн\n";
$sendMessageHTML .= "━━━━━━━━━━━━━━━━━━━━━━\n";
}
$telegramBotFunction->sendMessageHTML($user->getTelegramID(), $sendMessageHTML);
} else {
$telegramBotFunction->sendMessage($user->getTelegramID(), "📦 У вас немає посилок.");
}
}
}
return $this->json('Empty');
}
#[Route('/testDVB', name: 'testDVB')]
public function index2(Bot $bot, EntityManagerInterface $entityManager): Response
{
$user = $this->entityManager->getRepository(User::class)->findOneBy(['phoneNumber' => 666666]);
if($user) {
$user->setPhoneNumber("666666");
$this->entityManager->flush();
return $this->json('t');
}
return $this->json('f');
}
#[Route('/testDVB2', name: 'testDVB2')]
public function index22(Bot $bot, EntityManagerInterface $entityManager): Response
{
$cityArray = $entityManager->getRepository(City::class)->findAll();
$buttons = [];
foreach ($cityArray as $city) {
$buttons[] = [
'text' => $city->getName() // Текст кнопки, отправляемый как сообщение
];
}
// Формируем клавиатуру с кнопками городов
$keyboard = [
'keyboard' => array_chunk(array_map(function ($button) {
return $button; // Добавляем каждую кнопку
}, $buttons), 3), // Разбиваем кнопки на строки по 3 в каждой
'resize_keyboard' => true,
'one_time_keyboard' => true
];
$keyboard = json_encode($keyboard);
return $this->json($keyboard);
}
#[Route('/index222', name: 'index222')]
public function index222(Bot $bot, EntityManagerInterface $entityManager): Response
{
// $userOb = $this->entityManager->getRepository(User::class)->findOneBy(['telegramID' => $userChat]);
$userOb = $entityManager->getRepository(User::class)->findOneBy(['telegramID' => "295940824"]);
$orders = $this->entityManager->getRepository(OrderUkraine::class)->findBy(['phoneInGermany' => $userOb->getPhoneNumber()]);
$telegramBotFunction = new Telegram($this->entityManager);
if($orders) {
$sendMessageHTML = "";
foreach ($orders as $item) {
$trackNumber = $item->getTracknumberInGermany();
$status = $item->getStatusDelivery();
$sendMessageHTML .= "---------------------------\n";
$sendMessageHTML .= "<b>Номер:</b> $trackNumber\n";
$sendMessageHTML .= "<b>Статус:</b> $status\n";
$sendMessageHTML .= "---------------------------\n";
}
$telegramBotFunction->sendMessageHTML("295940824", $sendMessageHTML);
} else {
$telegramBotFunction->sendMessage("295940824", "📦 У вас немає посилок.");
}
return $this->json("Empty");
}
#[Route('/telegram/bot', name: 'app_telegram_bot')]
public function index(Bot $bot, EntityManagerInterface $entityManager, UserPasswordHasherInterface $userPasswordHasher): Response
{
file_put_contents('log.txt', "Метод index вызван\n", FILE_APPEND);
$telegramBotFunction = new Telegram($entityManager);
file_put_contents('log.txt', " 111 Метод index вызван\n", FILE_APPEND);
$firstBot = $bot->getBot('first');
$updateArray = $firstBot->getWebhookUpdate();
file_put_contents('log.txt', "Метод getWebhookUpdate вызван\n", FILE_APPEND);
$webhookInfo = $firstBot->getWebhookInfo();
file_put_contents('log.txt', "Метод getWebhookInfo вызван\n", FILE_APPEND);
file_put_contents('log.txt', "Webhook Info: " . json_encode($webhookInfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n", FILE_APPEND);
file_put_contents('log.txt', "updateArray Info: " . json_encode($updateArray, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n", FILE_APPEND);
if ($updateArray->getMessage()) {
file_put_contents('log.txt', "Получено сообщение: " . json_encode($updateArray, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n", FILE_APPEND);
$textRequest = $updateArray->getMessage()->get('text');
$userChat = $updateArray->getMessage()->getChat()->get('id');
file_put_contents('log.txt', "Получено сообщение: '$textRequest' от пользователя: $userChat\n", FILE_APPEND);
$userOb = $entityManager->getRepository(User::class)->findOneBy(['telegramID' => $userChat]);
$registrationStep = $entityManager->getRepository(RegistrationStep::class)->findOneBy(['chatId' => $userChat]);
// Лог о состоянии пользователя и шага регистрации
file_put_contents('log.txt', "Пользователь найден: " . ($userOb ? 'Да' : 'Нет') . "\n", FILE_APPEND);
file_put_contents('log.txt', "Текущий шаг регистрации: " . ($registrationStep ? $registrationStep->getStep() : 'Нет') . "\n", FILE_APPEND);
if ($registrationStep) {
file_put_contents('log.txt', "Продолжение незавершённой регистрации.\n", FILE_APPEND);
$registrationHandler = new RegistrationHandlerTelegram($entityManager, $telegramBotFunction, $userPasswordHasher);
$result = $registrationHandler->handleStep($registrationStep, $textRequest, $userChat);
if ($result === 'complete') {
file_put_contents('log.txt', "Регистрация завершена. Удаление шага регистрации.\n", FILE_APPEND);
$entityManager->remove($registrationStep);
$entityManager->flush();
}
return $this->json('Empty');
}
if($userOb) {
switch ($textRequest) {
case '📞 Контакти':
file_put_contents('log.txt', "Команда: '📞 Контакти'", FILE_APPEND);
$contactMessage = "📞 <b>Контакти:</b>\n\n";
$contactMessage .= "<b>Телефони:</b>\n";
$contactMessage .= "<a href=\"tel:+491639454555\">+49 163 945 4555</a>\n";
$contactMessage .= "<a href=\"tel:+380955137377\">+380 95 513 7377</a>\n";
$contactMessage .= "<a href=\"tel:+4915259177701\">+49 152 591 777 01</a>\n\n";
file_put_contents('log.txt', "Отправка контактной информации.\n", FILE_APPEND);
$telegramBotFunction->sendMessageHTML($userChat, $contactMessage);
return $this->json('Empty');
case '📜 Політика конфіденційності':
file_put_contents('log.txt', "Команда: '📜 Політика конфіденційності'", FILE_APPEND);
$telegramBotFunction->sendMessage($userChat, "📜 Політика конфіденційності:\nВаші дані зберігаються відповідно до GDPR. Детальніше на нашому сайті.");
return $this->json('Empty');
case '📦 Показати мої посилки':
file_put_contents('log.txt', "Команда: '📦 Показати мої посилки'", FILE_APPEND);
return $this->handleShowParcels($userChat, $telegramBotFunction);
case '📍 Адреса отримування':
file_put_contents('log.txt', "Команда: '📍 Адреса отримування", FILE_APPEND);
return $this->handleDeliveryAddress($userChat, $telegramBotFunction);
default:
file_put_contents('log.txt', "Неизвестная команда: $textRequest\n", FILE_APPEND);
$telegramBotFunction->sendMessagewithKeyboard($userChat, "Виберіть команду із меню.", $this->getMainMenu());
return $this->json('Empty');
}
} else {
file_put_contents('log.txt', "Начало новой регистрации.\n", FILE_APPEND);
return $this->handleStart($userChat, $userOb, $registrationStep, $entityManager, $telegramBotFunction);
}
// Обработка команд
}
return $this->json('Empty');
}
// Обработчик команды /start
private function handleStart($userChat, $userOb, $registrationStep, $entityManager, $telegramBotFunction): Response
{
if ($registrationStep) {
// Продолжить с текущего шага
$telegramBotFunction->sendMessage($userChat, "Реєстрація не завершена. Введіть ваш email для продовження:");
return $this->json('Empty');
}
if (!$userOb) {
$registrationStep = new RegistrationStep();
$registrationStep->setChatId($userChat);
$registrationStep->setStep('check_email');
$entityManager->persist($registrationStep);
$entityManager->flush();
$telegramBotFunction->sendMessage($userChat, "Реєстрація почалась. Введіть свій email:");
return $this->json('Empty');
}
$telegramBotFunction->sendMessagewithKeyboard($userChat, "Ласкаво просимо! Оберіть дію:", $this->getMainMenu());
return $this->json('Empty');
}
private function handleShowParcels($userChat, $telegramBotFunction): Response
{
$userOb = $this->entityManager->getRepository(User::class)->findOneBy(['telegramID' => $userChat]);
$orders = $this->entityManager->getRepository(OrderUkraine::class)->findBy(['phoneInGermany' => $userOb->getPhoneNumber()]);
if($orders) {
$sendMessageHTML = "";
foreach ($orders as $item) {
$trackNumber = $item->getTracknumberInGermany();
$status = $item->getStatusDelivery();
$city = $item->getCityInGermany();
$getFactWeight = $item->getFactWeight();
$priceToPay = $item->priceToPay();
/*$address = $this->entityManager->getRepository(Adressen::class)->findOneBy(['city'=> $item->getCityInGermany()]);*/
$sendMessageHTML .= "━━━━━━━━━━━━━━━━━━━━━━\n";
$sendMessageHTML .= "📦 <b>Номер посилки:</b> $trackNumber\n";
$sendMessageHTML .= "🔄 <b>Статус:</b> $status\n";
$sendMessageHTML .= "🏙️ <b>Місто отримання:</b> $city\n";
/* if($address) {
$sendMessageHTML .= "📍 <b>Адресса отримання:</b> $address\n";
} else {
$sendMessageHTML .= "📍 <b>Адресса отримання:</b> Не вказана\n";
}*/
$sendMessageHTML .= "⚖ <b>Фактична вага:</b> $getFactWeight кг\n";
$sendMessageHTML .= "💰 <b>Ціна до сплати:</b> $priceToPay грн\n";
$sendMessageHTML .= "━━━━━━━━━━━━━━━━━━━━━━\n";
}
$telegramBotFunction->sendMessageHTML($userChat, $sendMessageHTML);
return $this->json('Empty');
} else {
$telegramBotFunction->sendMessage($userChat, "📦 У вас немає посилок.");
return $this->json('Empty');
}
}
private function handleDeliveryAddress($userChat, $telegramBotFunction): Response
{
// Получаем все адреса из базы данных
$adresses = $this->entityManager->getRepository(Adressen::class)->findAll();
if ($adresses) {
$sendMessageHTML = "<b>📍 Доступні адреси:</b>";
// Формируем HTML для каждого адреса
foreach ($adresses as $address) {
$city = $address->getCity();
$addressText = $address->getAddressen();
$workDay = $address->getWorkDay();
$advanced = $address->getAdvanced();
$time = $address->getTime();
$sendMessageHTML .= "---------------------------\n";
$sendMessageHTML .= "<b>Місто:</b> $city\n";
$sendMessageHTML .= "<b>Адреса:</b> $addressText\n";
$sendMessageHTML .= "<b>Робочі дні:</b> $workDay\n";
$sendMessageHTML .= "<b>Додаткова інформація:</b> $advanced\n";
$sendMessageHTML .= "<b>Час роботи:</b> $time\n";
$sendMessageHTML .= "---------------------------\n\n";
}
// Отправляем сообщение пользователю
$telegramBotFunction->sendMessageHTML($userChat, $sendMessageHTML);
} else {
// Если адресов нет, отправляем сообщение об этом
$telegramBotFunction->sendMessage($userChat, "📍 Упс немає даних");
}
return $this->json('Empty');
}
// Генерация меню
public function getMainMenu(): array
{
$keyboard = [
[
['text' => '📦 Показати мої посилки', 'callback_data' => 'show_parcels'],
['text' => '📍 Адреса отримування', 'callback_data' => 'delivery_address']
],
[
['text' => '📞 Контакти', 'callback_data' => 'contacts'],
['text' => '📜 Політика конфіденційності', 'callback_data' => 'privacy_policy']
]
];
$replyMarkup = [
'keyboard' => $keyboard,
'resize_keyboard' => true,
'one_time_keyboard' => false
];
return $replyMarkup;
}
// Функция для проверки заполненности всех обязательных полей
private function allRequiredFieldsFilled(array $data, array $excludeFields = []): bool
{
$requiredFields = ['firstName', 'lastName', 'city', 'postalCode', 'address', 'password'];
foreach ($requiredFields as $field) {
if (!in_array($field, $excludeFields) && empty($data[$field])) {
return false;
}
}
return true;
}
// Проверка, существует ли пользователь в базе данных по email
private function checkUserExistsInDatabase(string $email, EntityManagerInterface $entityManager): bool
{
return (bool) $entityManager->getRepository(User::class)->findOneBy(['email' => $email]);
}
// Создание нового пользователя в базе данных
private function createNewUserInDatabase(array $data, $userChat,UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $entityManager, $telegramBotFunction)
{
$user = new User();
$user->setFirstName($data['firstName']);
$user->setLastName($data['lastName']);
$user->setEmail($data['email']);
$user->setPhoneNumber($data['phoneNumber']);
$user->setCity($data['city']);
$user->setPostalCode($data['postalCode']);
$user->setAddress($data['address']);
$user->setPassword(
$userPasswordHasher->hashPassword(
$user,
$data['password']
)
);
$user->setRoles([
"ROLE_RECEIVER"
]);
$user->setPassword(password_hash($data['password'], PASSWORD_BCRYPT));
$user->setTelegramID($userChat);
$entityManager->persist($user);
$entityManager->flush();
$telegramBotFunction->sendMessage($userChat, "Реєстрація пройшла успішно!");
}
// Обновление данных существующего пользователя в базе данных
private function updateUserDataInDatabase(array $data, $userChat, EntityManagerInterface $entityManager, $telegramBotFunction)
{
$user = $entityManager->getRepository(User::class)->findOneBy(['email' => $data['email']]);
if ($user) {
$user->setFirstName($data['firstName']);
$user->setLastName($data['lastName']);
$user->setPhoneNumber($data['phoneNumber']);
$user->setCity($data['city']);
$user->setPostalCode($data['postalCode']);
$user->setAddress($data['address']);
$user->setTelegramID($userChat);
$entityManager->flush();
$telegramBotFunction->sendMessage($userChat, "Ваші дані оновлені!");
} else {
$telegramBotFunction->sendMessage($userChat, "Помилка при оновленні даних. Спробуйте ще раз.");
}
}
}