<?php
/*
 *  Copyright (c) 2025 Borlabs GmbH. All rights reserved.
 *  This file may not be redistributed in whole or significant part.
 *  Content of this file is protected by international copyright laws.
 *
 *  ----------------- Borlabs Cookie IS NOT FREE SOFTWARE -----------------
 *
 *  @copyright Borlabs GmbH, https://borlabs.io
 */

declare(strict_types=1);

namespace Borlabs\Cookie\Controller\Admin\Dashboard;

use Borlabs\Cookie\Adapter\WpFunction;
use Borlabs\Cookie\Controller\Admin\ControllerInterface;
use Borlabs\Cookie\Controller\Admin\ExtendedRouteValidationInterface;
use Borlabs\Cookie\Dto\System\RequestDto;
use Borlabs\Cookie\Enum\System\AutomaticUpdateEnum;
use Borlabs\Cookie\Exception\TranslatedException;
use Borlabs\Cookie\Localization\Dashboard\DashboardLocalizationStrings;
use Borlabs\Cookie\Localization\GlobalLocalizationStrings;
use Borlabs\Cookie\Support\Formatter;
use Borlabs\Cookie\System\Config\PluginConfig;
use Borlabs\Cookie\System\Dashboard\ChartDataService;
use Borlabs\Cookie\System\Dashboard\NewsService;
use Borlabs\Cookie\System\Language\Language;
use Borlabs\Cookie\System\License\License;
use Borlabs\Cookie\System\Message\MessageManager;
use Borlabs\Cookie\System\Option\Option;
use Borlabs\Cookie\System\SystemCheck\SystemCheck;
use Borlabs\Cookie\System\Template\Template;
use Borlabs\Cookie\System\Updater\Updater;

/**
 * Class DashboardController.
 */
final class DashboardController implements ControllerInterface, ExtendedRouteValidationInterface
{
    public const CONTROLLER_ID = 'borlabs-cookie';

    private ChartDataService $chartDataService;

    private GlobalLocalizationStrings $globalLocalizationStrings;

    private Language $language;

    private License $license;

    private MessageManager $messageManager;

    private NewsService $newsService;

    private Option $option;

    private PluginConfig $pluginConfig;

    private SystemCheck $systemCheck;

    private Template $template;

    private Updater $updater;

    private WpFunction $wpFunction;

    public function __construct(
        ChartDataService $chartDataService,
        GlobalLocalizationStrings $globalLocalizationStrings,
        Language $language,
        License $license,
        MessageManager $messageManager,
        NewsService $newsService,
        Option $option,
        PluginConfig $pluginConfig,
        SystemCheck $systemCheck,
        Template $template,
        Updater $updater,
        WpFunction $wpFunction
    ) {
        $this->chartDataService = $chartDataService;
        $this->globalLocalizationStrings = $globalLocalizationStrings;
        $this->language = $language;
        $this->license = $license;
        $this->messageManager = $messageManager;
        $this->newsService = $newsService;
        $this->option = $option;
        $this->pluginConfig = $pluginConfig;
        $this->systemCheck = $systemCheck;
        $this->template = $template;
        $this->updater = $updater;
        $this->wpFunction = $wpFunction;
    }

    public function route(RequestDto $request): ?string
    {
        $action = $request->postData['action'] ?? $request->getData['action'] ?? '';

        try {
            if ($action === 'save') {
                return $this->save($request->postData);
            }
        } catch (TranslatedException $e) {
            $this->messageManager->error($e->getMessage());
        }

        return $this->viewOverview($request->postData);
    }

    public function save(array $postData): string
    {
        $pluginConfig = $this->pluginConfig->get();
        $pluginConfig->automaticUpdate = AutomaticUpdateEnum::hasValue($postData['automaticUpdate'] ?? '')
            ? AutomaticUpdateEnum::fromValue($postData['automaticUpdate']) : AutomaticUpdateEnum::AUTO_UPDATE_ALL();
        $pluginConfig->enableDebugConsole = (bool) ($postData['enableDebugConsole'] ?? false);
        $pluginConfig->enableDebugLogging = (bool) ($postData['enableDebugLogging'] ?? false);
        $this->pluginConfig->save($pluginConfig);
        $this->updater->handleAutomaticUpdateStatus();

        $this->messageManager->success($this->globalLocalizationStrings::get()['alert']['savedSuccessfully']);

        return $this->viewOverview($postData);
    }

    public function validate(RequestDto $request, string $nonce, bool $isValid): bool
    {
        if (isset($request->postData['action'])
            && in_array($request->postData['action'], ['chart-data', ], true)
            && $this->wpFunction->wpVerifyNonce(self::CONTROLLER_ID . '-' . $request->postData['action'], $nonce)
        ) {
            $isValid = true;
        }

        return $isValid;
    }

    public function viewOverview(array $postData): string
    {
        $templateData = [];
        $templateData['controllerId'] = self::CONTROLLER_ID;
        $templateData['localized'] = DashboardLocalizationStrings::get();
        $templateData['localized']['global'] = GlobalLocalizationStrings::get();
        $templateData['enum']['automaticUpdateOptions'] = AutomaticUpdateEnum::getLocalizedKeyValueList();
        $templateData['enum']['automaticUpdateOptions']->sortListByPropertiesNaturally(['value']);
        $templateData['language'] = $this->language->getSelectedLanguageCode();
        $templateData['data']['pluginConfig'] = $this->pluginConfig->get();
        $templateData['data']['news'] = $this->newsService->getNews();
        $timeRange = '30days';

        if (isset($postData['timeRange']) && $postData['timeRange'] === 'today') {
            $timeRange = 'today';
        } elseif (isset($postData['timeRange']) && $postData['timeRange'] === '7days') {
            $timeRange = '7days';
        } elseif (isset($postData['timeRange']) && $postData['timeRange'] === 'services30days') {
            $timeRange = 'services30days';
        }

        $chartData = $this->chartDataService->getChartData($timeRange);

        $templateData['data']['timeRange'] = $timeRange;
        $templateData['data']['jsonChartData'] = isset($chartData['datasets'][0]['data'][0]) ? true : false;
        $templateData['scriptTagChartData'] = '<script>var barChartData = ' . json_encode($chartData) . '; </script>';
        $templateData['localized']['headline']['cookieVersion'] = Formatter::interpolate(
            $templateData['localized']['headline']['cookieVersion'],
            [
                'cookieVersion' => $this->option->getGlobal('CookieVersion', 1)->value,
            ],
        );

        // Contains parsed template of system status section
        $templateData['template']['systemCheck'] = $this->systemCheck->systemCheckView();

        return $this->template->getEngine()->render(
            'dashboard/dashboard.html.twig',
            $templateData,
        );
    }
}
