<?php

namespace idoit\Module\Pro\SettingPage\Center\DownloadCenter;

use idoit\Component\Helper\Purify;
use idoit\Module\Pro\SettingPage\Center\Base;
use isys_auth;
use isys_component_list;
use isys_component_template_navbar;
use isys_helper_textformat;
use isys_module_pro as ModulePro;
use isys_module_system as ModuleSystem;
use isys_tenantsettings;

class DownloadCenter extends Base
{
    public const GROUP_ADDON_PAID = 'addon_paid';
    public const GROUP_ADDON_FREE = 'addon_free';
    public const GROUP_IDOIT      = 'idoit';

    /**
     * @return void
     * @throws \isys_exception_auth
     * @throws \isys_exception_database
     */
    protected function render($navMode, array $response): void
    {
        global $g_license_token;

        isys_component_template_navbar::getInstance()
            ->hide_all_buttons();

        $this->tpl->assign('content_title', $this->lang->get('LC__DOWNLOAD_CENTER'))
            ->assign('cssPath', ModulePro::getPath() . 'assets/css/download-center.css')
            ->smarty_tom_add_rule('tom.content.navbar.cRecStatus.p_bInvisible=1')
            ->include_template('contentbottomcontent', ModulePro::getPath() . 'templates/SettingPage/Center/Download/download-center.tpl');
        $data = $response;
        $rowHeaders = [
            'action'       => 'LC__DOWNLOAD_CENTER__ACTION',
            'name'         => 'LC__DOWNLOAD_CENTER__PRODUCT',
            'type'         => 'LC__DOWNLOAD_CENTER__TYPE',
            'version'      => 'LC__DOWNLOAD_CENTER__VERSION',
            'vendor'       => 'LC__DOWNLOAD_CENTER__EDITOR',
            'releaseDate'  => 'LC__DOWNLOAD_CENTER__RELEASE_DATE',
            'releaseNotes' => 'LC__DOWNLOAD_CENTER__RELEASE_NOTES',
        ];

        $listData = $data['data'];
        foreach ($listData as $index => $item) {
            // Set type as group because it is a keyword in sql and can not be used for ordering
            $listData[$index]['type'] = $item['group'];
        }

        $downloadList = new isys_component_list($listData);
        $downloadList->config($rowHeaders, function ($a) {
            return "javascript:downloadPackage('" . $a['id'] . "')";
        })
            ->disable_dragndrop()
            ->disableCheckboxes()
            ->set_row_modifier($this, 'modifyRow')
            ->setOptions([
                'columnSizes' => ['6%', '16%', '14%', '17%', '15%', '17%', '14%']
            ]);

        $properties = $downloadList->get_table_config()
            ->getProperties();
        $properties[0]->setIndexed(false);
        $downloadList->set_table_config($downloadList->get_table_config()
            ->setProperties($properties)
            ->setRowClickable(false));
        $downloadList->createTempTable();

        $this->tpl->assign('downloadList', $downloadList->getTempTableHtml());
    }

    /**
     * @param array $row
     *
     * @return void
     * @throws \Exception
     */
    public function modifyRow(array &$row)
    {
        global $g_dirs;

        if ($row['downloadLink']) {
            $link = $row['downloadLink'];
            $row['action'] = '<div class="display-flex align-items-center">' . '<a class="btn" style="outline:0;" data-tooltip="1" href="' . $link .
                '" download id="downloadcenter_' . $row['id'] . '" title="' . $this->lang->get('LC__DOWNLOAD_CENTER__DOWNLOAD') . '">' . '<img src="' . $g_dirs['images'] .
                'axialis/basic/symbol-download.svg" />' . '</a>' . '</div>';
        }

        if ($row['releaseNotes']) {
            $row['releaseNotes'] = Purify::purifyValueByRegex(isys_helper_textformat::remove_scripts($row['releaseNotes']), '/<pre.*>|<\/pre>/');
            $row['releaseNotes'] = '<a data-tooltip="1" href="javascript:showReleasenotes(btoa(encodeURIComponent(\'' . htmlentities($row['releaseNotes']) .
                '\')))" class="align-items-end" style="display: flex" title="' . $this->lang->get('LC__DOWNLOAD_CENTER__RELEASE_NOTES') . '">' . '<img src="' .
                $g_dirs['images'] . 'axialis/web-email/external-link.svg" class="mr5" /> <span>' . $this->lang->get('LC__DOWNLOAD_CENTER__RELEASE_NOTE') . '</span></a>';
        }

        $row['releaseDate'] = $row['releaseDate'] ? (new \DateTime($row['releaseDate']))->format('Y-m-d') : '';
        $row['type'] = $this->getType($row['group'] ?? '');

        $url = str_starts_with($row['vendorWebsite'], 'http') ? $row['vendorWebsite'] : 'http://' . $row['vendorWebsite'];
        $row['vendor'] = '<a data-tooltip="1" href="' . $url . '" target="_blank" class="align-items-end" style="display: flex" title="' . $row['vendor'] . '">' .
            '<img src="' . $g_dirs['images'] . 'axialis/web-email/external-link.svg" class="mr5" />' . $row['vendor'] . '</a>';
    }

    /**
     * @param string $type
     *
     * @return string
     */
    private function getType(string $type): string
    {
        if ($type === self::GROUP_ADDON_PAID) {
            return $this->lang->get('LC__DOWNLOAD_CENTER__GROUP_ADDON_PAID');
        }

        if ($type === self::GROUP_ADDON_FREE) {
            return $this->lang->get('LC__DOWNLOAD_CENTER__GROUP_ADDON_FREE');
        }

        if ($type === self::GROUP_IDOIT) {
            return $this->lang->get('LC__DOWNLOAD_CENTER__GROUP_IDOIT');
        }

        return isys_tenantsettings::get('gui.empty_value', '-');
    }

    /**
     * @return void
     * @throws \isys_exception_auth
     */
    protected function checkAuth(): void
    {
        ModuleSystem::getAuth()
            ->check(isys_auth::EXECUTE, 'downloader');
    }

    /**
     * @return string
     */
    protected function getUrl(): string
    {
        return '/downloads';
    }
}
