<?php

namespace App\Handlers;

use App\Services\SettingsService;
use Exception;
use GuzzleHttp\Exception\ClientException;
use Openguru\OpenCartFramework\Http\Request;
use Openguru\OpenCartFramework\ImageTool\ImageFactory;
use Openguru\OpenCartFramework\Telegram\TelegramService;
use Symfony\Component\HttpFoundation\JsonResponse;

class SettingsHandler
{
    private SettingsService $settings;
    private ImageFactory $image;
    private TelegramService $telegramService;

    public function __construct(
        SettingsService $settings,
        ImageFactory $image,
        TelegramService $telegramService
    ) {
        $this->settings = $settings;
        $this->image = $image;
        $this->telegramService = $telegramService;
    }

    public function index(): JsonResponse
    {
        $appConfig = $this->settings->config()->getApp();

        $appIcon = $appConfig->getAppIcon();
        $hash = $this->settings->getHash();

        if ($appIcon) {
            $appIcon = $this->image->make($appIcon)->resize(null, 64)->url('png') . '?_v=' . $hash;
        }

        return new JsonResponse([
            'app_name' => $appConfig->getAppName(),
            'app_debug' => $appConfig->isAppDebug(),
            'app_icon' => $appIcon,
            'theme_light' => $appConfig->getThemeLight(),
            'theme_dark' => $appConfig->getThemeDark(),
            'ya_metrika_enabled' => $this->settings->config()->getMetrics()->isYandexMetrikaEnabled(),
            'app_enabled' => $appConfig->isAppEnabled(),
            'product_interaction_mode' => $this->settings->config()->getStore()->getProductInteractionMode(),
            'manager_username' => $this->settings->config()->getStore()->getManagerUsername(),
            'feature_coupons' => $this->settings->config()->getStore()->isFeatureCoupons(),
            'feature_vouchers' => $this->settings->config()->getStore()->isFeatureVouchers(),
            'show_category_products_button' => $this->settings->config()->getStore()->isShowCategoryProductsButton(),
            'currency_code' => $this->settings->config()->getStore()->getOcDefaultCurrency(),
            'texts' => $this->settings->config()->getTexts()->toArray(),
            'mainpage_blocks' => $this->settings->get('mainpage_blocks', []),
            'privacy_policy_link' => $this->settings->get('app.privacy_policy_link'),
            'image_aspect_ratio' => $this->settings->get('app.image_aspect_ratio', '1:1'),
            'haptic_enabled' => $appConfig->isHapticEnabled(),
        ]);
    }

    public function testTgMessage(Request $request): JsonResponse
    {
        $template = $request->json('template', 'Нет шаблона');
        $token = $request->json('token');
        $chatId = $request->json('chat_id');

        if (! $token) {
            return new JsonResponse([
                'message' => 'Не задан Telegram BotToken',
            ]);
        }

        if (! $chatId) {
            return new JsonResponse([
                'message' => 'Не задан ChatID.',
            ]);
        }

        $variables = [
            '{store_name}' => $this->settings->config()->getApp()->getAppName(),
            '{order_id}' => 777,
            '{customer}' => 'Иван Васильевич',
            '{email}' => 'telegram@opencart.com',
            '{phone}' => '+79999999999',
            '{comment}' => 'Это тестовый заказ',
            '{address}' => 'г. Москва',
            '{total}' => 100000,
            '{ip}' => '127.0.0.1',
            '{created_at}' => date('Y-m-d H:i:s'),
        ];

        $message = $this->telegramService->prepareMessage($template, $variables);

        try {
            $this->telegramService
                ->setBotToken($token)
                ->sendMessage($chatId, $message);

            return new JsonResponse([
                'message' => 'Сообщение отправлено. Проверьте Telegram.',
            ]);
        } catch (ClientException $exception) {
            $json = json_decode($exception->getResponse()->getBody(), true);

            return new JsonResponse([
                'message' => $json['description'],
            ]);
        } catch (Exception $e) {
            return new JsonResponse([
                'message' => $e->getMessage(),
            ]);
        }
    }
}
