<?php

namespace CleantalkSP\SpbctWP\UsersPassCheckModule;

use CleantalkSP\Common\TextPlate;

class UserPassCheckView
{
    use TextPlate;

    const VULNERABLE_CAPABILITIES = array(
        //default wp editor role caps
        'moderate_comments',
        'manage_categories',
        'manage_links',
        'edit_others_posts',
        'edit_pages',
        'edit_others_pages',
        'edit_published_pages',
        'publish_pages',
        'delete_pages',
        'delete_others_pages',
        'delete_published_pages',
        'delete_others_posts',
        'delete_private_posts',
        'edit_private_posts',
        'read_private_posts',
        'delete_private_pages',
        'edit_private_pages',
        'read_private_pages',
        //custom spbc caps
        'manage_options',
        'activate_plugins'
    );

    /**
     * @psalm-suppress PossiblyUnusedMethod
     */
    public static function getRolesSelect()
    {
        global $spbc, $wp_roles;
        $wp_roles   = new \WP_Roles();
        $roles_name = $wp_roles->get_names();

        $select_size = count($roles_name) - 1 < 6 ? count($roles_name) - 1 : 5;
        $is_disabled = ! $spbc->settings['check_pass__enable'] ? ' disabled="disabled"' : '';

        // Generate options for select
        $options_html = '';
        foreach ( $roles_name as $role => $role_name ) {
            $is_role_enabled = self::isRoleEnabled($role, (array)$spbc->settings['check_pass__roles'], $wp_roles);
            $selected_chunk  = $is_role_enabled ? ' selected="selected"' : '';
            $options_html .= sprintf(
                '<option%s value="%s">%s</option>',
                $selected_chunk,
                esc_attr($role),
                esc_html($role_name)
            );
        }

        // Main template
        $template = '
            <div class="spbc_wrapper_field spbc_sub_setting">
                <span class="spbc_settings-field_title spbc_settings-field_title--field">%s</span><br>
                <div style="margin-bottom: 10px" class="spbc_settings_description">%s</div>
                <select multiple="multiple" id="spbc_setting_check_pass__roles" name="spbc_settings[check_pass__roles][]"%s size="%d">%s</select>
            </div>
        ';

        $out = sprintf(
            $template,
            esc_html__(
                'Roles that use checking the user\'s password for information leaks',
                'security-malware-firewall'
            ),
            esc_html__(
                'Hold CTRL button to select multiple roles. Users with unselected roles keep log in to your website in a standard way with their logins and passwords.',
                'security-malware-firewall'
            ),
            $is_disabled,
            $select_size,
            $options_html
        );

        return $out;
    }

    /**
     * @param string $role
     * @param array $spbc_settings_roles
     * @param \WP_Roles $wp_roles
     *
     * @return bool
     */
    private static function isRoleEnabled($role, $spbc_settings_roles, $wp_roles)
    {
        $enabled_roles = !empty($spbc_settings_roles) ? $spbc_settings_roles : array();
        // First run - show roles with capabilities higher than or equal to editor
        if ( empty($enabled_roles) ) {
            // Get roles that have at least one editor-level capability
            foreach ( $wp_roles->roles as $role_slug => $role_data ) {
                foreach ( static::VULNERABLE_CAPABILITIES as $cap ) {
                    if ( isset($role_data['capabilities'][$cap]) && $role_data['capabilities'][$cap] ) {
                        $enabled_roles[] = $role_slug;
                        break;
                    }
                }
            }
        }

        return in_array($role, $enabled_roles);
    }

    public static function getLongDescription()
    {
        global $spbc;
        $text = '
<div>
    <p>{{heading}}</p>
    <p>{{short_desc}}</p>
    <p>{{how_often}}</p>   
    <p><b>{{not_raw}}</b></p>
    <p>{{statuses_head}}</p>
    <p>{{leaked}}</p>
    <p>{{ok}}</p>
    <p>{{unverified}}</p>
</div>';
        $plate = array(
            'heading' => sprintf(__('This functional is provided by %s plugin.', 'security-malware-firewall'), $spbc->data['wl_brandname']),
            'how_often' => sprintf(__('The check being run every 10 days by default, also the check will be performed within %s minutes since a user finished the login process.', 'security-malware-firewall'), round(UsersPassCheckCron::CRON_JOB_WORKER_PERIOD / 60, 2)),
            'short_desc' => __('The process checks if a user`s password is listed in public leaks databases.', 'security-malware-firewall'),
            'not_raw' => __('The feature operates with a part of password hash and does not operate raw passwords.', 'security-malware-firewall'),
            'statuses_head' => __('Statuses description:', 'security-malware-firewall'),
            'leaked' => __('* Leaked - the password hash found in databases', 'security-malware-firewall'),
            'ok' => __('* Checked and safe - the password is strong enough', 'security-malware-firewall'),
            'unverified' => __('* Not verified - the user`s role is not selected int he plugin settings or user has not logged in since the service started', 'security-malware-firewall'),
        );
        return self::textPlateRender($text, $plate);
    }

    public static function lastCallDescription()
    {
        $last_request_ts = UsersPassCheckCron::getLastCheckTime();

        if (empty($last_request_ts)) {
            $msg = __('Not checked yet', 'security-malware-firewall');
        } else {
            $msg = date('M d Y H:i:s', $last_request_ts);
        }

        return esc_html(sprintf(__('Last check performed on %s', 'security-malware-firewall'), $msg));
    }

    public static function nextCallDescription()
    {
        $next_call_final_ts = UsersPassCheckCron::getNextCheckTime();

        if (empty($next_call_final_ts)) {
            $msg = __('Next check time is undefined.', 'security-malware-firewall');
        } else {
            $msg = date('M d Y H:i:s', $next_call_final_ts);
        }

        return esc_html(sprintf(__('Next check scheduled on %s', 'security-malware-firewall'), $msg));
    }

    public static function callsDescriptionForUsersPage()
    {
        $next_call_final_ts = UsersPassCheckCron::getNextCheckTime();
        $last_request_ts = UsersPassCheckCron::getLastCheckTime();

        if (empty($last_request_ts)) {
            $next_call_text = $next_call_final_ts ? date('M d Y H:i:s', $next_call_final_ts) : __('unknown datetime', 'security-malware-firewall');
            $msg = sprintf(
                __('Not checked, scheduled on %s', 'security-malware-firewall'),
                $next_call_text
            );
        } else {
            $msg = sprintf(
                __('Last check at: %s', 'security-malware-firewall'),
                date('M d Y H:i:s', $last_request_ts)
            );
        }

        return esc_html($msg);
    }
}
