<?php

namespace CleantalkSP\SpbctWP\Views;

use CleantalkSP\SpbctWP\AdminBannersModule\AdminBanners\AdminBannerTrialAndRenewFullpage;
use CleantalkSP\SpbctWP\AdminBannersModule\AdminBannersHandler;
use CleantalkSP\SpbctWP\LinkConstructor;
use CleantalkSP\SpbctWP\VulnerabilityAlarm\VulnerabilityAlarmView;
use CleantalkSP\Variables\Server;

class Settings
{
    public static function page()
    {
        global $spbc;

        if (is_network_admin()) {
            $link = get_admin_url(get_main_site_id(), 'options-general.php?page=spbc');
            $msg = sprintf(
                '<h2>' . __('Please, enter the %splugin settings%s in main site dashboard.', 'security-malware-firewall') . '</h2>',
                '<a href="' . esc_url($link) . '">',
                '</a>'
            );

            $spbct_page_data = [
                'isNetworkAdminDashboard' => true,
                'networkAdminDashboardMsg' => wp_kses(
                    $msg,
                    array(
                        'h2' => array(),
                        'a'  => array('href' => array()),
                    )
                ),
            ];
            $spbct_tabs_data = [];
        } else {
            self::checkPhpVersion();
            self::checkMemoryLimit();

            $spbct_page_data = [
                // left corner section
                'brandname' => $spbc->data["wl_brandname"],
                'adminsOnlineCount' => self::getAdminsOnline(),
                'nextScanLaunchTime' => spbc_get_next_scan_launch_time(),

                // right corner section
                'supportLink' => self::getSupportLink(),
                'textSupportLink' => $spbc->data["wl_mode_enabled"] ? $spbc->data["wl_support_url"] : 'wordpress.org',
                'homepage' => $spbc->data["wl_url"],
                //todo We should not use the brand name to tell this is registered trademark. We are not sure.
                'trademark' => $spbc->data["wl_brandname"] . __(' is a registered trademark. All rights reserved.', 'security-malware-firewall'),
                'feedback' => self::getFeedbackRequest(),
                'premium' => self::getPremiumLink(),
                // delete link on wl mode
                'malwareCleaningLink' => empty($spbc->data['wl_mode_enabled'])
                    ? LinkConstructor::buildSimpleLink(
                        'https://cleantalk.org/',
                        'wordpress-malware-removal'
                    )
                    : '',
                // buttons
                'goToCleanTalkLink' => esc_html(self::goToCleantalkLink()),
                'goToCleanTalkText' => __('Security Dashboard', 'security-malware-firewall'),
                'support2Link' => esc_html(self::support2Link()),
                'support2Text' => __('Support', 'security-malware-firewall'),
                'sync' => spbc_api_key__is_correct() ? __('Synchronize with Cloud', 'security-malware-firewall') : '',
                'syncProgress' => __('Synchronizing with Cloud', 'security-malware-firewall'),
                'syncUrl' => SPBC_PATH . "/images/preloader2.gif",
                'syncUrlProgress' => SPBC_PATH . "/images/yes.png",

                // errors
                'spbcErrors' => spbc_settings__error__output(),
                'adminEmail' => spbc_get_admin_email(),
                'accountNameOb' => $spbc->data["account_name_ob"],

                // settings
                'backendLogsEnabled' => $spbc->data['extra_package']['backend_logs'],
                'wlModeEnabled' => $spbc->data["wl_mode_enabled"],
                'wlCompanyName' => $spbc->data["wl_company_name"],
                'backendLogsLink' => self::getBackendLogsLink(),
                'myBillingLink' => self::getMyBillingLink(),
                'wpUploadDirPreventPhpExecutionDesc' => \CleantalkSP\SpbctWP\UploadDirPreventPhpExecutionModule\UploadDirPreventPhpExecution::getDescription(
                    isset($spbc->data['upload_dir_prevent_php_execution_status']) ? $spbc->data['upload_dir_prevent_php_execution_status'] : null
                ),
                'spbctPluginDir' => SPBC_PLUGIN_DIR,
                'directorySeparator' => DIRECTORY_SEPARATOR,
                'trustedAndAffiliateAddIdLink' => LinkConstructor::buildSimpleLink(
                    'https://cleantalk.org',
                    'my/partners'
                ),
            ];

            $display_debug = in_array(Server::getDomain(), array(
                    'lc',
                    'loc',
                    'local',
                    'lh',
                    'wordpress'
                )) || $spbc->debug || $spbc->show_debug;

            $spbct_tabs_data = [
                "criticalCount" => $spbc->key_is_ok ? $spbc->data['display_scanner_warnings']['critical'] : "",
                "vulnerabilitiesCount" => $spbc->key_is_ok ? VulnerabilityAlarmView::getCountOfCurrnetlyVulnerableModules() : "",
                "keyIsOk" => $spbc->key_is_ok,
                "displayDebug" => $display_debug,
                "isWPMSMainSite" => is_main_site(),
                "isSecFWEnabled" => (bool) $spbc->settings['secfw__enabled'],
                "isFsWatcherEnabled" => (bool) $spbc->settings['scanner__fs_watcher'],
                "isVulnerabilityCheckEnabled" => (bool) $spbc->settings['vulnerability_check__enable_cron'],
            ];
        }

        // Show fullpage trial banner instead of settings if conditions are met
        $trial_fullpage_banner = new AdminBannerTrialAndRenewFullpage(new AdminBannersHandler($spbc));
        $trial_fullpage_style = '';
        if ( $trial_fullpage_banner->needToShow() ) {
            $trial_fullpage_banner->display();
            $trial_fullpage_style = 'display:none;';
        }

        echo '<div 
            id="spbct-page--react"
            data-page-data=\'' . esc_attr(json_encode($spbct_page_data)) . '\'
            data-tabs-data=\'' . esc_attr(json_encode($spbct_tabs_data)) . '\' 
            style="' . esc_attr($trial_fullpage_style) . '"
            ></div>';
    }

    private static function getAdminsOnline()
    {
        global $spbc;
        $authorized_admins = spbc_get_authorized_admins(true);
        $admin_names_online = !empty($authorized_admins)
            ? implode(',', $authorized_admins)
            : 'n/a';
        $caption = __('Admins online', 'security-malware-firewall');
        $out = sprintf(
            '<a href="options-general.php?page=spbc&spbc_tab=security_log">%s</a>
                    <span style="padding-left: 2px">%d</span>
                    <i class="spbc-icon-help-circled" title="%s"></i>',
            $caption,
            $spbc->counter__admins_online,
            $admin_names_online
        );
        return $out;
    }

    private static function getPremiumLink()
    {
        return spbc_badge__get_premium(false, true);
    }

    private static function getSupportLink()
    {
        global $spbc;

        $support_link = LinkConstructor::buildSimpleLink(
            'https://wordpress.org/',
            'support/plugin/security-malware-firewall/'
        );
        if ($spbc->data["wl_mode_enabled"]) {
            $support_link = $spbc->data["wl_support_url"];
        }

        return $support_link;
    }

    private static function getFeedbackRequest()
    {
        global $spbc;

        $feedback_link = '';
        if (!$spbc->data["wl_mode_enabled"]) {
            $feedback_link = LinkConstructor::buildSimpleLink(
                'https://wordpress.org/',
                'support/plugin/security-malware-firewall/reviews/#new-post'
            );
        }

        return $feedback_link;
    }

    private static function goToCleantalkLink()
    {
        global $spbc;

        $link = '';

        if ($spbc->key_is_ok && !$spbc->data["wl_mode_enabled"]) {
            $link = "https://cleantalk.org/my?user_token=" . $spbc->user_token . "&cp_mode=security";
        }

        return $link;
    }

    private static function getBackendLogsLink()
    {
        global $spbc;

        $link = '';

        if ($spbc->key_is_ok && $spbc->user_token) {
            $link = LinkConstructor::buildSimpleLink(
                'https://cleantalk.org/',
                'my/backend_logs?user_token=' . $spbc->user_token
            );
        }

        return $link;
    }

    private static function getMyBillingLink()
    {
        global $spbc;

        $link = '';

        if ($spbc->key_is_ok) {
            $link = LinkConstructor::buildSimpleLink(
                'https://cleantalk.org/',
                'my/bill/security?package=1'
            );
        }

        return $link;
    }

    private static function support2Link()
    {
        global $spbc;

        $link = '';

        if ($spbc->key_is_ok && !$spbc->data["wl_mode_enabled"]) {
            $link = $spbc->data["wl_support_url"];
        }

        return $link;
    }

    private static function checkPhpVersion()
    {
        global $spbc;

        if (is_admin() && version_compare(phpversion(), '5.4.0', '<')) {
            $spbc->error_add('php_version', '');
        } else {
            $spbc->error_delete('php_version');
        }
    }

    private static function checkMemoryLimit()
    {
        global $spbc;

        $m_limit = ini_get('memory_limit');

        if (is_string($m_limit) && $m_limit !== "-1") {
            $prefix = strtolower(substr($m_limit, - 1, 1));
            $number = substr($m_limit, 0, - 1);
            switch ($prefix) {
                case 'k':
                    $m_limit = (int)$number * 1000;
                    break;
                case 'm':
                    $m_limit = (int)$number * 1000000;
                    break;
                case 'g':
                    $m_limit = (int)$number * 1000000000;
                    break;
            }

            if ($m_limit - memory_get_usage(true) < 25 * 1024 * 1024) {
                $spbc->error_add('memory_limit_low', '');
            } else {
                $spbc->error_delete('memory_limit_low');
            }
        }
    }
}
