<?php

use CleantalkSP\SpbctWP\Cron as SpbcCron;
use CleantalkSP\SpbctWP\Escape;
use CleantalkSP\SpbctWP\HTTP\CDNHeadersChecker;
use CleantalkSP\SpbctWP\UsersPassCheckModule\UsersPassCheckCron;
use CleantalkSP\SpbctWP\UsersPassCheckModule\UsersPassCheckModel;

// Prevent direct call
if ( ! defined('ABSPATH') ) {
    die('Not allowed!');
}

/**
 * Admin callback function - Displays current statistics
 * @return string
 */
function spbc_field_support()
{
    $template = '
        <h3 class="spbc_group_header">%1$s</h3>
        <div class="spbc_stats_support_buttons_wrapper">
            <span class="spbc_stats_support_button">
                <a href="%3$s" class="spbc_manual_link spbc_page_buttons_links_basic_align" target="_blank">
                    <div>%2$s</div>
                </a>
            </span>
            <span class="spbc_stats_support_button">
                <a href="%6$s" class="spbc_manual_link spbc_page_buttons_links_basic_align" target="_blank">
                    <div>%5$s</div>
                </a>
            </span>
            <span class="spbc_stats_support_button">
                <a
                id="spbc_stats_support_button_create_user"
                href="#"
                class="spbc_manual_link spbc_page_buttons_links_basic_align"
                target="_blank"
                onclick="spbcCreateSupportUser(event)"
                >
                    <div>%4$s</div>
                </a>
            </span>
            <div class="spbc_stats_user_creation_result">
                <p id="spbc_stats_user_creation_title"></p>
                <code>
                <p class="spbc_stats_user_creation_row">
                    <span>%7$s:</span><span class="spbc_stats_user_creation_value" id="spbc_stats_user_creation_username"></span>
                </p>
                <p class="spbc_stats_user_creation_row">
                    <span>%8$s:</span><span class="spbc_stats_user_creation_value" id="spbc_stats_user_creation_email"></span>
                </p>
                <p class="spbc_stats_user_creation_row">
                    <span>%9$s:</span><span class="spbc_stats_user_creation_value" id="spbc_stats_user_creation_password"></span>
                </p>
                </code>
                <p id="spbc_stats_user_creation_mail_sent"></p>
                <p id="spbc_stats_user_creation_cron_updated"></p>
            </div>
        </div>
    ';

    $template = sprintf(
        $template,
        __('Support', 'security-malware-firewall'), //1
        __('Open Support Ticket', 'security-malware-firewall'), //2
        'https://wordpress.org/support/plugin/security-malware-firewall', //3
        __('Create Support User', 'security-malware-firewall'), //4
        __('CleanTalk Security Help', 'security-malware-firewall'), //5
        'https://cleantalk.org/help/security-features', //6
        __('Username', 'security-malware-firewall'), //7
        __('Email', 'security-malware-firewall'), //8
        __('Password', 'security-malware-firewall') //9
    );
    return $template;
}

/**
 * Admin callback function - Displays current statistics
 * @return string
 */
function spbc_field_statistics()
{
    global $spbc;

    $templates = [
        'security_log' => __('%d events have been sent to %s Cloud on %s.', 'security-malware-firewall'),
        'fw_log' => __(
            'Information about %d blocked entries have been sent to %s Cloud on %s.',
            'security-malware-firewall'
        ),
        'fw_stats' => __(
            'Security FireWall database has %s. Last updated at %s.',
            'security-malware-firewall'
        ),
        'fw_updating' => __('<b>Under updating now: %s%%</b>', 'security-malware-firewall'),
        'scanner_signatures' => __(
            'Malware scanner signatures was updated %s. For now it contains %s entries.',
            'security-malware-firewall'
        ),
        'last_scan' => __('The last scan of this website was on %s%s', 'security-malware-firewall'),
        'scan_sent' => __('Scan results were sent to the cloud at %s', 'security-malware-firewall'),
        'php_log' => __(
            '%d errors in PHP log have been sent to CleanTalk Cloud on %s',
            'security-malware-firewall'
        ),
        'vuln_check' => __('Closest vulnerabilities check requests%s: %s, %s', 'security-malware-firewall'),
        'plugins_header' => __('%s:', 'security-malware-firewall'),
        'plugins_row' => __('%s: %d', 'security-malware-firewall'),
        'version' => __('Plugin version: %s', 'security-malware-firewall'),
    ];

    $output = '<h3 class="spbc_group_header">' . __('Statistics', 'security-malware-firewall') . '</h3>';
    $output .= '<div class="spbc_wrapper_field">';

    // Security log statistics
    $output .= isset($spbc->data['logs_last_sent'], $spbc->data['last_sent_events_count'])
        ? sprintf(
            $templates['security_log'],
            $spbc->data['last_sent_events_count'],
            $spbc->data["wl_brandname"],
            date("M d Y H:i:s", $spbc->data['logs_last_sent'])
        )
        : __('Unknown last logs sending time.', 'security-malware-firewall');
    $output .= '<br />';

    // Firewall statistics
    if ( isset($spbc->fw_stats['last_updated'], $spbc->fw_stats['entries']) ) {
        $networks_count = sprintf(__('%d Networks', 'security-malware-firewall'), $spbc->fw_stats['entries']);

        if ( isset($spbc->fw_stats['ips_count']) ) {
            $networks_count .= ' ' . sprintf(
                __('(%s k IPs)', 'security-malware-firewall'),
                number_format($spbc->fw_stats['ips_count'] / 1000, 0, '', ' ')
            );
        }

        $output .= sprintf(
            $templates['fw_stats'],
            $networks_count,
            date('M d Y H:i:s', $spbc->fw_stats['last_updated'])
        );
    } else {
        $output .= __('Unknown last Security FireWall updating time.', 'security-malware-firewall');
    }

    $output .= '<br />';

    if ( $spbc->fw_stats['updating_id'] ) {
        $output .= sprintf($templates['fw_updating'], $spbc->fw_stats['update_percent']) . '<br />';
    }

    // Scanner statistics
    if ( $spbc->scaner_enabled ) {
        $duration = isset($spbc->data['scanner']['scan_start_timestamp'], $spbc->data['scanner']['scan_finish_timestamp'])
            ? sprintf(
                ' (%s %d %s)',
                __('duration', 'security-malware-firewall'),
                $spbc->data['scanner']['scan_finish_timestamp'] - $spbc->data['scanner']['scan_start_timestamp'],
                __('sec', 'security-malware-firewall')
            )
            : '';

        $output .= isset($spbc->data['scanner']['last_signature_update'], $spbc->data['scanner']['signature_count'])
            ? sprintf(
                $templates['scanner_signatures'],
                date('M d Y H:i:s', $spbc->data['scanner']['last_signature_update']),
                $spbc->data['scanner']['signature_count']
            )
            : __('Malware scanner signatures hasn\'t been updated yet.', 'security-malware-firewall');

        $output .= '<br />';

        $output .= ! empty($spbc->data['scanner']['last_scan'])
            ? sprintf(
                $templates['last_scan'],
                date('M d Y H:i:s', $spbc->data['scanner']['last_scan']),
                $duration
            )
            : __('Website hasn\'t been scanned yet.', 'security-malware-firewall');

        $output .= '<br />';

        if ( isset($spbc->data['scanner']['last_sent']) ) {
            $output .= sprintf(
                $templates['scan_sent'],
                date('M d Y H:i:s', $spbc->data['scanner']['last_sent'])
            );
            $output .= '<br />';
        }
    }

    if (is_main_site()) {
        // Firewall log statistics
        $output .= isset($spbc->fw_stats['last_send'], $spbc->fw_stats['last_send_count'])
            ? sprintf(
                $templates['fw_log'],
                $spbc->fw_stats['last_send_count'],
                $spbc->data["wl_brandname"],
                date("M d Y H:i:s", $spbc->fw_stats['last_send'])
            )
            : __('Unknown last firewall logs sending time.', 'security-malware-firewall');
        $output .= '<br />';

        // PHP log sending statistics
        $date_string = date(
            'M d Y H:i:s',
            $spbc->data['last_php_log_sent'] + $spbc->data['site_utc_offset_in_seconds']
        );

        $output .= isset($spbc->data['last_php_log_sent'], $spbc->data['last_php_log_amount'])
            ? sprintf(
                $templates['php_log'],
                $spbc->data['last_php_log_amount'],
                $date_string
            )
            : __('Unknown last PHP log sending time.', 'security-malware-firewall');
        $output .= '<br/>';

        // Vulnerability checks
        $cron_task_info = SpbcCron::getTask('check_vulnerabilities');
        $next_call      = ! empty($cron_task_info['next_call'])
            ? date('M d Y H:i:s', (int)($cron_task_info['next_call'] + $spbc->data['site_utc_offset_in_seconds']))
            : __('unknown', 'security-malware-firewall');

        $last_call = ! empty($spbc->data['spbc_security_check_vulnerabilities_last_call'])
            ? date(
                'M d Y H:i:s',
                (int)($spbc->data['spbc_security_check_vulnerabilities_last_call'] + $spbc->data['site_utc_offset_in_seconds'])
            )
            : __('unknown', 'security-malware-firewall');

        $research_text = empty($spbc->data['wl_mode_enabled'])
            ? ' ' . __(
                'performed to',
                'security-malware-firewall'
            ) . ' <a href="https://research.cleantalk.org">research.cleantalk.org</a>'
            : '';

        $output .= sprintf(
            $templates['vuln_check'],
            $research_text,
            __('last call on', 'security-malware-firewall') . ' ' . $last_call,
            __('next call on', 'security-malware-firewall') . ' ' . $next_call
        );
        $output .= '<br/>';

        // Plugins/Themes vulnerabilities
        if (
            $spbc->settings['vulnerability_check__enable_cron']
            && $spbc->settings['vulnerability_check__warn_on_modules_pages']
        ) {
            $output .= '<br/>';
            $output .= sprintf(
                $templates['plugins_header'],
                __('The results of checking plugins for vulnerabilities', 'security-malware-firewall')
            );
            $output .= '<br/>';
            $output .= sprintf(
                $templates['plugins_row'],
                __('Total site plugins count', 'security-malware-firewall'),
                $spbc->scan_plugins_info['total_site_plugins_count']
            );
            $output .= '<br/>';
            $output .= sprintf(
                $templates['plugins_row'],
                __('Plugins info requested', 'security-malware-firewall'),
                $spbc->scan_plugins_info['plugins_info_requested']
            );
            $output .= '<br/>';
            $output .= sprintf(
                $templates['plugins_row'],
                __('Plugins found with known vulnerabilities', 'security-malware-firewall'),
                $spbc->scan_plugins_info['plugins_found_with_known_vulnerabilities']
            );
            $output .= '<br/><br/>';

            $output .= sprintf(
                $templates['plugins_header'],
                __('The results of checking themes for vulnerabilities', 'security-malware-firewall')
            );
            $output .= '<br/>';
            $output .= sprintf(
                $templates['plugins_row'],
                __('Total site themes count', 'security-malware-firewall'),
                $spbc->scan_themes_info['total_site_themes_count']
            );
            $output .= '<br/>';
            $output .= sprintf(
                $templates['plugins_row'],
                __('Themes info requested', 'security-malware-firewall'),
                $spbc->scan_themes_info['themes_info_requested']
            );
            $output .= '<br/>';
            $output .= sprintf(
                $templates['plugins_row'],
                __('Themes found with known vulnerabilities', 'security-malware-firewall'),
                $spbc->scan_themes_info['themes_found_with_known_vulnerabilities']
            );
            $output .= '<br/>';

            // Users pass check
            if ($spbc->settings['check_pass__enable']) {
                $output .= '<br/>';
                $output .= __('Password Security Summary: ', 'security-malware-firewall');
                $output .= '<br/>';
                $output .= UsersPassCheckCron::getLastCheckTime();
                $output .= '<br/>';
                $output .= sprintf(
                    __('Total users checked: %s', 'security-malware-firewall'),
                    UsersPassCheckModel::getTotalUsersChecked()
                );
                $output .= '<br/>';
                $output .= sprintf(
                    __('Safe passwords: %s', 'security-malware-firewall'),
                    UsersPassCheckModel::getSafePasswordsCount()
                );
                $output .= '<br/>';
                $output .= sprintf(
                    __('Compromised passwords: %s (<a href="%s">View details</a>)', 'security-malware-firewall'),
                    UsersPassCheckModel::getCompromisedPasswordsCount(),
                    '/wp-admin/users.php'
                );
                $output .= '<br/>';
                $output .= sprintf(
                    __('Pending checks: %s', 'security-malware-firewall'),
                    UsersPassCheckModel::getPendingChecksCount()
                );
                $output .= '<br/>';
                $output .= '<br/>';
            }
        }
    }

    // CDN Checker
    add_filter('safe_style_css', function ($styles) {
        $styles[] = 'display';

        return $styles;
    });
    $output .= Escape::escKsesPreset(CDNHeadersChecker::getSummaryBlockHTML(), 'spbc_cdn_checker_table');
    $output .= '<br/>';

    // Version
    $output .= sprintf($templates['version'], SPBC_VERSION);
    $output .= '</div>';

    // 3. Support link
    $output .= sprintf(
        '%s %s.',
        __('Tech support:', 'security-malware-firewall'),
        $spbc->data["wl_mode_enabled"]
            ? sprintf(
                '<a target="_blank" href="%s">%s</a><br>',
                $spbc->data["wl_support_url"],
                $spbc->data["wl_brandname"]
            )
            : '<a target="_blank" href="https://wordpress.org/support/plugin/security-malware-firewall/">wordpress.org</a>'
    );
    // 4. Plugin home page
    $output .= sprintf(
        '%s <a href="%s" target="_blank">%s</a>.<br>',
        __('The plugin home page', 'security-malware-firewall'),
        $spbc->data["wl_url"],
        $spbc->data["wl_brandname"]
    );

    // 5. Trademark notice
    $output .= sprintf(
        '%s %s<br><br>',
        $spbc->data["wl_brandname"],
        __('is a registered trademark. All rights reserved.', 'security-malware-firewall')
    );

    return $output;
}
