<?php


class ISTKR_AdvisorModel
{

    public static function istkr_advice_database_prefix()
    {

        // try {
        global $wpdb;

        $state = $wpdb->prefix === 'wp_';

        return [
            'state' => $state ? __('Failed', 'istkr') : __('Passed', 'istkr'),
            'meta' => self::istkr_get_check_details_by_name('istkr_advice_database_prefix', $state)
        ];
        // } catch (Exception $e) {
        //     // throw new Exception()
        // }
    }

    public static function istkr_advice_database_username()
    {

        $state = false;

        if (isset(ISTKR_Security::COMMON_USERNAMES[DB_USER]) !== false) {
            $state = true;
        }

        return [
            'state' => $state ? __('Failed', 'istkr') : __('Passed', 'istkr'),
            'meta' => self::istkr_get_check_details_by_name('istkr_advice_database_username', $state)
        ];
    }

    public static function istkr_advice_database_password()
    {

        $state = false;

        if (isset(ISTKR_Security::COMMON_PASSWORDS[DB_USER]) !== false) {
            $state = true;
        }

        return [
            'state' => $state ? __('Failed', 'istkr') : __('Passed', 'istkr'),
            'meta' =>  self::istkr_get_check_details_by_name('istkr_advice_database_password', $state)
        ];
    }


    public static function istkr_advice_outdated_php()
    {

        $state = version_compare(phpversion(), '7.4', '<');
        return [
            'state' => $state ? __('Failed', 'istkr') : __('Passed', 'istkr'),
            'meta' => self::istkr_get_check_details_by_name('istkr_advice_outdated_php', $state)
        ];
    }


    public static function istkr_advice_users_with_popular_logins()
    {

        global $wpdb;

        $raw_users = $wpdb->get_results('SELECT `user_login` FROM ' . $wpdb->prefix . 'users', ARRAY_A);

        $storage = [];
        foreach ($raw_users as $user) {
            if (isset($user['user_login'])) {
                array_push($storage, $user['user_login']);
            }
        }


        $match = array_uintersect($storage, ISTKR_Security::COMMON_USERNAMES, "strcasecmp");

        return [
            'state' => (bool) $match ? __('Failed', 'istkr') : __('Passed', 'istkr'),
            'meta' => self::istkr_get_check_details_by_name('istkr_advice_users_with_popular_logins', (bool) $match)
        ];
    }

    public static function istkr_advice_is_ssl_enabled()
    {
        return [
            'state' => !is_ssl() ? __('Failed', 'istkr') : __('Passed', 'istkr'),
            'meta' =>  self::istkr_get_check_details_by_name('istkr_advice_is_ssl_enabled', !is_ssl())
        ];
    }

    public static function istkr_advice_is_wp_ver_displayed()
    {

        try {
            $state = false;
            $site_html = wp_remote_get(get_home_url());

            if ($site_html instanceof WP_Error) {
                throw new Exception(__("Can't get the source code of the homepage. Check if cURL is enabled", 'istkr'));
            }

            if ($site_html && isset($site_html['body'])) {
                if (strpos($site_html['body'], '<meta name="generator" content="WordPress') !== false) {
                    $state = true;
                }
            }

            return [
                'state' => $state ? __('Failed', 'istkr') : __('Passed', 'istkr'),
                'meta' => self::istkr_get_check_details_by_name('istkr_advice_is_wp_ver_displayed', $state)
            ];
        } catch (Exception $e) {
            return [
                'state' => 'Failed',
                'meta' => [
                    'recommendation' => __('Checking failed. Exception description:', 'istkr') . ' ' . $e->getMessage()
                ]
            ];
        }
    }

    public static function istkr_advice_is_display_errors_enabled()
    {

        $state = WP_DEBUG && WP_DEBUG_DISPLAY;

        return [
            'state' => $state ? __('Failed', 'istkr') : __('Passed', 'istkr'),
            'meta' => self::istkr_get_check_details_by_name('istkr_advice_is_display_errors_enabled', $state),
        ];
    }

    public static function istkr_advice_free_disk_space()
    {

        $root =  $_SERVER['DOCUMENT_ROOT'] ?  $_SERVER['DOCUMENT_ROOT'] : '/';

        $busy_disk_percent = 100 - (disk_free_space($root) * 100) / disk_total_space($root);
        // If used space more than 80%
        $state = (int) $busy_disk_percent < 80;

        return [
            'state' => !$state ? __('Failed', 'istkr') : __('Passed', 'istkr'),
            'meta' =>  self::istkr_get_check_details_by_name('istkr_advice_free_disk_space', $state),
        ];
    }

    public static function istkr_advice_search_visibility()
    {
        $visibility_enabled = get_option('blog_public');
        if (self::istkr_is_localhost()) {
            return [
                'state' => __('Passed', 'istkr'),
                'meta' => self::istkr_get_check_details_by_name('istkr_advice_search_visibility_local')
            ];
        }

        $state = (bool) $visibility_enabled;
        return [
            'state' => $state ? __('Passed', 'istkr') : __('Failed', 'istkr'),
            'meta' =>  self::istkr_get_check_details_by_name('istkr_advice_search_visibility_prod', $state),
        ];
    }

    public static function istkr_run_checks()
    {
        return [
            'istkr_advice_database_password'         => self::istkr_advice_database_password()['state'],
            'istkr_advice_database_prefix'           => self::istkr_advice_database_prefix()['state'],
            'istkr_advice_database_username'         => self::istkr_advice_database_username()['state'],
            'istkr_advice_outdated_php'              => self::istkr_advice_outdated_php()['state'],
            'istkr_advice_is_display_errors_enabled' => self::istkr_advice_is_display_errors_enabled()['state'],
            'istkr_advice_is_ssl_enabled'            => self::istkr_advice_is_ssl_enabled()['state'],
            'istkr_advice_is_wp_ver_displayed'       => self::istkr_advice_is_wp_ver_displayed()['state'],
            'istkr_advice_users_with_popular_logins' => self::istkr_advice_users_with_popular_logins()['state'],
            'istkr_advice_free_disk_space'           => self::istkr_advice_free_disk_space()['state'],
            'istkr_advice_search_visibility'         => self::istkr_advice_search_visibility()['state']
        ];
    }

    public static function istkr_get_check_details_by_name($check_name, $state = false)
    {
        $checks = [
            'istkr_advice_database_password' => [
                'title' => __('This check verifies if the database password used in \'wp-config.php\' is commonly employed, potentially posing a security risk.', 'istkr'),
                'recommendation' => $state
                    ? __('To mitigate the risk of unauthorized access to the database, it is recommended to update the database password to a highly complex and secure one', 'istkr')
                    : __('Great news! The database password is not commonly used, so there\'s no immediate action required. Well done!', 'istkr')
            ],

            'istkr_advice_database_prefix' => [
                'title' => __('This check identifies whether the default database prefix is in use', 'istkr'),
                'recommendation' => $state
                    ? __('Please consider changing the database prefix from \'_wp\' to a more complex and unique one for improved security', 'istkr')
                    : __('The database prefix is not set to the default \'_wp,\' so there\'s no need for further action. Well done!', 'istkr')
            ],

            'istkr_advice_database_username' => [
                'title' => __('This check determines if the database username specified in \'wp-config.php\' is commonly used, which could pose a security risk.', 'istkr'),
                'recommendation' => $state
                    ? __('To enhance security and reduce the risk of unauthorized access to the database, it is advisable to update the database username to a highly complex and unique one', 'istkr')
                    : __('Great news! The database username is not commonly used, so there\'s no action required. Well done!', 'istkr')
            ],

            'istkr_advice_outdated_php' => [
                'title' => __('This check verifies whether the PHP version being used is up-to-date', 'istkr'),
                'recommendation' => $state
                    ? __('To improve security and performance, it is recommended to update PHP to the latest stable version available', 'istkr')
                    : __("Nothing to do. You're using", 'istkr') . ' ' . phpversion() . ' ' . __('but outdated PHP version, for now, is 7.4. No further action is needed. Well done!', 'istkr')
            ],

            'istkr_advice_is_display_errors_enabled' => [
                'title' => __('This check examines the current state of the \'WP_DEBUG_DISPLAY\' constant', 'istkr'),
                'recommendation' => $state
                    ? __("For enhanced security, it's important to set 'WP_DEBUG_DISPLAY' to 'false' on the Log Viewer page (or in the 'wp-config.php' file). This prevents visitors from viewing debug information on their screens, reducing potential vulnerabilities", 'istkr')
                    : __('Debug information will not be displayed to your visitors, reducing potential vulnerabilities. Well done!', 'istkr')
            ],

            'istkr_advice_is_ssl_enabled' => [
                'title' => __('This check verifies whether SSL (HTTPS) encryption is enabled for your website', 'istkr'),
                'recommendation' =>  $state
                    ? __("Data transmitted between your web server and users' browsers is not currently encrypted. It is strongly recommended to implement SSL (HTTPS) to secure this data.", 'istkr')
                    : __('Great news! Data between your web server and users\' browsers is encrypted. Well done on implementing SSL!', 'istkr')
            ],

            'istkr_advice_is_wp_ver_displayed' => [
                'title' => __('This check examines whether the WordPress version is disclosed in the HTML code of the website', 'istkr'),
                'recommendation' => $state
                    ? __("To enhance security, consider adding the following code into the 'functions.php' file of your theme: <b>remove_action( 'wp_head', 'wp_generator' ); </b>This will remove the WordPress version information from the HTML code, making it less visible to potential attackers.", 'istkr')
                    : __('Your WordPress version is not detectable in the HTML code of your site, which is a good security practice. Well done!', 'istkr')
            ],

            'istkr_advice_users_with_popular_logins' => [
                'title' => __('This check examines whether widely used usernames are being used for registered users on the website', 'istkr'),
                'recommendation' => $state
                    ? __("To reduce the risk of security breaches, it's advisable to avoid using usernames like 'admin,' 'root,' or 'administrator' due to their high susceptibility to hacking attempts", 'istkr')
                    : __('The check did not detect users with widely used usernames, which is a positive security measure. Well done!', 'istkr')
            ],

            'istkr_advice_free_disk_space' => [
                'title' => __('This check evaluates whether there is more than 80% free disk space available (beta)', 'istkr'),
                'recommendation' => !$state
                    ? __('To ensure optimal performance and storage capacity, it is recommended to free up additional disk space by removing unnecessary files, backups, etc.', 'istkr')
                    : __('Your server\'s disks have sufficient free space, which is essential for smooth operation. Well done!', 'istkr')
            ],
            'istkr_advice_search_visibility_prod' => [
                'title' => __('This check examines if your site is allowed to index by search engines', 'istkr'),
                'recommendation' => $state
                    ? __('Nice! Search engines can index the website', 'istkr')
                    : __('It appears that the site is not under development, and it would be beneficial to allow search engines to index your site. To do this, navigate to Settings, then Reading, and make the necessary adjustments.', 'istkr')
            ],

            'istkr_advice_search_visibility_local' => [
                'title' => __('This check examines if your site is allowed to index by search engines', 'istkr'),
                'recommendation' => __('It appears that your site is currently under development and not accessible globally. As a result, you don\'t need to worry about search engines indexing it for now.', 'istkr')
            ],
        ];

        return isset($checks[$check_name]) ? $checks[$check_name] : null;
    }

    public static function render_advisor_checks($checks)
    {
        $body = "" .
            "<tr>" .
            "    <td>Problem</td>" .
            "    <td>Solution</td>" .
            "</tr>";

        $row = "" .
            "<tr>" .
            "    <td>%s</td>" .
            "    <td>%s</td>" .
            "</tr>";

        foreach ($checks as $key => $value) {
            $details = ISTKR_AdvisorModel::istkr_get_check_details_by_name($key, true);
            $body .= sprintf($row, $details['title'], $details['recommendation']);
        }

        return $body;
    }

    public static function istkr_is_localhost()
    {
        return (bool) strpos(get_site_url(), 'localhost');
    }
}
