<?php
/**
 * 2026 Paysera
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2026 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of Paysera
 */

declare(strict_types=1);

namespace Paysera\PrestashopPayments\Helper;

use Paysera\PrestashopPayments\Dto\TabDto;
use Symfony\Contracts\Translation\TranslatorInterface;

if (!defined('_PS_VERSION_')) {
    exit;
}

class TabHelper
{
    private const PARENT_TAB_CLASS_NAME = 'AdminPayseraPaymentsTab';

    public function __construct(
        private TranslatorInterface $translator
    ) {
    }

    public function installTabs(): void
    {
        foreach ($this->getTabsToInstall() as $tabDto) {
            $existingTabId = $this->getTabIdByClassName($tabDto->className);

            if ($existingTabId !== 0) {
                $this->updateExistingTab($existingTabId, $tabDto);
            } else {
                $this->createNewTab($tabDto);
            }
        }
    }

    public function uninstallTabs(): void
    {
        foreach ($this->getTabsToInstall() as $tabDto) {
            $tabId = $this->getTabIdByClassName($tabDto->className);
            if ($tabId === 0) {
                continue;
            }

            $tab = new \Tab($tabId);
            $tab->delete();
        }
    }

    public function removeTabByClassName(string $className): void
    {
        $tabId = $this->getTabIdByClassName($className);
        if ($tabId === 0) {
            return;
        }

        $tab = new \Tab($tabId);
        $tab->delete();
    }

    public function refreshTabs(): void
    {
        foreach ($this->getTabsToInstall() as $tabDto) {
            $tabId = $this->getTabIdByClassName($tabDto->className);
            if ($tabId !== 0) {
                $this->updateExistingTab($tabId, $tabDto);
            }
        }
    }

    private function mapToEntity(TabDto $tabDto): ?\Tab
    {
        $tab = new \Tab();
        $tab->name = [];
        foreach (\Language::getLanguages(false) as $language) {
            $tab->name[$language['id_lang']] = $this->getTabName($tabDto, $language['locale']);
        }
        $tab->module = $tabDto->module;
        $tab->class_name = $tabDto->className;

        $parentId = $this->getTabIdByClassName($tabDto->parentId);
        if ($parentId === 0 && $tabDto->parentId !== 'CONFIGURE') {
            return null;
        }

        $tab->id_parent = $parentId;
        $tab->active = $tabDto->active;

        if ($tabDto->icon !== null) {
            $tab->icon = $tabDto->icon;
        }

        return $tab;
    }

    private function updateExistingTab(int $tabId, TabDto $tabDto): void
    {
        $tab = new \Tab($tabId);
        foreach (\Language::getLanguages(false) as $language) {
            $tab->name[$language['id_lang']] = $this->getTabName($tabDto, $language['locale']);
        }
        $tab->module = $tabDto->module;
        $tab->active = $tabDto->active;

        $parentId = $this->getTabIdByClassName($tabDto->parentId);
        if ($parentId !== 0 || $tabDto->parentId === 'CONFIGURE') {
            $tab->id_parent = $parentId;
        }

        if ($tabDto->icon !== null) {
            $tab->icon = $tabDto->icon;
        }

        $tab->update();
    }

    private function createNewTab(TabDto $tabDto): void
    {
        $tab = $this->mapToEntity($tabDto);
        if ($tab === null) {
            return;
        }

        $result = $tab->add();
        if (!$result) {
            throw new \Exception(sprintf('Failed to install tab: %s', $tabDto->className));
        }
    }

    private function getTabIdByClassName(string $className): int
    {
        return (int) \Tab::getInstanceFromClassName($className)->id;
    }

    private function getTabName(TabDto $tabDto, string $locale): string
    {
        return $this->translator->trans($tabDto->name, [], \PayseraPayments::TRANSLATION_DOMAIN, $locale);
    }

    /**
     * @return TabDto[]
     */
    private function getTabsToInstall(): array
    {
        return [
            new TabDto(
                name: 'Paysera Checkout',
                className: self::PARENT_TAB_CLASS_NAME,
                parentId: 'CONFIGURE',
                module: 'payserapayments',
                active: true,
                icon: 'payments',
            ),
            new TabDto(
                name: 'Overview',
                className: 'OverviewPayseraPaymentsTab',
                parentId: self::PARENT_TAB_CLASS_NAME,
                module: 'payserapayments',
                active: true,
            ),
            new TabDto(
                name: 'Authorisation',
                className: 'AuthorizationPayseraPaymentsTab',
                parentId: self::PARENT_TAB_CLASS_NAME,
                module: 'payserapayments',
                active: true,
            ),
            new TabDto(
                name: 'Payment Settings',
                className: 'PaymentSettingsPayseraPaymentsTab',
                parentId: self::PARENT_TAB_CLASS_NAME,
                module: 'payserapayments',
                active: true,
            ),
            new TabDto(
                name: 'Payments List',
                className: 'PaymentsListPayseraPaymentsTab',
                parentId: self::PARENT_TAB_CLASS_NAME,
                module: 'payserapayments',
                active: true,
            ),
            new TabDto(
                name: 'Diagnostics',
                className: 'DiagnosticPayseraPaymentsTab',
                parentId: self::PARENT_TAB_CLASS_NAME,
                module: 'payserapayments',
                active: true,
            ),
            new TabDto(
                name: 'Help',
                className: 'HelpPayseraPaymentsTab',
                parentId: self::PARENT_TAB_CLASS_NAME,
                module: 'payserapayments',
                active: true,
            ),
            new TabDto(
                name: 'Paysera AJAX',
                className: 'AdminPayseraPaymentsAjax',
                parentId: '-1',
                module: 'payserapayments',
                active: true,
            ),
        ];
    }
}
