<?php

namespace App\Handlers;

use App\Services\SettingsService;
use Exception;
use GuzzleHttp\Exception\ClientException;
use Openguru\OpenCartFramework\Http\JsonResponse;
use Openguru\OpenCartFramework\Http\Request;
use Openguru\OpenCartFramework\ImageTool\ImageToolInterface;
use Openguru\OpenCartFramework\Router\Router;
use Openguru\OpenCartFramework\Telegram\TelegramService;

class SettingsHandler
{
    private SettingsService $settings;
    private ImageToolInterface $imageTool;
    private Router $router;
    private TelegramService $telegramService;

    public function __construct(
        SettingsService $settings,
        ImageToolInterface $imageTool,
        Router $router,
        TelegramService $telegramService
    ) {
        $this->settings = $settings;
        $this->imageTool = $imageTool;
        $this->router = $router;
        $this->telegramService = $telegramService;
    }

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

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

        if ($appIcon) {
            $icons['icon192'] = $this->imageTool->resize($appIcon, 192, 192, 'no_image.png', 'png') . '?_v=' . $hash;
            $icons['icon180'] = $this->imageTool->resize($appIcon, 180, 180, 'no_image.png', 'png') . '?_v=' . $hash;
            $icons['icon152'] = $this->imageTool->resize($appIcon, 152, 152, 'no_image.png', 'png') . '?_v=' . $hash;
            $icons['icon120'] = $this->imageTool->resize($appIcon, 120, 120, 'no_image.png', 'png') . '?_v=' . $hash;
            $appIcon = $this->imageTool->resize($appIcon, null, 64, 'no_image.png', 'png') . '?_v=' . $hash;
        }

        return new JsonResponse([
            'app_name' => $appConfig->getAppName(),
            'app_debug' => $appConfig->isAppDebug(),
            'app_icon' => $appIcon,
            'app_icon192' => $icons['icon192'] ?? '',
            'app_icon180' => $icons['icon180'] ?? '',
            'app_icon152' => $icons['icon152'] ?? '',
            'app_icon120' => $icons['icon120'] ?? '',
            'manifest_url' => $this->router->url('manifest', ['_v' => $hash]),
            'theme_light' => $appConfig->getThemeLight(),
            'theme_dark' => $appConfig->getThemeDark(),
            'ya_metrika_enabled' => $this->settings->config()->getMetrics()->isYandexMetrikaEnabled(),
            'app_enabled' => $appConfig->isAppEnabled(),
            'store_enabled' => $this->settings->config()->getStore()->isEnableStore(),
            'feature_coupons' => $this->settings->config()->getStore()->isFeatureCoupons(),
            'feature_vouchers' => $this->settings->config()->getStore()->isFeatureVouchers(),
            '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'),
        ]);
    }

    public function manifest(): JsonResponse
    {
        $manifest = [
            'name' => $this->settings->config()->getApp()->getAppName(),
            'short_name' => $this->settings->config()->getApp()->getAppName(),
            'start_url' => '/image/catalog/tgshopspa/',
            'display' => 'standalone',
            'background_color' => '#ffffff',
            'theme_color' => '#000000',
            'orientation' => 'portrait',
        ];

        $appIcon = $this->settings->config()->getApp()->getAppIcon();
        if ($appIcon) {
            $icon192 = $this->imageTool->resize($appIcon, 192, 192, 'no_image.png', 'png');
            $icon512 = $this->imageTool->resize($appIcon, 512, 512, 'no_image.png', 'png');
            $manifest['icons'] = [
                [
                    'src' => $icon192,
                    'sizes' => '192x192',
                    'type' => 'image/png',
                ],
                [
                    'src' => $icon512,
                    'sizes' => '512x512',
                    'type' => 'image/png',
                ]
            ];
        }

        return new JsonResponse($manifest);
    }

    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(),
            ]);
        }
    }
}
