<?php
/**
 * MainWP Manage Sites View.
 *
 * @package MainWP/Dashboard
 */

namespace MainWP\Dashboard;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Class MainWP_Manage_Sites_View
 *
 * @package MainWP\Dashboard
 */
class MainWP_Manage_Sites_View { // phpcs:ignore Generic.Classes.OpeningBraceSameLine.ContentAfterBrace -- NOSONAR.

    // phpcs:disable Generic.Metrics.CyclomaticComplexity -- complexity.
    /**
     * Method init_menu()
     *
     * Initiate Sites sub menu.
     *
     * @return add_submenu_page()
     *
     * @uses \MainWP\Dashboard\MainWP_Manage_Sites::get_class_name()
     */
    public static function init_menu() {
        return add_submenu_page(
            'mainwp_tab',
            __( 'Sites', 'mainwp' ),
            '<span id="mainwp-Sites">' . esc_html__( 'Sites', 'mainwp' ) . '</span>',
            'read',
            'managesites',
            array( MainWP_Manage_Sites::get_class_name(), 'render_manage_sites' )
        );
    }

    /**
     * Method init_subpages_menu()
     *
     * @param array $subPages Sub pages array.
     *
     * @uses \MainWP\Dashboard\MainWP_Menu::is_disable_menu_item()
     */
    public static function init_subpages_menu( &$subPages ) { // phpcs:ignore -- NOSONAR - complex.
        ?>
        <div id="menu-mainwp-Sites" class="mainwp-submenu-wrapper">
            <div class="wp-submenu sub-open" style="">
                <div class="mainwp_boxout">
                    <div class="mainwp_boxoutin"></div>
                    <a href="<?php echo esc_url( admin_url( MainWP_Unhooks_Helper::add_unhooks_params( 'admin.php?page=managesites' ) ) ); ?>" class="mainwp-submenu"><?php esc_html_e( 'Manage Sites', 'mainwp' ); ?></a>
                    <?php if ( \mainwp_current_user_can( 'dashboard', 'add_sites' ) ) { ?>
                        <?php if ( ! MainWP_Menu::is_disable_menu_item( 3, 'managesites_add_new' ) ) { ?>
                            <a href="<?php echo esc_url( admin_url( 'admin.php?page=managesites&do=new' ) ); ?>" class="mainwp-submenu"><?php esc_html_e( 'Add New', 'mainwp' ); ?></a>
                        <?php } ?>
                        <?php if ( ! MainWP_Menu::is_disable_menu_item( 3, 'managesites_import' ) ) { ?>
                            <a href="<?php echo esc_url( admin_url( 'admin.php?page=managesites&do=bulknew' ) ); ?>" class="mainwp-submenu"><?php esc_html_e( 'Import Sites', 'mainwp' ); ?></a>
                        <?php } ?>
                    <?php } ?>
                    <?php if ( ! MainWP_Menu::is_disable_menu_item( 3, 'MonitoringSites' ) ) { ?>
                        <a href="<?php echo esc_url( admin_url( 'admin.php?page=MonitoringSites' ) ); ?>" class="mainwp-submenu"><?php esc_html_e( 'Monitoring', 'mainwp' ); ?></a>
                    <?php } ?>
                    <?php
                    if ( isset( $subPages ) && is_array( $subPages ) ) {
                        foreach ( $subPages as $subPage ) {
                            if ( ! isset( $subPage['menu_hidden'] ) || ( isset( $subPage['menu_hidden'] ) && true !== $subPage['menu_hidden'] ) ) {
                                $sub_slug  = isset( $subPage['slug'] ) ? $subPage['slug'] : '';
                                $sub_title = isset( $subPage['title'] ) ? $subPage['title'] : '';
                                if ( MainWP_Menu::is_disable_menu_item( 3, 'ManageSites' . $sub_slug ) ) {
                                    continue;
                                }
                                ?>
                                <a href="<?php echo esc_url( admin_url( 'admin.php?page=ManageSites' . $sub_slug ) ); ?>" class="mainwp-submenu"><?php echo esc_html( $sub_title ); ?></a>
                                <?php
                            }
                        }
                    }
                    ?>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Method init_left_menu()
     *
     * Initiate left Sites menu.
     *
     * @param array $subPages Sub pages array.
     *
     * @uses \MainWP\Dashboard\MainWP_Menu::add_left_menu()
     * @uses \MainWP\Dashboard\MainWP_Menu::init_subpages_left_menu()
     * @uses \MainWP\Dashboard\MainWP_Menu::is_disable_menu_item()
     */
    public static function init_left_menu( $subPages = array() ) {

        MainWP_Menu::add_left_menu(
            array(
                'title'      => esc_html__( 'Sites', 'mainwp' ),
                'parent_key' => 'mainwp_tab',
                'slug'       => 'managesites',
                'href'       => MainWP_Unhooks_Helper::add_unhooks_params( 'admin.php?page=managesites' ),
                'icon'       => '<i class="globe icon"></i>',
            ),
            0
        );

        $items_menu = array(
            array(
                'title'                => esc_html__( 'Manage Sites', 'mainwp' ),
                'parent_key'           => 'managesites',
                'slug'                 => 'managesites',
                'href'                 => MainWP_Unhooks_Helper::add_unhooks_params( 'admin.php?page=managesites' ),
                'right'                => '',
                'leftsub_order_level2' => 1,
                'id'                   => 'managesites-root',
            ),
            array(
                'title'                => esc_html__( 'Add New', 'mainwp' ),
                'parent_key'           => 'managesites',
                'href'                 => 'admin.php?page=managesites&do=new',
                'slug'                 => 'managesites',
                'right'                => 'add_sites',
                'item_slug'            => 'managesites_add_new',
                'id'                   => 'managesites-addnew',
                'leftsub_order_level2' => 2,
            ),
        );

        MainWP_Menu::init_subpages_left_menu( $subPages, $items_menu, 'managesites', 'ManageSites' );

        foreach ( $items_menu as $item ) {
            if ( isset( $item['item_slug'] ) ) {
                if ( MainWP_Menu::is_disable_menu_item( 3, $item['item_slug'] ) ) {
                    continue;
                }
            } elseif ( MainWP_Menu::is_disable_menu_item( 3, $item['slug'] ) ) {
                continue;
            }
            MainWP_Menu::add_left_menu( $item, 2 );
        }
    }

    /**
     * Method render_header()
     *
     * Build Sites page header.
     *
     * @param string $shownPage Current Page.
     * @param array  $subPages Sites subpages.
     *
     * @uses \MainWP\Dashboard\MainWP_Connect::get_favico_url()
     * @uses \MainWP\Dashboard\MainWP_DB::get_website_by_id()
     * @uses \MainWP\Dashboard\MainWP_UI::render_top_header()
     * @uses \MainWP\Dashboard\MainWP_UI::render_second_top_header()
     */
    public static function render_header( $shownPage = '', $subPages = array() ) { // phpcs:ignore -- NOSONAR - complex.

        if ( '' === $shownPage || 'managesites' === $shownPage ) {
            $shownPage = 'ManageSites';
        }

        $site_id = 0;
        // phpcs:disable WordPress.Security.NonceVerification,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        if ( isset( $_GET['id'] ) && ! empty( $_GET['id'] ) ) {
            $site_id = intval( $_GET['id'] );
        } elseif ( isset( $_GET['backupid'] ) && ! empty( $_GET['backupid'] ) ) {
            $site_id = intval( $_GET['backupid'] );
        } elseif ( isset( $_GET['updateid'] ) && ! empty( $_GET['updateid'] ) ) {
            $site_id = intval( $_GET['updateid'] );
        } elseif ( isset( $_GET['dashboard'] ) && ! empty( $_GET['dashboard'] ) ) {
            $site_id = intval( $_GET['dashboard'] );
        } elseif ( isset( $_GET['scanid'] ) && ! empty( $_GET['scanid'] ) ) {
            $site_id = intval( $_GET['scanid'] );
        } elseif ( isset( $_GET['emailsettingsid'] ) && ! empty( $_GET['emailsettingsid'] ) ) {
            $site_id = intval( $_GET['emailsettingsid'] );
        } elseif ( isset( $_GET['cacheControlId'] ) && ! empty( $_GET['cacheControlId'] ) ) {
            $site_id = intval( $_GET['cacheControlId'] );
        } elseif ( ! empty( $_GET['monitor_wpid'] ) ) {
            $site_id = intval( $_GET['monitor_wpid'] );
        }
        // phpcs:enable WordPress.Security.NonceVerification,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

        $managesites_pages = array(
            'ManageSites'     => array(
                'href'   => MainWP_Unhooks_Helper::add_unhooks_params( 'admin.php?page=managesites' ),
                'title'  => esc_html__( 'Manage Sites', 'mainwp' ),
                'access' => true,
            ),
            'AddNew'          => array(
                'href'   => 'admin.php?page=managesites&do=new',
                'title'  => esc_html__( 'Add New', 'mainwp' ),
                'access' => \mainwp_current_user_can( 'dashboard', 'add_sites' ),
            ),
            'BulkAddNew'      => array(
                'href'   => 'admin.php?page=managesites&do=bulknew',
                'title'  => esc_html__( 'Import Sites', 'mainwp' ),
                'access' => \mainwp_current_user_can( 'dashboard', 'add_sites' ),
            ),
            'MonitoringSites' => array(
                'href'   => 'admin.php?page=MonitoringSites',
                'title'  => esc_html__( 'Monitoring', 'mainwp' ),
                'access' => true,
            ),
        );

        $total_info    = MainWP_Manage_Sites_Update_View::get_total_info( $site_id );
        $total_updates = $total_info['total_upgrades'];
        $after_title   = empty( $total_updates ) ? '' : '<div class="ui tiny green label" timestamp="' . time() . '">' . absint( $total_updates ) . '</div>';

        $site_pages = array(
            'ManageSitesDashboard' => array(
                'href'   => 'admin.php?page=managesites&dashboard=' . $site_id,
                'title'  => esc_html__( 'Overview', 'mainwp' ),
                'access' => \mainwp_current_user_can( 'dashboard', 'access_individual_dashboard' ),
            ),
            'ManageSitesEdit'      => array(
                'href'   => 'admin.php?page=managesites&id=' . $site_id,
                'title'  => esc_html__( 'Settings', 'mainwp' ),
                'access' => \mainwp_current_user_can( 'dashboard', 'edit_sites' ),
            ),
            'ManageSitesUpdates'   => array(
                'href'        => 'admin.php?page=managesites&updateid=' . $site_id,
                'title'       => esc_html__( 'Updates', 'mainwp' ),
                'access'      => \mainwp_current_user_can( 'dashboard', 'access_individual_dashboard' ),
                'after_title' => $after_title,
            ),
            'ManageSitesBackups'   => array(
                'href'   => 'admin.php?page=managesites&backupid=' . $site_id,
                'title'  => esc_html__( 'Backups', 'mainwp' ),
                'access' => \mainwp_current_user_can( 'dashboard', 'execute_backups' ),
            ),
            'SecurityScan'         => array(
                'href'   => 'admin.php?page=managesites&scanid=' . $site_id,
                'title'  => esc_html__( 'Site Hardening', 'mainwp' ),
                'access' => true,
            ),
        );

        /**
         * MainWP Use External Primary backup Method global.
         *
         * @global string
         */
        global $mainwpUseExternalPrimaryBackupsMethod;

        if ( ! empty( $mainwpUseExternalPrimaryBackupsMethod ) ) {
            unset( $site_pages['ManageSitesBackups'] );
        } elseif ( ! get_option( 'mainwp_enableLegacyBackupFeature' ) ) {
            if ( isset( $site_pages['ManageSitesBackups'] ) ) {
                unset( $site_pages['ManageSitesBackups'] );
            }
        }

        $pagetitle = esc_html__( 'Sites', 'mainwp' );

        if ( ! empty( $site_id ) ) {
            $website = MainWP_DB::instance()->get_website_by_id( $site_id );
            if ( $website ) {
                $reconnect = '';
                if ( $site_id && $website && '' !== $website->sync_errors ) {
                    $reconnect = '<a href="#" class="mainwp-updates-overview-reconnect-site item" adminuser="' . esc_attr( $website->adminname ) . '" siteid="' . intval( $site_id ) . '"><i class="sync alternate icon"></i> Reconnect</a>';
                }
                $wp_admin_href = MainWP_Site_Open::get_open_site_url( $site_id, false, false );
                $dropdown      = $reconnect . '
                <a class="item mainwp-remove-site-button" site-id="' . intval( $site_id ) . '" id="mainwp-remove-site-button" href="#"><i class="trash grey icon"></i> Remove Site</a>
                <a id="mainwp-go-wp-admin-button" target="_blank" href="' . $wp_admin_href . '" class="item open_newwindow_wpadmin"><i class="sign in grey icon"></i> Go to WP Admin</a>
                ';
                $site_icon     = '';
                if ( 1 === (int) get_option( 'mainwp_use_favicon', 1 ) ) {
                    $favi_url  = MainWP_Connect::get_favico_url( $website );
                    $site_icon = MainWP_Manage_Sites::get_instance()->get_site_icon_display( $website->cust_site_icon_info, $favi_url );
                }
                $pagetitle                   = $site_icon . '<div class="content"><a href="' . esc_url( MainWP_Site_Open::get_open_site_url( $website->id, '', false ) ) . '" target="_blank" class="open_newwindow_wpadmin" rel="noopener noreferrer" style="font-weight:normal!important;"><i class="sign in grey icon" style="font-weight:normal!important;"></i></a><div class="ui pointing dropdown"><div class="text">' . esc_html( $website->name ) . '</div><i class="dropdown icon"></i><div class="menu">' . $dropdown . '</div></div><div class="sub header"><a href="' . esc_url( $website->url ) . '" target="_blank" style="font-size:10px" class="ui grey text" rel="noopener noreferrer">' . esc_html( MainWP_Utility::get_nice_url( $website->url ) ) . '</a></div></div>';
                $site_pages['JumpToWPAdmin'] = array(
                    'href'   => $wp_admin_href,
                    'title'  => esc_html__( 'Go to WP Admin', 'mainwp' ),
                    'access' => true,
                    'class'  => 'open_newwindow_wpadmin',
                    'target' => '_blank',
                    'rel'    => 'noopener noreferrer',
                );
            }
        }

        $params = array(
            'title' => $pagetitle,
        );

        MainWP_UI::render_top_header( $params );

        $manage_sites = false;
        if ( 'ManageSites' === $shownPage || 'MonitoringSites' === $shownPage ) {
            $manage_sites = true;
        }

        static::render_managesites_header( $site_pages, $managesites_pages, $subPages, $site_id, $shownPage );

        if ( $manage_sites ) {
            $count = MainWP_DB::instance()->get_websites_count( null, false );
            if ( ! empty( $count ) ) {
                $which = strtolower( $shownPage );
                MainWP_UI::render_second_top_header( $which );
            }
        }

        if ( ! empty( $site_id ) ) {
            MainWP_UI::render_modal_reconnect();
        }
    }

    /**
     * Method render_footer()
     *
     * Close the page container.
     */
    public static function render_footer() {
        echo '</div>';
    }

    /**
     * Method render_managesites_header()
     *
     * Render manage sites header.
     *
     * @param array  $site_pages site pages.
     * @param array  $managesites_pages manage site pages.
     * @param array  $subPages sub pages.
     * @param int    $site_id Site id.
     * @param string $shownPage Current Page.
     *
     * @uses \MainWP\Dashboard\MainWP_Menu::is_disable_menu_item()
     * @uses \MainWP\Dashboard\MainWP_UI::render_page_navigation()
     */
    private static function render_managesites_header( $site_pages, $managesites_pages, $subPages, $site_id, $shownPage ) { //phpcs:ignore -- NOSONAR - complex method.

        $renderItems = array();
        if ( isset( $managesites_pages[ $shownPage ] ) ) {
            foreach ( $managesites_pages as $page => $value ) {
                if ( MainWP_Menu::is_disable_menu_item( 3, $page ) ) {
                    continue;
                }

                $item           = $value;
                $item['active'] = ( $page === $shownPage ) ? true : false;
                $renderItems[]  = $item;
            }
        } elseif ( $site_id ) {
            foreach ( $site_pages as $page => $value ) {
                if ( MainWP_Menu::is_disable_menu_item( 3, $page ) ) {
                    continue;
                }
                $item           = $value;
                $item['active'] = ( $page === $shownPage ) ? true : false;
                $renderItems[]  = $item;
            }
        }

        if ( isset( $subPages ) && is_array( $subPages ) ) {
            foreach ( $subPages as $subPage ) {
                if ( MainWP_Menu::is_disable_menu_item( 3, 'ManageSites' . $subPage['slug'] ) ) {
                    continue;
                }

                if ( isset( $subPage['sitetab'] ) && true === $subPage['sitetab'] && empty( $site_id ) ) {
                    continue;
                }
                $item          = array();
                $item['title'] = isset( $subPage['title'] ) ? $subPage['title'] : '';
                $sub_slug      = isset( $subPage['slug'] ) ? $subPage['slug'] : '';

                if ( ! empty( $subPage['href'] ) ) {
                    $item['href'] = $subPage['href'];
                } else {
                    $item['href'] = 'admin.php?page=ManageSites' . $sub_slug . ( $site_id ? '&id=' . esc_attr( $site_id ) : '' );
                }
                $item['active'] = ( $sub_slug === $shownPage ) ? true : false;
                $renderItems[]  = $item;
            }
        }
        $renderItems = apply_filters( 'mainwp_manage_sites_navigation_items', $renderItems, $site_id, $shownPage );
        MainWP_UI::render_page_navigation( $renderItems );
    }

    /**
     * Method render_import_sites()
     *
     * Render import sites dialog.
     *
     * @uses \MainWP\Dashboard\MainWP_System_Utility::get_wp_file_system()
     * @uses  \MainWP\Dashboard\MainWP_Utility::starts_with()
     */
    public static function render_import_sites() { // phpcs:ignore -- NOSONAR - complex.
        ?>
        <div id="mainwp-importing-sites" class="ui active dimmer">
            <div class="ui double text loader"><?php esc_html_e( 'Importing...', 'mainwp' ); ?></div>
        </div>
        <div class="ui message" id="mainwp-import-sites-status-message">
            <?php echo '<i class="notched circle loading icon"></i> ' . esc_html__( 'Importing...', 'mainwp' ); ?>
        </div>
        <?php
        $errors = array();
        //phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized,WordPress.Security.NonceVerification.Recommended
        if ( isset( $_FILES['mainwp_managesites_file_bulkupload']['error'] ) && UPLOAD_ERR_OK === $_FILES['mainwp_managesites_file_bulkupload']['error'] && check_admin_referer( 'mainwp-admin-nonce' ) ) {
            if ( isset( $_FILES['mainwp_managesites_file_bulkupload']['tmp_name'] ) && is_uploaded_file( $_FILES['mainwp_managesites_file_bulkupload']['tmp_name'] ) ) {
                $tmp_path = isset( $_FILES['mainwp_managesites_file_bulkupload']['tmp_name'] ) ? sanitize_text_field( wp_unslash( $_FILES['mainwp_managesites_file_bulkupload']['tmp_name'] ) ) : ''; //phpcs:ignore WordPress.Security.NonceVerification
                MainWP_System_Utility::get_wp_file_system();
                //phpcs:enable
                /**
                 * WordPress files system object.
                 *
                 * @global object
                 */
                global $wp_filesystem;

                $content = $wp_filesystem->get_contents( $tmp_path );

                // to compatible with EOL on OSs.
                $content = str_replace( "\r\n", "\r", $content );
                $content = str_replace( "\n", "\r", $content );
                $lines   = explode( "\r", $content );

                $default_values = array(
                    'name'               => '',
                    'url'                => '',
                    'adminname'          => '',
                    'adminpwd'           => '',
                    'wpgroups'           => '',
                    'uniqueId'           => '',
                    'http_user'          => '',
                    'http_pass'          => '',
                    'verify_certificate' => 1,
                    'ssl_version'        => 'auto',
                );

                if ( is_array( $lines ) && ( ! empty( $lines ) ) ) {
                    $row         = 0;
                    $header_line = null;

                    foreach ( $lines as $originalLine ) {

                        $line = trim( $originalLine );

                        if ( MainWP_Utility::starts_with( $line, '#' ) ) {
                            continue;
                        }

                        $items = str_getcsv( $line, ',' );

                        if ( ( null === $header_line ) && ! empty( $_POST['mainwp_managesites_chk_header_first'] ) ) {
                            $header_line = sanitize_text_field( $line ) . "\r";
                            continue;
                        }

                        if ( 3 > count( $items ) ) {
                            continue;
                        }

                        $x = 0;
                        foreach ( $default_values as $field => $val ) {
                            $value = isset( $items[ $x ] ) ? $items[ $x ] : $val;

                            if ( 'verify_certificate' === $field ) {
                                if ( 'T' === $value ) {
                                    $value = '1';
                                } elseif ( 'Y' === $value ) {
                                    $value = '0';
                                }
                            }

                            $import_data[ $field ] = sanitize_text_field( wp_unslash( $value ) );
                            ++$x;
                        }
                        $encoded = wp_json_encode( $import_data );
                        ?>
                        <input type="hidden" id="mainwp_managesites_import_csv_line_<?php echo esc_attr( $row + 1 ); ?>" value="" encoded-data="<?php echo esc_attr( $encoded ); ?>" original="<?php echo esc_attr( sanitize_text_field( $originalLine ) ); ?>" />
                        <?php
                        ++$row;
                    }
                    $header_line = trim( $header_line );
                    ?>
                    <input type="hidden" id="mainwp_managesites_do_import" value="1"/>
                    <input type="hidden" id="mainwp_managesites_total_import" value="<?php echo esc_attr( $row ); ?>"/>
                    <div class="mainwp_managesites_import_listing" id="mainwp_managesites_import_logging">
                        <span class="log ui medium text"><?php echo esc_html( $header_line ) . '<br/>'; ?></span>
                    </div>
                    <div class="mainwp_managesites_import_listing" id="mainwp_managesites_import_fail_logging" style="display: none;">
                    <?php
                        echo esc_html( $header_line );
                    ?>
                    </div>

                    <?php
                } else {
                    $errors[] = esc_html__( 'Invalid data. Please, review the import file.', 'mainwp' ) . '<br />';
                }
            } else {
                $errors[] = esc_html__( 'Upload failed. Please, try again.', 'mainwp' ) . '<br />';
            }
        } elseif ( ! empty( $_POST['mainwp_managesites_import'] ) && check_admin_referer( 'mainwp-admin-nonce' ) ) {
            // Set site data by POST value.
            $sites_data = ! empty( $_POST['mainwp_managesites_import'] ) ? wp_unslash( $_POST['mainwp_managesites_import'] ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
            if ( ! empty( $sites_data ) ) {
                $import_data = array(); // Create default import data.
                // Map data sites data to import_data.
                foreach ( $sites_data as $site ) {
                    // Break site if site_url and admin_name empty.
                    if ( empty( $site['site_url'] ) && empty( $site['admin_name'] ) ) {
                        continue;
                    }
                    // Map POST data to import data.
                    $import_data[] = array(
                        'name'               => ! empty( $site['site_name'] ) ? sanitize_text_field( wp_unslash( $site['site_name'] ) ) : '',
                        'url'                => ! empty( $site['site_url'] ) ? sanitize_text_field( wp_unslash( $site['site_url'] ) ) : '',
                        'adminname'          => ! empty( $site['admin_name'] ) ? sanitize_text_field( wp_unslash( $site['admin_name'] ) ) : '',
                        'adminpwd'           => ! empty( $site['admin_password'] ) ? wp_unslash( $site['admin_password'] ) : '',
                        'wpgroups'           => ! empty( $site['tag'] ) ? sanitize_text_field( wp_unslash( $site['tag'] ) ) : '',
                        'uniqueId'           => ! empty( $site['security_id'] ) ? sanitize_text_field( wp_unslash( $site['security_id'] ) ) : '',
                        'http_user'          => ! empty( $site['http_username'] ) ? sanitize_text_field( wp_unslash( $site['http_username'] ) ) : '',
                        'http_pass'          => ! empty( $site['http_password'] ) ? wp_unslash( $site['http_password'] ) : '',
                        'verify_certificate' => isset( $site['verify_certificate'] ) ? intval( $site['verify_certificate'] ) : 1,
                        'ssl_version'        => ! empty( $site['ssl_version'] ) ? sanitize_text_field( wp_unslash( $site['ssl_version'] ) ) : 'auto',
                    );

                }
                // Import website if import data is not empty.
                if ( ! empty( $import_data ) ) {
                    $header_line = trim( 'Site Name, Url, Admin Name, Tag,Security ID,HTTP Username,HTTP Password,Verify Certificate,SSL Version' ); // Set Header Line.
                    // Map import data to input html.
                    foreach ( $import_data as $key_import => $val_import ) {
                        $line = trim( implode( ',', $val_import ) )
                        ?>
                        <input type="hidden" id="mainwp_managesites_import_csv_line_<?php echo esc_attr( $key_import + 1 ); ?>" value="" encoded-data="<?php echo esc_attr( wp_json_encode( $val_import ) ); ?>" original="<?php echo esc_attr( $line ); ?>" />
                        <?php
                    }
                    $hd_id1       = 'mainwp_managesites_do_import';
                    $hd_id2       = 'mainwp_managesites_total_import';
                    $list_id      = 'mainwp_managesites_import_logging';
                    $fail_list_id = 'mainwp_managesites_import_fail_logging';
                    ?>
                    <input type="hidden" id="mainwp_managesites_do_managesites_import" value="1"/>
                    <input type="hidden" id="<?php echo esc_attr( $hd_id1 ); ?>" value="1"/>
                    <input type="hidden" id="<?php echo esc_attr( $hd_id2 ); ?>" value="<?php echo esc_attr( count( $import_data ) ); ?>"/>

                    <div class="mainwp_managesites_import_listing" id="<?php echo esc_attr( $list_id ); ?>">
                        <span class="log ui small text">
                            <?php echo esc_html( $header_line ) . '<br/>'; ?>
                        </span>
                    </div>
                    <div class="mainwp_managesites_import_listing" id="<?php echo esc_attr( $fail_list_id ); ?>" style="display: none;">
                        <?php echo esc_html( $header_line ); ?>
                    </div>
                    <?php
                } else {
                    $errors[] = esc_html__( 'An error occurred. Please, try again.', 'mainwp' ) . '<br />';
                }
            } else {
                $errors[] = esc_html__( 'Import failed. Please, try again.', 'mainwp' ) . '<br />';
            }
        } else {
            $errors[] = esc_html__( 'Import failed. Please, try again.', 'mainwp' ) . '<br />';
        }

        if ( ! empty( $errors ) ) {
            ?>
            <div class="error below-h2">
                <?php
                foreach ( $errors as $error ) {
                    ?>
                    <p><strong><?php esc_html_e( 'Error', 'mainwp' ); ?></strong>: <?php echo esc_html( $error ); ?></p>
                <?php } ?>
            </div>
            <?php
        }
    }

    /**
     * Method render_sync_exts_settings()
     *
     * Render sync extension settings.
     *
     * @uses \MainWP\Dashboard\MainWP_Extensions_View::get_available_extensions()
     * @uses \MainWP\Dashboard\MainWP_Extensions_Handler::get_indexed_extensions_infor()
     */
    public static function render_sync_exts_settings() { // phpcs:ignore -- NOSONAR - complex.
        $sync_extensions_options = apply_filters_deprecated( 'mainwp-sync-extensions-options', array( array() ), '4.0.7.2', 'mainwp_sync_extensions_options' );  // @deprecated Use 'mainwp_sync_extensions_options' instead. NOSONAR - not IP.
        $sync_extensions_options = apply_filters( 'mainwp_sync_extensions_options', $sync_extensions_options );

        $working_extensions = MainWP_Extensions_Handler::get_indexed_extensions_infor();
        if ( ! empty( $working_extensions ) && ! empty( $sync_extensions_options ) ) {
            ?>

            <h3 class="ui dividing header">
                <?php esc_html_e( 'Add-ons Settings Synchronization', 'mainwp' ); ?>
                <div class="sub header"><?php esc_html_e( 'Select the plugins you want to install and if you want to apply the Add-ons default settings to this Child site.', 'mainwp' ); ?></div>
            </h3>

            <?php
            $loader = '<i class="ui active inline loader tiny" style="display: none"></i> <span class="status"></span>';
            foreach ( $working_extensions as $slug => $data ) {
                $dir_slug = dirname( $slug );

                if ( ! isset( $sync_extensions_options[ $dir_slug ] ) ) {
                    continue;
                }

                $sync_info = isset( $sync_extensions_options[ $dir_slug ] ) ? $sync_extensions_options[ $dir_slug ] : array();
                $ext_name  = MainWP_Extensions_Handler::polish_string_name( $data['name'] );
                $ext_name  = esc_html( $ext_name );

                $html  = '<div class="ui grid field">';
                $html .= '<div class="sync-ext-row" slug="' . $dir_slug . '" ext_name = "' . esc_attr( $ext_name ) . '"status="queue">';
                $html .= '<h4>' . $ext_name . '</h4>';
                if ( isset( $sync_info['plugin_slug'] ) && ! empty( $sync_info['plugin_slug'] ) ) {
                    $html .= '<div class="sync-install-plugin" slug="' . esc_attr( dirname( $sync_info['plugin_slug'] ) ) . '" plugin_name="' . esc_attr( $sync_info['plugin_name'] ) . '">';
                    /* translators: 1: Plugin name. */
                    $html .= '<div class="ui checkbox"><input type="checkbox" class="chk-sync-install-plugin" /> <label>' . esc_html( sprintf( esc_html__( 'Install %1$s plugin', 'mainwp' ), esc_html( $sync_info['plugin_name'] ) ) ) . '</label></div> ';
                    $html .= $loader;
                    $html .= '</div>';
                    if ( ! isset( $sync_info['no_setting'] ) || empty( $sync_info['no_setting'] ) ) {
                        $html .= '<div class="sync-options options-row">';
                        $html .= '<div class="ui checkbox"><input type="checkbox" /><label> ';
                        /* translators: 1: Plugin name, 2: Opening anchor tag, 3: Closing anchor tag. */
                        $html .= sprintf( esc_html__( 'Apply %1$s %2$ssettings%3$s', 'mainwp' ), esc_html( $sync_info['plugin_name'] ), '<a href="admin.php?page=' . $data['page'] . '">', '</a>' );
                        $html .= '</label>';
                        $html .= '</div> ';
                        $html .= $loader;
                        $html .= '</div>';
                    }
                    if ( ! empty( $sync_info['action_after_install'] ) ) {
                        $html .= '<div class="sync-options options-row">';
                        $html .= '<div class="ui checkbox"><input type="checkbox" /><label> ';
                        $html .= esc_html( $sync_info['action_after_install'] );
                        $html .= '</label>';
                        $html .= '</div> ';
                        $html .= $loader;
                        $html .= '</div>';
                    }
                } else {
                    $html .= '<div class="sync-global-options options-row">';
                    /* translators: 1: Extension name. */
                    $html .= '<div class="ui checkbox"><input type="checkbox" /> <label>' . esc_html( sprintf( esc_html__( 'Apply global %1$s options', 'mainwp' ), trim( $ext_name ) ) ) . '</label></div> ';
                    $html .= '<i class="ui active inline loader tiny"  style="display: none"></i> <span class="status"></span>';
                    $html .= '</div>';
                }
                $html .= '</div>';
                $html .= '</div>';

                echo $html; // phpcs:ignore WordPress.Security.EscapeOutput
            }
        }
    }

    /**
     * Method render_dashboard()
     *
     * Render individual Child Site Operations page.
     *
     * @param mixed $website Child Site.
     *
     * @return string Sites Operations Page.
     *
     * @uses \MainWP\Dashboard\MainWP_Overview::render_dashboard_body()
     */
    public static function render_dashboard( &$website ) {
        if ( ! \mainwp_current_user_can( 'dashboard', 'access_individual_dashboard' ) ) {
            \mainwp_do_not_have_permissions( esc_html__( 'individual dashboard', 'mainwp' ) );
            return;
        }
        ?>
        <div>
            <?php
            if ( -1 === (int) $website->mainwpdir ) {
                echo '<div class="ui yellow message"><span class="mainwp_conflict" siteid="' . intval( $website->id ) . '"><strong>Configuration issue detected</strong>: MainWP has no write privileges to the uploads directory. Because of this some of the functionality might not work.</span></div>';
            }

            /**
             * Screen layout columns global.
             *
             * @global string
             */
            global $screen_layout_columns;

            MainWP_Overview::render_dashboard_body( array( $website ) );
            ?>
        </div>
        <?php
    }

    /**
     * Method render_header_tabs()
     *
     * Render Sites sub page header tabs.
     *
     * @param mixed $active_tab Currently active tab.
     * @param mixed $active_text Currently active drop down text.
     * @param mixed $show_language_updates Whether or not to show translations.
     */
    public static function render_header_tabs( $active_tab, $active_text, $show_language_updates ) {
        ?>
        <div class="mainwp-actions-bar">
            <div class="ui grid">
                <div class="equal width row">
                    <div class="middle aligned column">
                        <div class="inline field">
                            <div class="ui selection mini dropdown select-individual-updates">
                                <div class="text"><?php echo esc_html( $active_text ); ?></div>
                                <i class="dropdown icon"></i>
                                <div class="menu">
                                    <div class="<?php echo 'wordpress' === $active_tab ? 'active' : ''; ?> item" data-tab="wordpress" data-value="wordpress"><?php esc_html_e( 'WordPress Updates', 'mainwp' ); ?></div>
                                    <div class="<?php echo 'plugins' === $active_tab ? 'active' : ''; ?> item" data-tab="plugins" data-value="plugins"><?php esc_html_e( 'Plugin Updates', 'mainwp' ); ?></div>
                                    <div class="<?php echo 'themes' === $active_tab ? 'active' : ''; ?> item" data-tab="themes" data-value="themes"><?php esc_html_e( 'Theme Updates', 'mainwp' ); ?></div>
                                    <?php if ( $show_language_updates ) { ?>
                                    <div class="<?php echo 'trans' === $active_tab ? 'active' : ''; ?> item" data-tab="translations" data-value="translations"><?php esc_html_e( 'Translation Updates', 'mainwp' ); ?></div>
                                    <?php } ?>
                                    <?php if ( is_plugin_active( 'mainwp-database-updater-extension/mainwp-database-updater-extension.php' ) ) { ?>
                                        <div class="item" data-tab="dbupdates" data-value="dbupdates"><?php esc_html_e( 'Database Updates', 'mainwp' ); ?></div>
                                    <?php } ?>
                                    <div class="<?php echo 'abandoned-plugins' === $active_tab ? 'active' : ''; ?> item" data-tab="abandoned-plugins" data-value="abandoned-plugins"><?php esc_html_e( 'Abandoned Plugins', 'mainwp' ); ?></div>
                                    <div class="<?php echo 'abandoned-themes' === $active_tab ? 'active' : ''; ?> item" data-tab="abandoned-themes" data-value="abandoned-themes"><?php esc_html_e( 'Abandoned Themes', 'mainwp' ); ?></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="middle aligned column">
                    <?php
                    /**
                     * Action: mainwp_widget_updates_actions_top
                     *
                     * Updates actions top content.
                     *
                     * @since 5.5
                     */
                    do_action( 'mainwp_widget_updates_actions_top', $active_tab );
                    ?>
                    </div>
                    <div class="middle aligned right aligned column select-buttons-individual-updates">
                        <?php echo '<a href="javascript:void(0)" data-tooltip="' . esc_html__( 'Update Selected Plugins.', 'mainwp' ) . '" onClick="updatesoverview_plugins_global_upgrade_all( false, true ); return false;" class="ui mini green basic button plugins ' . ( 'plugins' === $active_tab ? '' : 'hidden' ) . '" data-inverted="" data-position="top right">' . esc_html__( 'Update Selected', 'mainwp' ) . '</a>'; ?>
                        <?php echo '<a href="javascript:void(0)" onClick="updatesoverview_themes_global_upgrade_all( false, true );return false;" class="ui mini green basic button themes ' . ( 'themes' === $active_tab ? '' : 'hidden' ) . '" data-tooltip="' . esc_html__( 'Update Selected Themes.', 'mainwp' ) . '" data-inverted="" data-position="top right">' . esc_html__( 'Update Selected', 'mainwp' ) . '</a>'; ?>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Method render_scan_site()
     *
     * Render Site Hardening sub page.
     *
     * @param mixed $website Child Site.
     *
     * @uses \MainWP\Dashboard\MainWP_DB::get_website_by_id()
     */
    public static function render_scan_site( &$website ) {
        if ( ! \mainwp_current_user_can( 'dashboard', 'manage_security_issues' ) ) {
            \mainwp_do_not_have_permissions( esc_html__( 'security scan', 'mainwp' ) );
            return;
        }
        ?>
        <div class="mainwp-actions-bar">
            <div class="ui one column grid">
                <div class="column">
                    <input type="button" id="securityIssues_refresh" class="ui mini green button" value="<?php esc_html_e( 'Scan Site', 'mainwp' ); ?>"/>
                </div>
            </div>
        </div>
        <div class="ui padded segment">
            <?php if ( MainWP_Utility::show_mainwp_message( 'notice', 'mainwp-manage-security-info-message' ) ) { ?>
                <div class="ui info message">
                    <i class="close icon mainwp-notice-dismiss" notice-id="mainwp-manage-security-info-message"></i>
                    <?php esc_html_e( 'Ensure your sites are secure and up to date with automated security and update checks.', 'mainwp' ); // NOSONAR - noopener - open safe. ?>
                </div>
            <?php } ?>
            <?php
            // Render security check issues.
            //phpcs:disable WordPress.Security.NonceVerification.Recommended,WordPress.Security.NonceVerification,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
            $websiteid = isset( $_GET['scanid'] ) ? intval( $_GET['scanid'] ) : null;
            //phpcs:enable WordPress.Security.NonceVerification.Recommended,WordPress.Security.NonceVerification,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

            $website = MainWP_DB::instance()->get_website_by_id( $websiteid );
            if ( empty( $website ) ) {
                return;
            }
            if ( \mainwp_current_user_can( 'dashboard', 'manage_security_issues' ) ) {
                do_action_deprecated( 'mainwp-securityissues-sites', array( $website ), '4.0.7.2', 'mainwp_securityissues_sites' ); // @deprecated Use 'mainwp_securityissues_sites' instead. NOSONAR - not IP.

                /**
                 * Action: mainwp_securityissues_sites
                 *
                 * Fires on a child site Hardening page at top.
                 *
                 * @hooked MainWP basic hardening features.
                 *
                 * @param object $website Object containing child site info.
                 *
                 * @since Unknown
                 */
                do_action( 'mainwp_securityissues_sites', $website );
            }
            ?>

            <?php
            // Hook in MainWP Sucuri Extension.
            if ( \mainwp_current_user_can( 'extension', 'mainwp-sucuri-extension' ) && is_plugin_active( 'mainwp-sucuri-extension/mainwp-sucuri-extension.php' ) ) {
                do_action_deprecated( 'mainwp-sucuriscan-sites', array( $website ), '4.0.7.2', 'mainwp_sucuriscan_sites' ); // @deprecated Use 'mainwp_sucuriscan_sites' instead. NOSONAR - not IP.

                /**
                 * Action: mainwp_sucuriscan_sites
                 *
                 * Fires on a child site Hardening page.
                 *
                 * @hooked MainWP Sucuri Extension data.
                 *
                 * @param object $website Object containing child site info.
                 *
                 * @since Unknown
                 */
                do_action( 'mainwp_sucuriscan_sites', $website );
            }
            ?>

            <?php
            // Hook in MainWP Wordfence Extension.
            if ( \mainwp_current_user_can( 'extension', 'mainwp-wordfence-extension' ) && is_plugin_active( 'mainwp-wordfence-extension/mainwp-wordfence-extension.php' ) ) {
                do_action_deprecated( 'mainwp-wordfence-sites', array( $website ), '4.0.7.2', 'mainwp_wordfence_sites' ); // @deprecated Use 'mainwp_wordfence_sites' instead. NOSONAR - not IP.

                /**
                 * Action: mainwp_wordfence_sites
                 *
                 * Fires on a child site Hardening page.
                 *
                 * @hooked MainWP Wordfence Extension data.
                 *
                 * @param object $website Object containing child site info.
                 *
                 * @since Unknown
                 */
                do_action( 'mainwp_wordfence_sites', $website );
            }
            ?>
        </div>

        <?php
    }

    /**
     * Method render_edit_site()
     *
     * Render individual Child Site Edit sub page.
     *
     * @param mixed $websiteid Child Site ID.
     * @param mixed $updated Site settings updated check.
     *
     * @return string Edit Child Site sub page.
     *
     * @uses \MainWP\Dashboard\MainWP_DB_Common::get_groups_for_current_user()
     * @uses \MainWP\Dashboard\MainWP_DB_Common::get_groups_by_website_id()
     * @uses \MainWP\Dashboard\MainWP_DB::get_website_by_id()
     * @uses \MainWP\Dashboard\MainWP_System_Utility::can_edit_website()
     * @uses  \MainWP\Dashboard\MainWP_Utility::starts_with()
     * @uses  \MainWP\Dashboard\MainWP_Utility::remove_http_prefix()
     */
    public static function render_edit_site( $websiteid, $updated ) { // phpcs:ignore -- NOSONAR - complex.
        if ( ! \mainwp_current_user_can( 'dashboard', 'edit_sites' ) ) {
            \mainwp_do_not_have_permissions( esc_html__( 'edit sites', 'mainwp' ) );
            return;
        }

        $website = MainWP_DB::instance()->get_website_by_id( $websiteid, false, array( 'monitoring_notification_emails', 'settings_notification_emails', 'ignored_trans_updates' ) );
        if ( ! MainWP_System_Utility::can_edit_website( $website ) ) {
            $website = null;
        }

        if ( empty( $website ) ) {
            return;
        }

        $groups = MainWP_DB_Common::instance()->get_groups_for_current_user();

        if ( ! is_array( $groups ) ) {
            $groups = array();
        }

        $website_url = MainWP_Utility::remove_http_www_prefix( $website->url, true );

        $text_use_global = esc_html__( 'Use global setting', 'mainwp' );
        $style_checked   = 'checked="true"';
        ?>
        <div class="ui padded segment mainwp-edit-site-<?php echo intval( $website->id ); ?>" id="mainwp-edit-site">
            <?php if ( MainWP_Utility::show_mainwp_message( 'notice', 'mainwp-edit-site-info-message' ) ) { ?>
                <div class="ui info message">
                    <i class="close icon mainwp-notice-dismiss" notice-id="mainwp-edit-site-info-message"></i>
                    <?php /* translators: 1: Site name, 2: Site URL with anchor tag, 3: Opening anchor tag for documentation link, 4: Closing anchor tag. */ printf( esc_html__( 'Edit the %1$s (%2$s) child site settings.  For additional help, please check this %3$shelp documentation%4$s.', 'mainwp' ), esc_html( stripslashes( $website->name ) ), '<a href="' . esc_url( $website->url ) . '" target="_blank">' . esc_url( $website->url ) . '</a>', '<a href="https://docs.mainwp.com/sites/management/manage-child-sites#edit-child-site-settings" target="_blank">', '</a> <i class="external alternate icon"></i>' ); // phpcs:ignore WordPress.Security.EscapeOutput -- NOSONAR - noopener - open safe. ?>
                </div>
            <?php } ?>
            <?php
            MainWP_Client_Handler::show_notice_existed_contact_emails();
            ?>
            <div id="mainwp-message-zone" class="ui message" style="display:none;"></div>
            <?php if ( $updated ) { ?>
            <div class="ui message green"><i class="close icon"></i> <?php esc_html_e( 'Child site settings saved successfully.', 'mainwp' ); ?></div>
            <?php } ?>
            <form method="POST" action="" id="mainwp-edit-single-site-form" enctype="multipart/form-data" class="ui form">
                <?php MainWP_UI::generate_wp_nonce( 'mainwp-admin-nonce' ); ?>
                <input type="hidden" name="wp_nonce" value="<?php echo esc_attr( wp_create_nonce( 'UpdateWebsite' . $website->id ) ); ?>" />

                <div class="ui basic accordion mainwp-blank-accordion mainwp-sidebar-accordion" id="mainwp-edit-site-general-settings-accordion">
                    <h2 class="ui dividing header active title">
                        <i class="right dropdown icon"></i>
                        <?php MainWP_Settings_Indicator::render_indicator( 'header', 'settings-field-indicator-edit-site-general' ); ?>
                        <?php esc_html_e( 'General Settings', 'mainwp' ); ?>
                        <div class="sub header"><?php esc_html_e( 'Basic site details, organization, and update behavior.', 'mainwp' ); ?></div>
                    </h2>
                    <div class="content active">
                <h4 class="ui dividing tiny header"><?php esc_html_e( 'Site Identity', 'mainwp' ); ?></h4>
                <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-general" default-indi-value="">
                    <label class="six wide column middle aligned">
                    <?php
                    MainWP_Settings_Indicator::render_not_default_indicator( 'none_preset_value', $website->url );
                    ?>
                    <?php esc_html_e( 'Site URL', 'mainwp' ); ?> <span class="ui small red text">(<?php esc_html_e( 'Required', 'mainwp' ); ?>)</span></label>
                    <div class="ui six wide column">
                        <div class="ui left action input">
                            <select class="ui compact selection dropdown" id="mainwp_managesites_edit_siteurl_protocol" name="mainwp_managesites_edit_siteurl_protocol">
                                <option <?php echo MainWP_Utility::starts_with( $website->url, 'http:' ) ? 'selected' : ''; ?> value="http">http://</option>
                                <option <?php echo MainWP_Utility::starts_with( $website->url, 'https:' ) ? 'selected' : ''; ?> value="https">https://</option>
                            </select>
                            <div class="ui compact selection dropdown" id="mainwp-edit-site-edit-url-www">
                                <input type="hidden" name="mainwp_managesites_edit_wpurl_with_www" value="<?php echo false !== stripos( $website->url, '/www.' ) ? 'www' : 'none-www'; ?>">
                                <i class="dropdown icon"></i>
                                <div class="default text"><?php esc_html_e( 'www', 'mainwp' ); ?></div>
                                <div class="menu">
                                    <div class="item" data-value="www"><?php esc_html_e( 'www', 'mainwp' ); ?></div>
                                    <div class="item" data-value="none-www"><del><?php esc_html_e( 'www', 'mainwp' ); ?></del></div>
                                </div>
                            </div>
                            <input type="text" id="mainwp_managesites_edit_siteurl" class="settings-field-value-change-handler" disabled="disabled" name="mainwp_managesites_edit_siteurl" value="<?php echo esc_html( $website_url ); ?>" />
                        </div>
                    </div>
                    <div class="ui four wide middle aligned column">
                        <input type="button" name="mainwp_managesites_edit_test" id="mainwp_managesites_edit_test" class="ui button basic green" value="<?php esc_attr_e( 'Test Connection', 'mainwp' ); ?>"/>
                    </div>
                </div>
                <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-general">
                    <label class="six wide column middle aligned">
                    <?php
                    MainWP_Settings_Indicator::render_not_default_indicator( 'none_preset_value', $website->name );
                    ?>
                    <?php esc_html_e( 'Site title', 'mainwp' ); ?></label>
                    <div class="ui six wide column">
                        <div class="ui left labeled input">
                            <input type="text" class="settings-field-value-change-handler" id="mainwp_managesites_edit_sitename" name="mainwp_managesites_edit_sitename" value="<?php echo esc_attr( stripslashes( $website->name ) ); ?>" />
                        </div>
                    </div>
                </div>
                <?php
                $adminname = $website->adminname;
                ?>
                <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-general">
                    <label class="six wide column middle aligned">
                    <?php
                    MainWP_Settings_Indicator::render_not_default_indicator( 'none_preset_value', $adminname );
                    ?>
                    <?php esc_html_e( 'Administrator username', 'mainwp' ); ?> <span class="ui small red text">(<?php esc_html_e( 'Required', 'mainwp' ); ?>)</span></label>
                    <div class="ui six wide column">
                        <div class="ui left labeled input">
                            <input type="text" id="mainwp_managesites_edit_siteadmin" class="settings-field-value-change-handler" name="mainwp_managesites_edit_siteadmin" value="<?php echo esc_attr( $adminname ); ?>" />
                        </div>
                    </div>
                </div>
                <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-general">
                    <label class="six wide column middle aligned">
                    <?php
                    MainWP_Settings_Indicator::render_not_default_indicator( 'none_preset_value', $website->uniqueId );
                    ?>

                    <?php esc_html_e( 'Unique security ID', 'mainwp' ); ?></label>
                    <div class="ui six wide column" data-tooltip="<?php esc_attr_e( 'If in use, enter the website Unique ID.', 'mainwp' ); ?>" data-inverted="" data-position="right center">
                        <div class="ui left labeled input">
                            <input type="text" id="mainwp_managesites_edit_uniqueId" class="settings-field-value-change-handler" name="mainwp_managesites_edit_uniqueId" value="<?php echo esc_attr( $website->uniqueId ); ?>" />
                        </div>
                    </div>
                </div>

                <h4 class="ui dividing tiny header"><?php esc_html_e( 'Organization', 'mainwp' ); ?></h4>

                <?php
                $uploaded_site_icon  = MainWP_Manage_Sites::get_instance()->get_cust_site_icon( $website->cust_site_icon_info, 'uploaded' );
                $selected_site_icon  = MainWP_Manage_Sites::get_instance()->get_cust_site_icon( $website->cust_site_icon_info, 'selected' );
                $selected_site_color = MainWP_Manage_Sites::get_instance()->get_cust_site_icon( $website->cust_site_icon_info, 'color' );

                $uploaded_icon_src = '';

                // default.
                if ( empty( $selected_site_color ) ) {
                    $selected_site_color = '#34424D';
                }

                if ( empty( $selected_site_icon ) ) {
                    $selected_site_icon = 'wordpress'; //phpcs:ignore -- WP icon default.
                }

                if ( ! empty( $uploaded_site_icon ) ) {
                    $dirs                = MainWP_System_Utility::get_mainwp_dir( 'site-icons', true );
                    $icon_base           = $dirs[1];
                    $cust_prod_icon_file = $uploaded_site_icon;
                    $uploaded_icon_src   = $icon_base . $cust_prod_icon_file;
                }

                $default_icons = MainWP_UI::get_default_icons();
                $delnonce      = MainWP_System_Utility::get_custom_nonce( 'site', esc_attr( $uploaded_site_icon ) );

                ?>
                <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-cost-add-edit">
                    <label class="six wide column middle aligned">
                    <?php
                    $indi_val = ! empty( $uploaded_site_icon ) ? 1 : 0;
                    MainWP_Settings_Indicator::render_not_default_indicator( 'none_preset_value', $indi_val );
                    esc_html_e( 'Upload site icon', 'mainwp' );
                    ?>
                    </label>
                    <input type="hidden" name="mainwp_managesites_edit_site_uploaded_icon_hidden" class="settings-field-value-change-handler" id="mainwp_managesites_edit_site_uploaded_icon_hidden" value="<?php echo esc_attr( $uploaded_site_icon ); ?>">
                    <div class="three wide middle aligned column" >
                        <span class="ui circular bordered image">
                            <?php if ( ! empty( $uploaded_site_icon ) ) { ?>
                                <?php echo MainWP_Manage_Sites::get_instance()->get_cust_site_icon( $website->cust_site_icon_info, 'display_edit' ); //phpcs:ignore --ok. ?>
                            <?php } else { ?>
                                <div style="display:inline-block;" id="mainw_managesites_add_edit_site_upload_custom_icon"></div> <?php // used for icon holder. ?>
                            <?php } ?>
                        </span>
                        <div class="ui basic button mainwp-managesites-edit-site-icon-customable"
                            iconItemId="<?php echo intval( $website->id ); ?>"
                            iconFileSlug="<?php echo esc_attr( $uploaded_site_icon ); ?>"
                            del-icon-nonce="<?php echo esc_attr( $delnonce ); ?>"
                            icon-src="<?php echo esc_attr( $uploaded_icon_src ); ?>">
                            <i class="image icon"></i> <?php echo ! empty( $uploaded_site_icon ) ? esc_html__( 'Change Image', 'mainwp' ) : esc_html__( 'Upload Image', 'mainwp' ); ?>
                        </div>
                    </div>
                </div>

                <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-general" default-indi-value="wordpress">
                    <label class="six wide column middle aligned">
                    <?php
                    $indi_val = 'wordpress' !== $selected_site_icon ? 1 : 0; //phpcs:ignore -- WP icon.
                    MainWP_Settings_Indicator::render_not_default_indicator( 'none_preset_value', $indi_val );
                    esc_html_e( 'Select icon', 'mainwp' );
                    ?>
                    </label>
                    <input type="hidden" name="mainwp_managesites_edit_site_selected_icon_hidden" class="settings-field-value-change-handler" id="mainwp_managesites_edit_site_selected_icon_hidden" value="<?php echo esc_attr( $selected_site_icon ); ?>">
                    <div class="six wide column" data-tooltip="<?php esc_attr_e( 'Select an icon if not using original site icon.', 'mainwp' ); ?>" data-inverted="" data-position="right center">
                        <div class="ui left action input mainwp-dropdown-color-picker-field">
                            <div class="ui five column selection search dropdown not-auto-init" id="mainwp_manage_add_edit_site_icon_select">
                                <div class="text">
                                    <span style="color:<?php echo esc_attr( $selected_site_color ); ?>" ><?php echo ! empty( $selected_site_icon ) ? '<i class="' . esc_attr( $selected_site_icon ) . ' icon"></i>' : ''; ?></span>
                                </div>
                                <i class="dropdown icon"></i>
                                <div class="menu">
                                    <?php foreach ( $default_icons as $icon ) : ?>
                                        <?php echo '<div class="item" style="color:' . esc_attr( $selected_site_color ) . '" data-value="' . esc_attr( $icon ) . '"><i class="' . esc_attr( $icon ) . ' icon"></i></div>'; ?>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <input type="color" data-tooltip="Color will update on save" data-position="top center" data-inverted="" name="mainwp_managesites_edit_site_color" class="mainwp-color-picker-input" id="mainwp_managesites_edit_site_color"  value="<?php echo esc_attr( $selected_site_color ); ?>" />
                        </div>
                    </div>
                    <div class="one wide column"></div>
                </div>

                <?php
                $groupsSite  = MainWP_DB_Common::instance()->get_groups_by_website_id( $website->id );
                $init_groups = '';
                if ( is_array( $groupsSite ) ) {
                    foreach ( $groupsSite as $gpsSite ) {
                        $init_groups .= ( isset( $groups[ $gpsSite->id ] ) && $groups[ $gpsSite->id ] ) ? ',' . $gpsSite->id : '';
                    }
                }
                $init_groups = ltrim( $init_groups, ',' );
                ?>
                <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-general">
                    <label class="six wide column middle aligned">
                    <?php
                    MainWP_Settings_Indicator::render_not_default_indicator( 'none_preset_value', $init_groups );
                    ?>
                    <?php esc_html_e( 'Tags', 'mainwp' ); ?></label>
                    <div class="ten wide column">
                        <div class="ui multiple selection dropdown" init-value="<?php echo esc_attr( $init_groups ); ?>">
                            <input name="mainwp_managesites_edit_addgroups" value="" class="settings-field-value-change-handler" type="hidden">
                            <i class="dropdown icon"></i>
                            <div class="default text"><?php echo '' === $init_groups ? esc_html__( 'No Tags added yet.', 'mainwp' ) : ''; ?></div>
                            <div class="menu">
                                <?php foreach ( $groups as $group ) { ?>
                                    <div class="item" data-value="<?php echo intval( $group->id ); ?>"><?php echo esc_html( $group->name ); ?></div>
                                <?php } ?>
                            </div>
                        </div>
                    </div>
                </div>
                <?php
                if ( \mainwp_current_user_can( 'dashboard', 'manage_clients' ) ) {
                    $clients = MainWP_DB_Client::instance()->get_wp_client_by( 'all' );
                    ?>
                <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-general">
                    <label class="six wide column middle aligned">
                    <?php
                    MainWP_Settings_Indicator::render_not_default_indicator( 'mainwp_site_client_id', (int) $website->client_id );
                    esc_html_e( 'Client', 'mainwp' );
                    ?>
                    </label>
                    <div class="ui six wide column">
                        <div class="ui search selection dropdown">
                            <input type="hidden" name="mainwp_managesites_edit_client_id" class="settings-field-value-change-handler" value="<?php echo intval( $website->client_id ); ?>">
                            <i class="dropdown icon"></i>
                            <div class="default text"><?php esc_html_e( 'Select Client', 'mainwp' ); ?></div>
                            <div class="menu">
                                <div class="item" data-value="0"><?php esc_html_e( 'No Client', 'mainwp' ); ?></div>
                                <?php
                                foreach ( $clients as $client ) {
                                    ?>
                                    <div class="item" data-value="<?php echo intval( $client->client_id ); ?>">
                                        <?php echo esc_html( $client->name ); ?>
                                    </div>
                                    <?php
                                }
                                ?>
                            </div>
                        </div>
                        <a href="javascript:void(0)" class="ui basic grey button edit-site-new-client-button"><?php esc_html_e( 'Create New Client', 'mainwp' ); ?></a>
                    </div>
                </div>
                <?php } ?>

                <h4 class="ui dividing tiny header"><?php esc_html_e( 'Update and Maintenance', 'mainwp' ); ?></h4>
                <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-general" default-indi-value="2">
                    <label class="six wide column middle aligned">
                    <?php
                    MainWP_Settings_Indicator::render_not_default_indicator( 'mainwp_site_backup_before_upgrade', (int) $website->backup_before_upgrade );
                    esc_html_e( 'Require backup before update', 'mainwp' );
                    ?>
                    </label>
                    <div class="ui six wide column">
                        <select class="ui dropdown settings-field-value-change-handler" id="mainwp_backup_before_upgrade" name="mainwp_backup_before_upgrade">
                            <option <?php echo 1 === (int) $website->backup_before_upgrade ? 'selected' : ''; ?> value="1"><?php esc_html_e( 'Yes', 'mainwp' ); ?></option>
                            <option <?php echo 0 === (int) $website->backup_before_upgrade ? 'selected' : ''; ?> value="0"><?php esc_html_e( 'No', 'mainwp' ); ?></option>
                            <option <?php echo 2 === (int) $website->backup_before_upgrade ? 'selected' : ''; ?> value="2"><?php echo $text_use_global; //phpcs:ignore --ok. ?></option>
                        </select>
                    </div>
                </div>
                <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-general">
                    <label class="six wide column middle aligned">
                    <?php
                    MainWP_Settings_Indicator::render_not_default_indicator( 'mainwp_site_automatic_update', (int) $website->automatic_update );
                    esc_html_e( 'Auto update WP Core', 'mainwp' );
                    ?>
                    </label>
                    <div class="one wide column ui toggle checkbox" data-tooltip="<?php esc_attr_e( 'Enable if you want MainWP to automatically update WP Core on this website.', 'mainwp' ); ?>" data-inverted="" data-position="right center">
                        <input type="checkbox" name="mainwp_automaticDailyUpdate" class="settings-field-value-change-handler" id="mainwp_automaticDailyUpdate" <?php echo 1 === (int) $website->automatic_update ? $style_checked : ''; //phpcs:ignore -- ok.  ?>><label for="mainwp_automaticDailyUpdate"></label>
                    </div>
                </div>
                <?php if ( \mainwp_current_user_can( 'dashboard', 'ignore_unignore_updates' ) ) { ?>
                    <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-general">
                        <label class="six wide column middle aligned">
                        <?php
                        MainWP_Settings_Indicator::render_not_default_indicator( 'mainwp_site_is_ignoreCoreUpdates', (int) $website->is_ignoreCoreUpdates );
                        esc_html_e( 'Ignore core updates', 'mainwp' );
                        ?>
                        </label>
                        <div class="one wide column ui toggle checkbox" data-tooltip="<?php esc_attr_e( 'Enable if you want to ignore WP Core updates on this website.', 'mainwp' ); ?>" data-inverted="" data-position="right center">
                            <input type="checkbox" name="mainwp_is_ignoreCoreUpdates" class="settings-field-value-change-handler" id="mainwp_is_ignoreCoreUpdates" <?php echo 1 === (int) $website->is_ignoreCoreUpdates ? $style_checked : ''; //phpcs:ignore -- ok.  ?>><label for="mainwp_is_ignoreCoreUpdates"></label>
                        </div>
                    </div>
                    <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-general">
                        <label class="six wide column middle aligned">
                        <?php
                        MainWP_Settings_Indicator::render_not_default_indicator( 'mainwp_site_is_ignorePluginUpdates', (int) $website->is_ignorePluginUpdates );
                        esc_html_e( 'Ignore plugin updates', 'mainwp' );
                        ?>
                        </label>
                        <div class="one wide column ui toggle checkbox" data-tooltip="<?php esc_attr_e( 'Enable if you want to ignore plugin updates on this website.', 'mainwp' ); ?>" data-inverted="" data-position="right center">
                            <input type="checkbox" name="mainwp_is_ignorePluginUpdates" class="settings-field-value-change-handler" id="mainwp_is_ignorePluginUpdates" <?php echo 1 === (int) $website->is_ignorePluginUpdates ? $style_checked : ''; //phpcs:ignore -- ok.  ?>><label for="mainwp_is_ignorePluginUpdates"></label>
                        </div>
                    </div>
                    <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-general">
                        <label class="six wide column middle aligned">
                        <?php
                        MainWP_Settings_Indicator::render_not_default_indicator( 'mainwp_site_is_ignoreThemeUpdates', (int) $website->is_ignoreThemeUpdates );
                        esc_html_e( 'Ignore theme updates', 'mainwp' );
                        ?>
                        </label>
                        <div class="one wide column ui toggle checkbox" data-tooltip="<?php esc_attr_e( 'Enable if you want to ignore theme updates on this website.', 'mainwp' ); ?>" data-inverted="" data-position="right center">
                            <input type="checkbox" name="mainwp_is_ignoreThemeUpdates" class="settings-field-value-change-handler" id="mainwp_is_ignoreThemeUpdates" <?php echo 1 === (int) $website->is_ignoreThemeUpdates ? $style_checked : ''; //phpcs:ignore -- ok.  ?>><label for="mainwp_is_ignoreThemeUpdates"></label>
                        </div>
                    </div>
                    <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-general">
                        <label class="six wide column middle aligned">
                        <?php
                        MainWP_Settings_Indicator::render_not_default_indicator( 'mainwp_site_is_ignore_trans_updates', (int) $website->ignored_trans_updates );
                        esc_html_e( 'Ignore translation updates', 'mainwp' );
                        ?>
                        </label>
                        <div class="one wide column ui toggle checkbox" data-tooltip="<?php esc_attr_e( 'Enable if you want to ignore translation updates on this website.', 'mainwp' ); ?>" data-inverted="" data-position="right center">
                            <input type="checkbox" name="mainwp_is_ignore_trans_updates" class="settings-field-value-change-handler" id="mainwp_is_ignore_trans_updates" <?php echo 1 === (int) $website->ignored_trans_updates ? $style_checked : ''; //phpcs:ignore -- ok.  ?>><label for="mainwp_is_ignore_trans_updates"></label>
                        </div>
                    </div>
                <?php } ?>

                <h4 class="ui dividing tiny header"><?php esc_html_e( 'Site Status', 'mainwp' ); ?></h4>
                <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-general">
                    <label class="six wide column middle aligned">
                    <?php
                    MainWP_Settings_Indicator::render_not_default_indicator( 'mainwp_site_suspended_site', (int) $website->suspended );
                    esc_html_e( 'Suspend Site', 'mainwp' );
                    ?>
                    </label>
                    <div class="one wide column ui toggle checkbox" data-tooltip="<?php esc_attr_e( 'Suspends MainWP actions for this site (updates, maintenance tasks) without disconnecting it.', 'mainwp' ); ?>" data-inverted="" data-position="right center">
                        <input type="checkbox" name="mainwp_suspended_site" class="settings-field-value-change-handler" id="mainwp_suspended_site" <?php echo 1 === (int) $website->suspended ? $style_checked : ''; //phpcs:ignore -- ok. ?>><label for="mainwp_suspended_site"></label>
                    </div>
                </div>
                <div class="ui grid field">
                    <label class="six wide column middle aligned"><?php esc_html_e( 'Connected on', 'mainwp' ); ?></label>
                    <div class="three wide column" data-tooltip="<?php esc_attr_e( 'Set the date your site was added to your MainWP Dashboard.', 'mainwp' ); ?>" data-inverted="" data-position="right center">
                        <div class="ui left labeled input">
                            <div class="ui calendar mainwp_datepicker" >
                                <div class="ui input left icon">
                                    <i class="calendar icon"></i>
                                    <input type="text" autocomplete="off" name="mainwp_managesites_edit_dt_added" placeholder="<?php esc_attr_e( 'Date', 'mainwp' ); ?>" id="mainwp_managesites_edit_dt_added" value="<?php echo ! empty( $website->added_timestamp ) ? esc_attr( date( 'Y-m-d', $website->added_timestamp ) ) : ''; // phpcs:ignore -- local time works. ?>"/>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                    </div>
                </div>

                <div class="ui basic accordion mainwp-blank-accordion mainwp-sidebar-accordion" id="mainwp-edit-site-advanced-settings-accordion">
                    <h2 class="ui dividing header title">
                        <i class="right dropdown icon"></i>
                        <?php MainWP_Settings_Indicator::render_indicator( 'header', 'settings-field-indicator-edit-site-advanced' ); ?>
                        <?php esc_html_e( 'Advanced Settings (Optional)', 'mainwp' ); ?>
                        <div class="sub header"><?php esc_html_e( 'Fine-tune behavior and control edge-case options.', 'mainwp' ); ?></div>
                    </h2>
                    <div class="content">
                <div class="ui grid field settings-field-indicator-wrapper" default-indi-value="2">
                    <label class="six wide column middle aligned">
                    <?php
                    MainWP_Settings_Indicator::render_not_default_indicator( 'mainwp_site_verify_certificate', (int) $website->verify_certificate );
                    esc_html_e( 'Verify certificate', 'mainwp' );
                    ?>
                    </label>
                    <div class="three wide column">
                        <select class="ui dropdown settings-field-value-change-handler" id="mainwp_managesites_edit_verifycertificate" name="mainwp_managesites_edit_verifycertificate">
                            <option <?php echo 1 === (int) $website->verify_certificate ? 'selected' : ''; ?> value="1"><?php esc_html_e( 'Yes', 'mainwp' ); ?></option>
                            <option <?php echo 0 === (int) $website->verify_certificate ? 'selected' : ''; ?> value="0"><?php esc_html_e( 'No', 'mainwp' ); ?></option>
                            <option <?php echo 2 === (int) $website->verify_certificate ? 'selected' : ''; ?> value="2"><?php echo $text_use_global; //phpcs:ignore --ok. ?></option>
                        </select>
                    </div>
                </div>
                <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-advanced">
                    <label class="six wide column middle aligned">
                    <?php
                    MainWP_Settings_Indicator::render_not_default_indicator( 'mainwp_site_ssl_version', (int) $website->ssl_version );
                    esc_html_e( 'SSL version', 'mainwp' );
                    ?>
                    </label>
                    <div class="three wide column" data-tooltip="<?php esc_attr_e( 'If you are not sure, select "Auto Detect".', 'mainwp' ); ?>" data-inverted="" data-position="right center">
                        <select class="ui dropdown settings-field-value-change-handler" id="mainwp_managesites_edit_ssl_version" name="mainwp_managesites_edit_ssl_version">
                            <option <?php echo 0 === (int) $website->ssl_version ? 'selected' : ''; ?> value="0"><?php esc_html_e( 'Auto detect', 'mainwp' ); ?></option>
                            <option <?php echo 6 === (int) $website->ssl_version ? 'selected' : ''; ?> value="6"><?php esc_html_e( 'TLS v1.2', 'mainwp' ); ?></option>
                            <option <?php echo 1 === (int) $website->ssl_version ? 'selected' : ''; ?> value="1"><?php esc_html_e( 'TLS v1.x', 'mainwp' ); ?></option>
                            <option <?php echo 2 === (int) $website->ssl_version ? 'selected' : ''; ?> value="2"><?php esc_html_e( 'SSL v2', 'mainwp' ); ?></option>
                            <option <?php echo 3 === (int) $website->ssl_version ? 'selected' : ''; ?> value="3"><?php esc_html_e( 'SSL v3', 'mainwp' ); ?></option>
                            <option <?php echo 4 === (int) $website->ssl_version ? 'selected' : ''; ?> value="4"><?php esc_html_e( 'TLS v1.0', 'mainwp' ); ?></option>
                            <option <?php echo 5 === (int) $website->ssl_version ? 'selected' : ''; ?> value="5"><?php esc_html_e( 'TLS v1.1', 'mainwp' ); ?></option>
                        </select>
                    </div>
                </div>
                <?php
                if ( empty( $website->verify_method ) ) {
                    $verify_conn_method = 3;
                } else {
                    $verify_conn_method = (int) $website->verify_method;
                }
                ?>
                <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-advanced" default-indi-value="1">
                    <label class="six wide column middle aligned">
                    <?php
                    MainWP_Settings_Indicator::render_not_default_indicator( 'mainwp_site_verify_method', (int) $verify_conn_method );
                    esc_html_e( 'Verify connection method', 'mainwp' );
                    ?>
                    </label>
                    <div class="three wide column" data-tooltip="<?php esc_attr_e( 'If you are not sure, select "Default".', 'mainwp' ); ?>" data-inverted="" data-position="right center">
                        <select class="ui dropdown settings-field-value-change-handler"id="mainwp_managesites_edit_verify_connection_method" name="mainwp_managesites_edit_verify_connection_method">
                            <option <?php echo 1 === (int) $verify_conn_method ? 'selected' : ''; ?> value="1"><?php esc_html_e( 'OpenSSL (default)', 'mainwp' ); ?></option>
                            <option <?php echo 2 === (int) $verify_conn_method ? 'selected' : ''; ?> value="2"><?php esc_html_e( 'PHPSECLIB (fallback)', 'mainwp' ); ?></option>
                            <option <?php echo 3 === (int) $verify_conn_method ? 'selected' : ''; ?> value="3"><?php echo $text_use_global; //phpcs:ignore --ok. ?></option>
                        </select>
                    </div>
                </div>
                <?php
                $sign_note = MainWP_Connect_Lib::get_connection_algo_settings_note();
                $sign_algs = MainWP_System_Utility::get_open_ssl_sign_algos();
                if ( empty( $website->signature_algo ) ) {
                    $site_sign_algo = 9999;
                } else {
                    $site_sign_algo = (int) $website->signature_algo;
                }
                ?>
                <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-advanced mainwp-hide-elemenent-sign-algo" default-indi-value="9999" <?php echo ( 2 === $verify_conn_method ) ? 'style="display:none;"' : ''; ?> >
                    <label class="six wide column middle aligned">
                    <?php
                    MainWP_Settings_Indicator::render_not_default_indicator( 'mainwp_site_signature_algo', (int) $site_sign_algo );
                    esc_html_e( 'OpenSSL signature algorithm', 'mainwp' );
                    ?>
                    </label>
                    <div class="three wide column" data-tooltip="<?php esc_attr_e( 'If you are not sure, select "Default".', 'mainwp' ); ?>" data-inverted="" data-position="right center">
                        <select class="ui dropdown settings-field-value-change-handler" id="mainwp_managesites_edit_openssl_alg" name="mainwp_managesites_edit_openssl_alg">
                            <?php
                            foreach ( $sign_algs as $val => $text ) {
                                ?>
                                <option <?php echo ( $val === $site_sign_algo ) ? 'selected' : ''; ?> value="<?php echo esc_attr( $val ); ?>"><?php echo esc_html( $text ); ?></option>
                                <?php
                            }
                            ?>
                            <option <?php echo ( 9999 === $site_sign_algo ) ? 'selected' : ''; ?> value="9999"><?php echo $text_use_global; //phpcs:ignore --ok. ?></option>
                        </select>
                        <div class="ui yellow message mainwp-hide-elemenent-sign-algo-note" <?php echo ( 1 === $site_sign_algo ) ? '' : 'style="display:none;"'; ?>><?php echo esc_html( $sign_note ); ?></div>
                    </div>
                </div>

                <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-advanced" default-indi-value="2">
                    <label class="six wide column middle aligned">
                    <?php
                    MainWP_Settings_Indicator::render_not_default_indicator( 'mainwp_site_force_use_ipv4', (int) $website->force_use_ipv4 );
                    esc_html_e( 'Force IPv4', 'mainwp' );
                    ?>
                    </label>
                    <div class="three wide column">
                        <select class="ui dropdown settings-field-value-change-handler" id="mainwp_managesites_edit_forceuseipv4" name="mainwp_managesites_edit_forceuseipv4">
                            <option <?php echo ( 1 === (int) $website->force_use_ipv4 ) ? 'selected' : ''; ?> value="1"><?php esc_html_e( 'Yes', 'mainwp' ); ?></option>
                            <option <?php echo ( 0 === (int) $website->force_use_ipv4 ) ? 'selected' : ''; ?> value="0"><?php esc_html_e( 'No', 'mainwp' ); ?></option>
                            <option <?php echo ( 2 === (int) $website->force_use_ipv4 ) ? 'selected' : ''; ?> value="2"><?php echo $text_use_global; //phpcs:ignore --ok. ?></option>
                        </select>
                    </div>
                </div>
                <input style="display:none" type="text" name="fakeusernameremembered"/>
                <input style="display:none" type="password" name="fakepasswordremembered"/>
                <?php
                // MWP-1548: http_user is encrypted at rest; decrypt for the
                // visible username field. The "is set" indicator and the
                // change-detection handler still need a truthy/falsy hint
                // so we expose plaintext to those calls. http_pass uses the
                // sentinel render (below) so the live password never enters
                // the DOM, regardless of what's stored.
                $http_user_plain = MainWP_Credential_Storage::decrypt_credential( $website->http_user );
                $http_pass_set   = ! empty( $website->http_pass );
                ?>
                <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-advanced">
                    <label class="six wide column middle aligned">
                    <?php
                    MainWP_Settings_Indicator::render_not_default_indicator( 'mainwp_site_http_user', $http_user_plain );
                    esc_html_e( 'HTTP Username', 'mainwp' );
                    ?>
                    </label>
                    <div class="ui six wide column" data-tooltip="<?php esc_attr_e( 'If the child site is HTTP Basic Auth protected, enter the HTTP username here.', 'mainwp' ); ?>" data-inverted="" data-position="top left">
                        <div class="ui left labeled input">
                            <input type="text" class="settings-field-value-change-handler" id="mainwp_managesites_edit_http_user" name="mainwp_managesites_edit_http_user" value="<?php echo empty( $http_user_plain ) ? '' : esc_attr( $http_user_plain ); ?>" autocomplete="off" />
                        </div>
                    </div>
                </div>
                <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-advanced">
                    <label class="six wide column middle aligned">
                    <?php
                    MainWP_Settings_Indicator::render_not_default_indicator( 'mainwp_site_http_pass', $http_pass_set ? '1' : '' );
                    esc_html_e( 'HTTP Password', 'mainwp' );
                    ?>
                    </label>
                    <div class="ui six wide column" data-tooltip="<?php esc_attr_e( 'If the child site is HTTP Basic Auth protected, enter the HTTP password here.', 'mainwp' ); ?>" data-inverted="" data-position="top left">
                        <div class="ui left labeled input">
                            <input type="password" id="mainwp_managesites_edit_http_pass" class="settings-field-value-change-handler" name="mainwp_managesites_edit_http_pass" value="<?php echo esc_attr( MainWP_Credential_Render::value_for_input( $http_pass_set ) ); ?>" autocomplete="new-password" />
                        </div>
                    </div>
                </div>
                    </div>
                </div>

                <div class="ui basic accordion mainwp-blank-accordion mainwp-sidebar-accordion" id="mainwp-edit-site-health-monitoring-accordion">
                    <h2 class="ui dividing header title">
                        <i class="right dropdown icon"></i>
                        <?php MainWP_Settings_Indicator::render_indicator( 'header', 'settings-field-indicator-edit-site-health' ); ?>
                        <?php esc_html_e( 'Sites Health Monitoring (Optional)', 'mainwp' ); ?>
                        <div class="sub header"><?php esc_html_e( 'Configure checks and alerts to stay on top of site health.', 'mainwp' ); ?></div>
                    </h2>
                    <div class="content">
                <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-health" default-indi-value="1">
                    <label class="six wide column middle aligned">
                    <?php
                    MainWP_Settings_Indicator::render_not_default_indicator( 'mainwp_site_disable_health_check', (int) $website->disable_health_check );
                    esc_html_e( 'Enable Child Site Health monitoring', 'mainwp' );
                    ?>
                    </label>
                    <div class="one wide column ui toggle checkbox mainwp-checkbox-showhide-elements" hide-parent="health-monitoring">
                        <input type="checkbox" class="settings-field-value-change-handler" name="mainwp_managesites_edit_disableSiteHealthMonitoring" id="mainwp_managesites_edit_disableSiteHealthMonitoring" <?php echo 0 === (int) $website->disable_health_check ? $style_checked : ''; //phpcs:ignore -- ok.  ?>><label for="mainwp_managesites_edit_disableSiteHealthMonitoring"></label>
                    </div>
                </div>
                <?php
                $healthThreshold = $website->health_threshold;
                $indi_val        = 0 !== (int) $healthThreshold ? 1 : 0;
                $hide_style      = 'style="display:none;"';
                ?>
                <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-health" default-indi-value="0" <?php echo 1 === (int) $website->disable_health_check ? $hide_style : ''; //phpcs:ignore -- ok.?> hide-element="health-monitoring">
                    <label class="six wide column middle aligned">
                    <?php
                    MainWP_Settings_Indicator::render_not_default_indicator( 'none_preset_value', (int) $indi_val );
                    esc_html_e( 'Site health threshold (optional)', 'mainwp' );
                    ?>
                    </label>
                    <div class="three wide column">
                        <select name="mainwp_managesites_edit_healthThreshold" id="mainwp_managesites_edit_healthThreshold" class="ui dropdown settings-field-value-change-handler">
                            <option value="80" <?php echo 80 === (int) $healthThreshold ? 'selected' : ''; ?>><?php esc_html_e( 'Should be improved', 'mainwp' ); ?></option>
                            <option value="100" <?php echo 100 === (int) $healthThreshold ? 'selected' : ''; ?>><?php esc_html_e( 'Good', 'mainwp' ); ?></option>
                            <option value="0" <?php echo 0 === (int) $healthThreshold ? 'selected' : ''; ?>><?php echo $text_use_global; //phpcs:ignore --ok. ?></option>
                        </select>
                    </div>
                </div>
                    </div>
                </div>
                <?php
                MainWP_Uptime_Monitoring_Edit::instance()->render_monitor_settings( $website->id, true );

                MainWP_Manage_Sites::render_email_settings( $website );

                MainWP_Manage_Backups::render_individual_settings( $website );

                do_action_deprecated( 'mainwp-manage-sites-edit', array( $website ), '4.0.7.2', 'mainwp_manage_sites_edit' ); // @deprecated Use 'mainwp_manage_sites_edit' instead. NOSONAR - not IP.
                do_action_deprecated( 'mainwp-extension-sites-edit', array( $website ), '4.0.7.2', 'mainwp_manage_sites_edit' ); // @deprecated Use 'mainwp_manage_sites_edit' instead. NOSONAR - not IP.

                /** This action is documented in ../pages/page-mainwp-manage-sites.php */
                do_action( 'mainwp_manage_sites_edit', $website );
                do_action( 'mainwp_extension_sites_edit_tablerow', $website );
                ?>
                <div class="ui divider"></div>
                <input type="submit" name="submit" id="submit" class="ui button green big" value="<?php esc_attr_e( 'Save Settings', 'mainwp' ); ?>"/>
                <input type="button" name="submit_remove_website" id="mainwp-managesites-remove-site" class="ui button red big floated right" value="<?php esc_attr_e( 'Remove Site', 'mainwp' ); ?>"/>
            </form>
        </div>
        <div class="ui modal" id="mainwp-test-connection-modal">
            <i class="close icon"></i>
            <div class="header"><?php esc_html_e( 'Connection Test', 'mainwp' ); ?></div>
            <div class="content">
                <div class="ui active dimmer">
                    <div class="ui text loader"><?php esc_html_e( 'Testing connection...', 'mainwp' ); ?></div>
                </div>
                <div id="mainwp-test-connection-result" class="ui segment" style="display:none">
                    <h2 class="ui center aligned icon header">
                        <i class=" icon"></i>
                        <div class="content">
                            <span></span>
                            <div class="sub header"></div>
                        </div>
                    </h2>
                </div>
            </div>
        </div>

            <script type="text/javascript">
                jQuery( document ).ready( function () {
                    // to fix issue not loaded calendar js library
                    if (jQuery('.ui.calendar').length > 0) {
                        if (mainwpParams.use_wp_datepicker == 1) {
                            jQuery('#mainwp-edit-site .ui.calendar input[type=text]').datepicker({ dateFormat: "yy-mm-dd" });
                        } else {
                            mainwp_init_ui_calendar( '#mainwp-edit-site .ui.calendar' );
                        }
                    }

                    jQuery( '#mainwp_manage_add_edit_site_icon_select' ).dropdown( {
                        onChange: function( val ) {
                            jQuery( '#mainwp_managesites_edit_site_selected_icon_hidden' ).val(val);
                            jQuery( '#mainwp_managesites_edit_site_selected_icon_hidden' ).trigger('change');
                        }
                    } );

                    jQuery(document).on('click', '.mainwp-managesites-edit-site-icon-customable', function () {
                            let iconObj = jQuery(this);
                            jQuery('#mainwp_delete_image_field').hide();
                            jQuery('#mainwp-upload-custom-icon-modal').modal('setting', 'closable', false).modal('show');
                            jQuery('#update_custom_icon_btn').removeAttr('disabled');
                            jQuery('#update_custom_icon_btn').attr('uploading-icon', 'site');
                            jQuery('#mainwp_delete_image_field').find('#mainwp_delete_image_chk').attr('iconItemId', iconObj.attr('iconItemId') ); // @see used by mainwp_upload_custom_types_icon().
                            jQuery('#mainwp_delete_image_field').find('#mainwp_delete_image_chk').attr('iconFileSlug', iconObj.attr('iconFileSlug') ); // @see used by mainwp_upload_custom_types_icon().

                            if (iconObj.attr('icon-src') != '') {
                                jQuery('#mainwp_delete_image_field').find('.ui.image').attr('src', iconObj.attr('icon-src'));
                                jQuery('#mainwp_delete_image_field').show();
                            }

                            jQuery(document).on('click', '#update_custom_icon_btn', function () {
                                    let deleteIcon = jQuery('#mainwp_delete_image_chk').is(':checked');
                                    let iconItemId = iconObj.attr('iconItemId');
                                    let iconFileSlug = iconObj.attr('iconFileSlug'); // to support delete file when iconItemId = 0.
                                    // upload/delete icon action.
                                    mainwp_upload_custom_types_icon(iconObj, 'mainwp_managesites_add_edit_site_upload_site_icon', iconItemId, iconFileSlug, deleteIcon, function(response){
                                        if (jQuery('#mainwp_managesites_edit_site_uploaded_icon_hidden').length > 0) {
                                            if (typeof response.iconfile !== undefined) {
                                                jQuery('#mainwp_managesites_edit_site_uploaded_icon_hidden').val(response.iconfile);
                                            } else {
                                                jQuery('#mainwp_managesites_edit_site_uploaded_icon_hidden').val('');
                                            }
                                            jQuery('#mainwp_managesites_edit_site_uploaded_icon_hidden').trigger('change');
                                        }
                                        let deleteIcon = jQuery('#mainwp_delete_image_chk').is(':checked'); // to delete.
                                        if(deleteIcon){
                                            jQuery('#mainw_managesites_add_edit_site_upload_custom_icon').hide();
                                        } else if (jQuery('#mainw_managesites_add_edit_site_upload_custom_icon').length > 0) {
                                            if (typeof response.iconfile !== undefined) {
                                                let icon_img = typeof response.iconimg !== undefined ? response.iconimg : '';
                                                let icon_src = typeof response.iconsrc !== undefined ? response.iconsrc : '';
                                                iconObj.attr('icon-src', icon_src);
                                                iconObj.attr('iconFileSlug', response.iconfile); // to support delete file when iconItemId = 0.
                                                iconObj.attr('del-icon-nonce', response.iconnonce);
                                                jQuery('#mainwp_delete_image_field').find('.ui.image').attr('src', icon_src);
                                                jQuery('#mainw_managesites_add_edit_site_upload_custom_icon').html(icon_img).show();
                                            }
                                        }
                                        setTimeout(function () {
                                            jQuery('#mainwp-upload-custom-icon-modal').modal('hide')
                                        }, 1000);
                                    });
                                    return false;
                            });
                        });

                } );
            </script>
        <?php
        MainWP_Client::render_add_client_modal();
        MainWP_UI::render_modal_upload_icon();
    }

    /**
     * Render single site Email notification settings.
     *
     * Credits.
     *
     * Plugin-Name: WooCommerce.
     * Plugin URI: https://woocommerce.com/.
     * Author: Automattic.
     * Author URI: https://woocommerce.com.
     * License: GPLv3 or later.
     *
     * @param object $website       Object containng the website info.
     * @param string $type          Email type.
     * @param bool   $updated_templ True if page loaded after update, false if not.
     *
     * @uses \MainWP\Dashboard\MainWP_Notification_Settings::get_notification_types()
     * @uses \MainWP\Dashboard\MainWP_Notification_Settings::get_default_emails_fields()
     * @uses \MainWP\Dashboard\MainWP_Notification_Settings::get_settings_desc()
     * @uses \MainWP\Dashboard\MainWP_Notification_Settings::render_update_template_message()
     * @uses \MainWP\Dashboard\MainWP_Notification_Template::get_template_name_by_notification_type()
     * @uses \MainWP\Dashboard\MainWP_Notification_Template::is_overrided_template()
     */
    public static function render_site_edit_email_settings( $website, $type, $updated_templ ) {
        $emails_settings = array();
        if ( ! empty( $website->settings_notification_emails ) ) {
            $emails_settings = json_decode( $website->settings_notification_emails, true );
        }
        if ( ! is_array( $emails_settings ) ) {
            $emails_settings = array();
        }

        $default = MainWP_Notification_Settings::get_default_emails_fields( $type );
        $options = isset( $emails_settings[ $type ] ) ? $emails_settings[ $type ] : array();
        $options = array_merge( $default, $options );

        $title  = MainWP_Notification_Settings::get_notification_types( $type );
        $siteid = $website->id;

        $email_description = MainWP_Notification_Settings::get_settings_desc( $type );
        $text_recipients   = esc_html__( 'Recipient(s)', 'mainwp' );
        $style_checked     = 'checked="true"';
        ?>
        <div class="ui segment">
        <?php MainWP_Notification_Settings::render_update_template_message( $updated_templ ); ?>
        <form method="POST" action="admin.php?page=managesites&id=<?php echo intval( $siteid ); ?>&emailsettingsid=<?php echo intval( $siteid ); ?>" class="ui form">
            <input type="hidden" name="wp_nonce" value="<?php echo esc_attr( wp_create_nonce( 'UpdateWebsiteEmailSettings' . $siteid ) ); ?>" />
            <input type="hidden" name="mainwp_managesites_setting_emails_type" value="<?php echo esc_html( $type ); ?>" />
            <?php if ( MainWP_Utility::show_mainwp_message( 'notice', 'mainwp-email-tokens-info-message' ) ) { ?>
                <div class="ui info message">
                    <i class="close icon mainwp-notice-dismiss" notice-id="mainwp-manage-updates-message"></i>
                    <?php echo '<a href="https://mainwp.com/extension/boilerplate/" target="_blank">Boilerplate</a> <i class="external alternate icon"></i> and <a href="https://mainwp.com/extension/pro-reports/" target="_blank">Reports</a> <i class="external alternate icon"></i> extensions tokens are supported in the email settings and templates if Extensions are in use.'; // NOSONAR - noopener - open safe. ?>
                </div>
            <?php } ?>
            <h3 class="ui header"><?php echo esc_html( $title ); ?></h3>
            <div class="sub header"><?php echo esc_html( $email_description ); ?></h3></div>
            <div class="ui divider"></div>
            <?php
            $def_val = MainWP_Settings_Indicator::get_defaults_email_settings_value( $type, 'disable', false );
            ?>
            <div class="ui grid field settings-field-indicator-wrapper" default-indi-value="<?php echo esc_attr( $def_val ); ?>">
                <label class="six wide column middle aligned">
                <?php
                MainWP_Settings_Indicator::render_not_default_email_settings_indicator( $type, 'disable', (int) $options['disable'], false );
                esc_html_e( 'Enable', 'mainwp' );
                ?>
                </label>
                <div class="six wide column ui toggle checkbox" data-tooltip="<?php esc_attr_e( 'Enable this email notification.', 'mainwp' ); ?>" data-inverted="" data-position="top left">
                    <input type="checkbox" class="settings-field-value-change-handler" inverted-value="1" name="mainwp_managesites_edit_settingEmails[<?php echo esc_html( $type ); ?>][disable]" id="mainwp_managesites_edit_settingEmails[<?php echo esc_html( $type ); ?>][disable]" <?php echo ( 0 === $options['disable'] ) ? $style_checked : ''; //phpcs:ignore -- ok.  ?>/>
                </div>
            </div>
            <?php
            $def_val = MainWP_Settings_Indicator::get_defaults_email_settings_value( $type, 'recipients', false );
            ?>
            <div class="ui grid field settings-field-indicator-wrapper" default-indi-value="<?php echo esc_attr( $def_val ); ?>">
                <label class="six wide column middle aligned">
                <?php
                MainWP_Settings_Indicator::render_not_default_email_settings_indicator( $type, 'recipients', $options['recipients'], false );
                echo $text_recipients; //phpcs:ignore -- ok.
                ?>
                </label>
                <div class="ui six wide column" data-tooltip="<?php esc_attr_e( 'You can add multiple emails by separating them with comma.', 'mainwp' ); ?>" data-inverted="" data-position="top left">
                    <input type="text" class="settings-field-value-change-handler" name="mainwp_managesites_edit_settingEmails[<?php echo esc_html( $type ); ?>][recipients]" id="mainwp_managesites_edit_settingEmails[<?php echo esc_html( $type ); ?>][recipients]" value="<?php echo esc_html( $options['recipients'] ); ?>"/>
                </div>
            </div>
            <?php
            $def_val = MainWP_Settings_Indicator::get_defaults_email_settings_value( $type, 'subject', false );
            ?>
            <div class="ui grid field settings-field-indicator-wrapper" default-indi-value="<?php echo esc_attr( $def_val ); ?>">
                <label class="six wide column middle aligned">
                <?php
                MainWP_Settings_Indicator::render_not_default_email_settings_indicator( $type, 'subject', $options['subject'], false );
                esc_html_e( 'Subject', 'mainwp' );
                ?>
                </label>
                <div class="ui six wide column" data-tooltip="<?php esc_attr_e( 'Enter the email subject.', 'mainwp' ); ?>" data-inverted="" data-position="top left">
                    <input type="text" class="settings-field-value-change-handler" name="mainwp_managesites_edit_settingEmails[<?php echo esc_html( $type ); ?>][subject]" id="mainwp_managesites_edit_settingEmails[<?php echo esc_html( $type ); ?>][subject]" value="<?php echo esc_html( $options['subject'] ); ?>"/>
                </div>
            </div>
            <?php
            $def_val = MainWP_Settings_Indicator::get_defaults_email_settings_value( $type, 'heading', false );
            ?>
            <div class="ui grid field settings-field-indicator-wrapper" default-indi-value="<?php echo esc_attr( $def_val ); ?>" >
                <label class="six wide column middle aligned">
                <?php
                MainWP_Settings_Indicator::render_not_default_email_settings_indicator( $type, 'heading', $options['heading'], false );
                esc_html_e( 'Email heading', 'mainwp' );
                ?>
                </label>
                <div class="ui six wide column" data-tooltip="<?php esc_attr_e( 'Enter the email heading.', 'mainwp' ); ?>" data-inverted="" data-position="top left">
                <input type="text" class="settings-field-value-change-handler"  name="mainwp_managesites_edit_settingEmails[<?php echo esc_html( $type ); ?>][heading]" id="mainwp_managesites_edit_settingEmails[<?php echo esc_html( $type ); ?>][heading]" value="<?php echo esc_html( $options['heading'] ); ?>"/>
                </div>
            </div>
            <div class="ui grid field settings-field-indicator-wrapper" >
                <label class="six wide column middle aligned">
                <?php
                $templ     = MainWP_Notification_Template::get_template_name_by_notification_type( $type );
                $overrided = MainWP_Notification_Template::instance()->is_overrided_template( $type );
                MainWP_Settings_Indicator::render_not_default_email_settings_indicator( $type, 'overrided', (int) $overrided, false );
                esc_html_e( 'HTML template', 'mainwp' );
                ?>
                </label>
                <div class="ui six wide column" data-tooltip="<?php esc_attr_e( 'Manage the email HTML template.', 'mainwp' ); ?>" data-inverted="" data-position="top left">
                <?php
                echo $overrided ? esc_html__( 'This template has been overridden and can be found in:', 'mainwp' ) . ' <code>wp-content/uploads/mainwp/templates/' . esc_html( $templ ) . '</code>' : esc_html__( 'To override and edit this email template copy:', 'mainwp' ) . ' <code>mainwp/templates/' . esc_html( $templ ) . '</code> ' . esc_html__( 'to the folder:', 'mainwp' ) . ' <code>wp-content/uploads/mainwp/templates/' . esc_html( $templ ) . '</code>';
                ?>
                <input type="hidden" class="settings-field-value-change-handler" value="<?php echo intval( $overrided ); ?>">
                </div>
            </div>
            <div class="ui grid field" >
                <label class="six wide column middle aligned"></label>
                <div class="ui six wide column" data-tooltip="<?php esc_attr_e( 'Manage the email HTML template.', 'mainwp' ); ?>" data-inverted="" data-position="top left">
                    <?php if ( $overrided ) { ?>
                        <a href="<?php echo esc_url( wp_nonce_url( 'admin.php?page=managesites&id=' . intval( $siteid ) . '&emailsettingsid=' . intval( $siteid ) . '&edit-email=' . esc_attr( $type ), 'delete-email-template' ) ); ?>" onclick="mainwp_confirm('<?php echo esc_js( 'Are you sure you want to delete this template file?', 'mainwp' ); ?>', function(){ window.location = jQuery('a#email-delete-template').attr('href');}); return false;" id="email-delete-template" class="ui button"><?php esc_html_e( 'Return to Default Template', 'mainwp' ); ?></a>
                        <?php
                    } else {
                        ?>
                    <a href="<?php echo esc_url( wp_nonce_url( 'admin.php?page=managesites&id=' . intval( $siteid ) . '&emailsettingsid=' . intval( $siteid ) . '&edit-email=' . esc_attr( $type ), 'copy-email-template' ) ); ?>" class="ui button"><?php esc_html_e( 'Copy file to uploads', 'mainwp' ); ?></a>
                    <?php } ?>
                    <?php if ( $overrided ) { ?>
                        <a href="javascript:void(0)" class="ui button" onclick="mainwp_view_template('<?php echo esc_js( $type ); ?>'); return false;"><?php esc_html_e( 'Edit Template', 'mainwp' ); ?></a>
                        <?php
                    } else {
                        ?>
                    <a href="javascript:void(0)" class="ui button" onclick="mainwp_view_template('<?php echo esc_js( $type ); ?>'); return false;"><?php esc_html_e( 'View Template', 'mainwp' ); ?></a>
                    <?php } ?>
                </div>
            </div>
            <div class="ui divider"></div>
            <a href="admin.php?page=managesites&id=<?php echo (int) ( $siteid ); ?>&emailsettingsid=<?php echo intval( $siteid ); ?>" class="ui big basic green button"><?php esc_html_e( 'Back', 'mainwp' ); ?></a>
            <input type="submit" name="submit" id="submit" class="ui button green big" value="<?php esc_attr_e( 'Save Settings', 'mainwp' ); ?>"/>
            </form>
        </div>
        </div>
        <?php static::render_edit_template( $type, $siteid ); ?>
        <?php
    }

    /**
     * Render the email notification edit form.
     *
     * Credits.
     *
     * Plugin-Name: WooCommerce.
     * Plugin URI: https://woocommerce.com/.
     * Author: Automattic.
     * Author URI: https://woocommerce.com.
     * License: GPLv3 or later.
     *
     * @param string $type   Email type.
     * @param bool   $siteid Child site ID.
     *
     * @uses \MainWP\Dashboard\MainWP_Notification_Template::get_template_name_by_notification_type()
     * @uses \MainWP\Dashboard\MainWP_Notification_Template::get_default_templates_dir()
     * @uses \MainWP\Dashboard\MainWP_Notification_Template::get_custom_templates_dir()
     */
    public static function render_edit_template( $type, $siteid = false ) {

        $template    = MainWP_Notification_Template::get_template_name_by_notification_type( $type );
        $default_dir = MainWP_Notification_Template::instance()->get_default_templates_dir();
        $custom_dir  = MainWP_Notification_Template::instance()->get_custom_templates_dir();

        $custom_file   = $custom_dir . $template;
        $default_file  = $default_dir . $template;
        $template_file = apply_filters( 'mainwp_default_template_locate', $default_file, $template, $default_dir, $type, $siteid );

        if ( $siteid ) {
            $localion = 'admin.php?page=managesites&id=' . (int) $siteid . '&emailsettingsid=' . $siteid . '&edit-email=' . $type;
        } else {
            $localion = 'admin.php?page=SettingsEmail&edit-email=' . $type;
        }

        $editable = false;
        ?>
            <div class="ui large modal" id="mainwp-edit-email-template-modal">
                <i class="close icon"></i>
                <div class="header"><?php esc_html_e( 'Edit Email Template', 'mainwp' ); ?></div>
                    <div class="scrolling content">
                    <form method="POST" id="email-template-form" action="<?php echo esc_html( $localion ); ?>" class="ui form">
                        <input type="hidden" name="wp_nonce" value="<?php echo esc_attr( wp_create_nonce( 'save-email-template' ) ); ?>" />
                        <div class="template <?php echo esc_attr( $type ); ?>">
                            <?php if ( file_exists( $custom_file ) ) { ?>
                                <div class="editor">
                                    <textarea class="code" cols="80" rows="20"
                                    <?php
                                    $is_writable = MainWP_System_Utility::is_writable( $custom_file );
                                    if ( ! $is_writable ) {
                                        ?>
                                        readonly="readonly" disabled="disabled"
                                        <?php
                                    } else {
                                        $editable = true;
                                        ?>
                                        name="edit_<?php echo esc_attr( $type ) . '_code'; ?>"
                                                                <?php
                                    }
                                    ?>
                                    ><?php echo esc_html( file_get_contents( $custom_file ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- required to achieven desired results. Pull requests are welcome. ?></textarea>
                                </div>
                                <?php
                            } elseif ( file_exists( $template_file ) ) {
                                ?>
                                <div class="editor">
                                    <textarea class="code" readonly="readonly" disabled="disabled" cols="25" rows="20"><?php echo esc_html( file_get_contents( $template_file ) );  // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- required to achieven desired results. Pull requests are welcome. ?></textarea>
                                </div>
                                <?php
                            } else {
                                ?>
                                <p><?php esc_html_e( 'File was not found.', 'mainwp' ); ?></p>
                            <?php } ?>
                        </div>
                    </form>
                    </div>
                    <div class="actions">
                        <?php if ( $editable ) { ?>
                        <input type="submit" form="email-template-form" class="ui green button" value="<?php esc_attr_e( 'Save Changes', 'mainwp' ); ?>"/>
                        <?php } ?>
                    </div>
                </div>
            </div>
            <script type="text/javascript">
                jQuery( document ).ready( function () {
                    mainwp_view_template = function( templ ) {
                        jQuery( "#mainwp-edit-email-template-modal" ).modal( {
                            closable: false,
                            onHide: function() {
                                location.reload( true );
                            }
                        } ).modal( 'show' );
                    }
                } );
            </script>
        <?php
    }

    /**
     * Render all email settings options.
     *
     * @param object $website Object containing the website info.
     * @param bool   $updated True if page loaded after update, false if not.
     *
     * @uses \MainWP\Dashboard\MainWP_Notification_Settings::get_notification_types()
     * @uses \MainWP\Dashboard\MainWP_Notification_Settings::get_default_emails_fields()
     * @uses \MainWP\Dashboard\MainWP_Notification_Settings::get_settings_desc()
     * @uses \MainWP\Dashboard\MainWP_System_Utility::get_notification_email()
     */
    public static function render_edit_site_email_settings( $website, $updated ) {
        $emails_settings = array();
        if ( ! empty( $website->settings_notification_emails ) ) {
            $emails_settings = json_decode( $website->settings_notification_emails, true );
        }

        if ( ! is_array( $emails_settings ) ) {
            $emails_settings = array();
        }

        $email_description   = '';
        $notification_emails = MainWP_Notification_Settings::get_notification_types();
        $text_recipients     = esc_html__( 'Recipient(s)', 'mainwp' );

        ?>

        <div class="ui basic accordion mainwp-blank-accordion mainwp-sidebar-accordion" id="mainwp-edit-site-email-settings-accordion">
            <h2 class="ui dividing header title">
                <i class="right dropdown icon"></i>
                <?php esc_html_e( 'Email Settings', 'mainwp' ); ?>
                <div class="sub header"><?php esc_html_e( 'Set up email notifications with per-site options, extra recipients, and template controls.', 'mainwp' ); ?></div>
            </h2>
            <div class="content">

        <?php if ( $updated ) { ?>
        <div class="ui message green"><i class="close icon"></i> <?php esc_html_e( 'Email settings saved successfully.', 'mainwp' ); ?></div>
        <?php } ?>
        <div class="ui info message">
            <?php esc_html_e( 'Email notifications sent from MainWP Dashboard about this child site are listed below. Click on an email to configure it.', 'mainwp' ); ?>
        </div>
            <table class="ui unstackable table" id="mainwp-emails-settings-table">
                <thead>
                    <tr>
                        <th scope="col" class="collapsing"><?php esc_html_e( 'Status', 'mainwp' ); ?></th>
                        <th scope="col" data-priority="1"><?php esc_html_e( 'Email', 'mainwp' ); ?></th>
                        <th scope="col" ><?php esc_html_e( 'Description', 'mainwp' ); ?></th>
                        <th scope="col" ><?php echo $text_recipients; //phpcs:ignore -- ok. ?></th>
                        <th scope="col" class="no-sort collapsing" data-priority="2" style="text-align:right">&nbsp;</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ( $notification_emails as $type => $name ) { ?>
                        <?php
                        $options           = isset( $emails_settings[ $type ] ) ? $emails_settings[ $type ] : array();
                        $default           = MainWP_Notification_Settings::get_default_emails_fields( $type );
                        $options           = array_merge( $default, $options );
                        $email_description = MainWP_Notification_Settings::get_settings_desc( $type );
                        ?>
                        <tr>
                            <td><?php echo ( ! $options['disable'] ) ? '<span data-tooltip="Enabled." data-position="right center" data-inverted=""><i class="circular green check inverted icon"></i></span>' : '<span data-tooltip="Disabled." data-position="right center" data-inverted=""><i class="circular x icon inverted disabled"></i></span>'; ?></td>
                            <td><a href="admin.php?page=managesites&id=<?php echo intval( $website->id ); ?>&emailsettingsid=<?php echo intval( $website->id ); ?>&edit-email=<?php echo esc_html( rawurlencode( $type ) ); ?>" data-tooltip="<?php esc_html_e( 'Click to configure the email settings.', 'mainwp' ); ?>" data-position="right center" data-inverted=""><?php echo esc_html( $name ); ?></a></td>
                            <td><?php echo esc_html( $email_description ); ?></td>
                            <td><?php echo esc_html( $options['recipients'] ); ?></td>
                            <td style="text-align:right"><a href="admin.php?page=managesites&id=<?php echo intval( $website->id ); ?>&emailsettingsid=<?php echo intval( $website->id ); ?>&edit-email=<?php echo esc_html( rawurlencode( $type ) ); ?>" data-tooltip="<?php esc_html_e( 'Click to configure the email settings.', 'mainwp' ); ?>" data-position="left center" data-inverted="" class="ui green mini button"><?php esc_html_e( 'Manage', 'mainwp' ); ?></a></td>
                        </tr>
                    <?php } ?>
                </tbody>
            </table>
            <?php
            /**
             * Action: mainwp_manage_sites_email_settings
             *
             * Fires on the Email Settigns page at bottom.
             *
             * @param object $website Object containing the website info.
             *
             * @since 4.1
             */
            do_action( 'mainwp_manage_sites_email_settings', $website );
            ?>
            <?php if ( ! empty( $website->monitoring_notification_emails ) ) : ?>
            <div class="ui grid field settings-field-indicator-wrapper settings-field-indicator-edit-site-uptime" default-indi-value=""  hide-element="monitoring">
                <label class="six wide column middle aligned">
                <?php
                MainWP_Settings_Indicator::render_not_default_indicator( 'mainwp_site_monitoring_notification_emails', $website->monitoring_notification_emails );
                esc_html_e( 'Additional notification emails (comma-separated)', 'mainwp' );
                ?>
                <span class="ui yellow small label" data-tooltip="<?php esc_attr_e( 'Deprecated. Customize recipients using the email settings above. This option will be removed in a future update.', 'mainwp' ); ?>" data-position="top left" data-inverted=""><?php esc_html_e( 'Legacy', 'mainwp' ); ?></span>
                </label>
                <div class="six wide column">
                    <div class="ui left labeled input">
                        <input type="text" class="settings-field-value-change-handler" id="mainwp_managesites_edit_monitoringNotificationEmails" name="mainwp_managesites_edit_monitoringNotificationEmails" value="<?php echo ! empty( $website->monitoring_notification_emails ) ? esc_attr( $website->monitoring_notification_emails ) : ''; ?>"/>
                    </div>
                </div>
            </div>
            <?php endif; ?>
            </div>
        </div>
            <script type="text/javascript">
            let responsive = true;
            if( jQuery( window ).width() > 1140 ) {
                responsive = false;
            }
            jQuery( document ).ready( function() {
                jQuery( '#mainwp-emails-settings-table' ).DataTable( {
                    "stateSave":  true,
                    "searching": false,
                    "paging":   false,
                    "ordering": true,
                    "columnDefs": [ { "orderable": false, "targets": [ 4 ] } ],
                    "order": [ [ 1, "asc" ] ],
                    "responsive": responsive,
                } );
            } );
            </script>
        <?php
    }

    /**
     * Method m_reconnect_site()
     *
     * Reconnect child site.
     *
     * @param object $website The website object.
     * @param bool   $sync_first True try to sync before reconnect.
     * @param array  $params others params.
     *
     * @return boolean true|false.
     * @throws \MainWP_Exception Exception On errors.
     *
     * @uses \MainWP\Dashboard\MainWP_Connect::fetch_url_authed()
     * @uses \MainWP\Dashboard\MainWP_DB::update_website_values()
     * @uses \MainWP\Dashboard\MainWP_Exception
     * @uses \MainWP\Dashboard\MainWP_Sync::sync_information_array()
     * @uses \MainWP\Dashboard\MainWP_Sync::sync_site()
     * @uses \MainWP\Dashboard\MainWP_System_Utility::get_openssl_conf()
     * @uses \MainWP\Dashboard\MainWP_System_Utility::can_edit_website()
     * @uses  \MainWP\Dashboard\MainWP_Utility::esc_content()
     */
    public static function m_reconnect_site( $website, $sync_first = true, $params = array() ) { //phpcs:ignore -- NOSONAR - complex method.
        if ( MainWP_System_Utility::can_edit_website( $website ) ) {
            $success    = false;
            $_error     = '';
            $error_code = '';
            try {
                if ( $sync_first ) {
                    $success = MainWP_Sync::sync_site( $website, true );
                    if ( ! $success && ! MainWP_Connect_Lib::is_use_fallback_sec_lib( $website ) ) { // fix sign algo in case not use phpseclib.
                        // to compatible.
                        $alg = is_object( $website ) && property_exists( $website, 'signature_algo' ) && ! empty( $website->signature_algo ) ? $website->signature_algo : false;
                        if ( empty( $alg ) && is_object( $website ) ) {
                            MainWP_DB::instance()->update_website_option( $website, 'signature_algo', 9999 ); // use global.
                            $website = MainWP_DB::instance()->get_website_by_id( $website->id );
                            if ( class_exists( __NAMESPACE__ . '\MainWP_Stack_Helper' ) ) {
                                MainWP_Stack_Helper::stack_push( 'sync_before_reconnect' );
                            }
                            $success = MainWP_Sync::sync_site( $website, true );
                        }
                    }
                }

                if ( ! $success ) {
                    if ( MainWP_Connect_Lib::is_use_fallback_sec_lib( $website ) ) {
                        $details = MainWP_Connect_Lib::instance()->create_connect_keys();
                        if ( is_array( $details ) ) {
                            $pubkey  = $details['pub'];
                            $privkey = $details['priv'];
                        } else {
                            $privkey = '-1';
                            $pubkey  = '-1';
                        }
                    } elseif ( function_exists( 'openssl_pkey_new' ) ) {
                        $conf     = array( 'private_key_bits' => 2048 );
                        $conf_loc = MainWP_System_Utility::get_openssl_conf();
                        if ( ! empty( $conf_loc ) ) {
                            $conf['config'] = $conf_loc;
                        }
                        $res = openssl_pkey_new( $conf );
                        @openssl_pkey_export( $res, $privkey, null, $conf ); // phpcs:ignore -- prevent warning.
                        $details = openssl_pkey_get_details( $res );
                        $pubkey  = $details['key'];
                    } else {
                        $privkey = '-1';
                        $pubkey  = '-1';
                    }

                    $verify_reg = MainWP_DB::instance()->get_website_option( $website, 'register_verify_key', '' );

                    $register_data = array(
                        'pubkey'    => $pubkey,
                        'server'    => get_admin_url(),
                        'uniqueId'  => $website->uniqueId,
                        'regverify' => $verify_reg,
                    );

                    $recon_user    = '';
                    $recon_userpwd = '';

                    if ( is_array( $params ) && ! empty( $params['wpadmin'] ) && ! empty( $params['adminpwd'] ) ) {
                        $recon_user    = ! empty( $params['wpadmin'] ) ? $params['wpadmin'] : '';
                        $recon_userpwd = ! empty( $params['adminpwd'] ) ? $params['adminpwd'] : '';
                    }

                    if ( ! empty( $recon_user ) && ! empty( $recon_userpwd ) ) {
                        $register_data['user']    = $recon_user;
                        $register_data['userpwd'] = $recon_userpwd;
                    }

                    // MWP-1548: decrypt at the boundary for the reconnect/register call.
                    $information = MainWP_Connect::fetch_url_not_authed(
                        $website->url,
                        $website->adminname,
                        'register',
                        $register_data,
                        true,
                        $website->verify_certificate,
                        MainWP_Credential_Storage::decrypt_credential( $website->http_user ),
                        MainWP_Credential_Storage::decrypt_credential( $website->http_pass ),
                        $website->ssl_version
                    );

                    if ( isset( $information['error'] ) && '' !== $information['error'] ) {
                        $err        = urldecode( $information['error'] );
                        $_error     = MainWP_Utility::esc_content( $err );
                        $error_code = isset( $information['error_code'] ) ? sanitize_text_field( wp_unslash( $information['error_code'] ) ) : '';
                    } elseif ( isset( $information['register'] ) && 'OK' === $information['register'] ) {

                        $en_pk_data = MainWP_Encrypt_Data_Lib::instance()->encrypt_privkey( $privkey, $website->id, true );
                        $en_privkey = isset( $en_pk_data['en_data'] ) ? $en_pk_data['en_data'] : '';

                        $site_values = array(
                            'pubkey'   => base64_encode( $pubkey ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions -- base64_encode() used for backwards compatibility.
                            'privkey'  => base64_encode( $en_privkey ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions -- base64_encode() used for backwards compatibility.
                            'uniqueId' => ( isset( $information['uniqueId'] ) ? $information['uniqueId'] : '' ),
                        );

                        if ( ! empty( $recon_user ) && ! empty( $recon_userpwd ) && ( $website->adminname !== $recon_user ) ) {
                            $site_values['adminname'] = $recon_user;
                        }

                        MainWP_DB::instance()->update_website_values(
                            $website->id,
                            $site_values
                        );

                        if ( ! empty( $information['regverify'] ) ) {
                            MainWP_DB::instance()->update_website_option( $website, 'register_verify_key', $information['regverify'] );
                        }
                        if ( class_exists( __NAMESPACE__ . '\MainWP_Stack_Helper' ) ) {
                            MainWP_Stack_Helper::stack_push( 'sync_reconnect' );
                        }
                        MainWP_Sync::sync_information_array( $website, $information );
                        $success = true;
                    } else {
                        $_error = esc_html__( 'Undefined error!', 'mainwp' );
                    }
                }
            } catch ( MainWP_Exception $e ) {
                if ( 'HTTPERROR' === $e->getMessage() ) {
                    $_error = 'HTTP error' . ( null !== $e->get_message_extra() ? ' - ' . $e->get_message_extra() : '' );
                } elseif ( 'NOMAINWP' === $e->getMessage() ) {
                    $_error = MainWP_Error_Helper::get_error_not_detected_connect(); // phpcs:ignore WordPress.Security.EscapeOutput
                }
            }

            /**
             * Fires immediately after reconnect website.
             *
             * @since 4.5.1.1
             *
             * @param object   $website  website data.
             */
            do_action( 'mainwp_site_reconnected', $website, $success, $_error );

            if ( $success ) {
                return true;
            }

            if ( ! empty( $_error ) ) {
                throw new MainWP_Exception( $_error, '', $error_code ); //phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
            }
        } else {
            throw new MainWP_Exception( esc_html__( 'This operation is not allowed!', 'mainwp' ) );
        }

        return false;
    }

    /**
     * Method add_site()
     *
     * Add Child Site.
     *
     * @param mixed $website Child Site.
     * @param array $output Output values.
     *
     * @return self add_wp_site()
     */
    public static function add_site( $website = false, &$output = array() ) { //phpcs:ignore -- NOSONAR - complexity.
        //phpcs:disable WordPress.Security.NonceVerification,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        $params['url']                = isset( $_POST['managesites_add_wpurl'] ) ? sanitize_text_field( wp_unslash( $_POST['managesites_add_wpurl'] ) ) : '';
        $params['name']               = isset( $_POST['managesites_add_wpname'] ) ? sanitize_text_field( wp_unslash( $_POST['managesites_add_wpname'] ) ) : '';
        $params['wpadmin']            = isset( $_POST['managesites_add_wpadmin'] ) ? sanitize_text_field( wp_unslash( $_POST['managesites_add_wpadmin'] ) ) : '';
        $params['adminpwd']           = isset( $_POST['managesites_add_adminpwd'] ) ?   wp_unslash( $_POST['managesites_add_adminpwd'] ) : ''; //phpcs:ignore -- NOSONAR - requires urlencoded passwd, do not sanitize for specical chars.
        $params['unique_id']          = isset( $_POST['managesites_add_uniqueId'] ) ? sanitize_text_field( wp_unslash( $_POST['managesites_add_uniqueId'] ) ) : '';
        $params['ssl_verify']         = empty( $_POST['verify_certificate'] ) ? false : intval( $_POST['verify_certificate'] );
        $params['ssl_version']        = empty( $_POST['ssl_version'] ) ? false : intval( $_POST['ssl_version'] );
        $params['force_use_ipv4']     = apply_filters( 'mainwp_manage_sites_force_use_ipv4', null, $params['url'] );
        $params['http_user']          = isset( $_POST['managesites_add_http_user'] ) ? sanitize_text_field( wp_unslash( $_POST['managesites_add_http_user'] ) ) : '';
        $params['http_pass']          = isset( $_POST['managesites_add_http_pass'] ) ? wp_unslash( $_POST['managesites_add_http_pass'] ) : '';
        $params['groupids']           = isset( $_POST['groupids'] ) && ! empty( $_POST['groupids'] ) ? explode( ',', sanitize_text_field( wp_unslash( $_POST['groupids'] ) ) ) : array();
        $params['groupnames_import']  = isset( $_POST['groupnames_import'] ) ? sanitize_text_field( wp_unslash( $_POST['groupnames_import'] ) ) : '';
        $params['clientid']           = isset( $_POST['clientid'] ) && ! empty( $_POST['clientid'] ) ? intval( $_POST['clientid'] ) : 0;
        $params['uploaded_site_icon'] = isset( $_POST['uploaded_icon'] ) && ! empty( $_POST['uploaded_icon'] ) ? sanitize_text_field( wp_unslash( $_POST['uploaded_icon'] ) ) : '';
        $params['selected_site_icon'] = isset( $_POST['selected_icon'] ) && ! empty( $_POST['selected_icon'] ) ? sanitize_text_field( wp_unslash( $_POST['selected_icon'] ) ) : '';
        $params['cust_icon_color']    = isset( $_POST['cust_color'] ) && ! empty( $_POST['cust_color'] ) ? sanitize_hex_color( wp_unslash( $_POST['cust_color'] ) ) : '';

        if ( isset( $_POST['qsw_page'] ) ) {
            $params['qsw_page'] = sanitize_text_field( wp_unslash( $_POST['qsw_page'] ) );
        }
        //phpcs:enable

        return static::add_wp_site( $website, $params, $output );
    }

    /**
     * Correct the entered URL when the only mismatch is the www prefix.
     *
     * This intentionally preserves the user-selected scheme and only flips the
     * leading www on or off to match what the child site reports.
     *
     * @param string $entered_url Entered child site URL.
     * @param string $reported_url Child-reported site URL.
     *
     * @return string Corrected URL or the original entered URL.
     */
    private static function maybe_correct_www_variant_url( $entered_url, $reported_url ) {
        if ( ! is_string( $entered_url ) || ! is_string( $reported_url ) ) {
            return $entered_url;
        }

        $entered_url  = trim( $entered_url );
        $reported_url = trim( $reported_url );

        $entered_compare  = strtolower( untrailingslashit( MainWP_Utility::remove_http_prefix( $entered_url, true ) ) );
        $reported_compare = strtolower( untrailingslashit( MainWP_Utility::remove_http_prefix( $reported_url, true ) ) );

        if ( empty( $entered_compare ) || empty( $reported_compare ) || $entered_compare === $reported_compare ) {
            return $entered_url;
        }

        $entered_no_www  = strtolower( untrailingslashit( MainWP_Utility::remove_http_www_prefix( $entered_url ) ) );
        $reported_no_www = strtolower( untrailingslashit( MainWP_Utility::remove_http_www_prefix( $reported_url ) ) );

        if ( empty( $entered_no_www ) || $entered_no_www !== $reported_no_www ) {
            return $entered_url;
        }

        $entered_scheme = wp_parse_url( $entered_url, PHP_URL_SCHEME );
        if ( empty( $entered_scheme ) ) {
            return $entered_url;
        }

        $reported_no_scheme = strtolower( MainWP_Utility::remove_http_prefix( $reported_url, true ) );
        $reported_has_www   = MainWP_Utility::starts_with( $reported_no_scheme, 'www.' );

        return strtolower( $entered_scheme ) . '://' . ( $reported_has_www ? 'www.' : '' ) . MainWP_Utility::remove_http_www_prefix( $entered_url );
    }

    /**
     * Try to fetch the child site favicon immediately after a successful add.
     *
     * @param int   $site_id Child site ID.
     * @param array $params  Child site add parameters.
     */
    private static function maybe_fetch_initial_site_favicon( $site_id, $params ) {
        if ( empty( $site_id ) ) {
            return;
        }

        $uploaded_site_icon = isset( $params['uploaded_site_icon'] ) ? $params['uploaded_site_icon'] : '';
        $selected_site_icon = isset( $params['selected_site_icon'] ) ? $params['selected_site_icon'] : '';

        if ( ! empty( $uploaded_site_icon ) || ! empty( $selected_site_icon ) ) {
            return;
        }

        $result = MainWP_Sync::get_wp_icon( $site_id );
        if ( isset( $result['error'] ) && ! empty( $result['error'] ) ) {
            MainWP_Logger::instance()->debug( 'Initial favicon fetch failed :: ' . esc_html( $result['error'] ) );
        }
    }

    /**
     * Medthod add_wp_site()
     *
     * Add new Child Site.
     *
     * @param mixed $website Child Site.
     * @param array $params Array of new Child Site to add.
     * @param array $output Output values.
     *
     * @return array $message, $error, $id
     *
     * @uses \MainWP\Dashboard\MainWP_Connect::fetch_url_authed()
     * @uses \MainWP\Dashboard\MainWP_DB_Common::get_group_by_name()
     * @uses \MainWP\Dashboard\MainWP_DB::add_website()
     * @uses \MainWP\Dashboard\MainWP_DB::get_website_by_id()
     * @uses \MainWP\Dashboard\MainWP_Exception
     * @uses \MainWP\Dashboard\MainWP_Sync::get_wp_icon()
     * @uses \MainWP\Dashboard\MainWP_Sync::sync_information_array()
     * @uses \MainWP\Dashboard\MainWP_System_Utility::get_openssl_conf()
     * @uses  \MainWP\Dashboard\MainWP_Utility::esc_content()
     */
    public static function add_wp_site( $website, $params = array(), &$output = array() ) { //phpcs:ignore -- NOSONAR -Current complexity is the only way to achieve desired results, pull request solutions appreciated.
        $error      = '';
        $message    = '';
        $id         = 0;
        $existed_id = 0;

        $error_category  = 'unknown';
        $error_code      = '';
        $connection_step = '';

        if ( $website ) {
            $error = esc_html__( 'The site is already connected to your MainWP Dashboard', 'mainwp' );
            if ( is_array( $website ) && ! empty( $website[0] ) && is_object( $website[0] ) ) {
                $existed_id = $website[0]->id;
            } elseif ( is_object( $website ) && property_exists( $website, 'id' ) ) {
                $existed_id = $website->id;
            }
            $error_category = 'already_connected';
        } else {
            try {
                if ( MainWP_Connect_Lib::is_use_fallback_sec_lib( $website ) ) {
                    $details = MainWP_Connect_Lib::instance()->create_connect_keys();
                    if ( is_array( $details ) ) {
                        $pubkey  = $details['pub'];
                        $privkey = $details['priv'];
                    } else {
                        $privkey = '-1';
                        $pubkey  = '-1';
                    }
                } elseif ( function_exists( 'openssl_pkey_new' ) ) {
                    $conf     = array( 'private_key_bits' => 2048 );
                    $conf_loc = MainWP_System_Utility::get_openssl_conf();
                    if ( ! empty( $conf_loc ) ) {
                        $conf['config'] = $conf_loc;
                    }
                    $res = openssl_pkey_new( $conf );
                    @openssl_pkey_export( $res, $privkey, null, $conf );  // phpcs:ignore -- prevent warning.
                    $pubkey = openssl_pkey_get_details( $res );
                    $pubkey = $pubkey['key'];
                } else {
                    $privkey = '-1';
                    $pubkey  = '-1';
                }

                $url = $params['url'];

                $verifyCertificate = ( ! isset( $params['ssl_verify'] ) || empty( $params['ssl_verify'] ) ) ? false : true;
                $sslVersion        = ! isset( $params['ssl_version'] ) || empty( $params['ssl_version'] ) ? 0 : $params['ssl_version'];
                $addUniqueId       = isset( $params['unique_id'] ) ? $params['unique_id'] : '';
                $http_user         = isset( $params['http_user'] ) ? $params['http_user'] : '';
                $http_pass         = isset( $params['http_pass'] ) ? $params['http_pass'] : '';
                $force_use_ipv4    = isset( $params['force_use_ipv4'] ) ? $params['force_use_ipv4'] : null;

                MainWP_Logger::instance()->debug( ' :: register site :: ' . $url );

                $connection_step = 'handshake';

                $information = MainWP_Connect::fetch_url_not_authed(
                    $url,
                    $params['wpadmin'],
                    'register',
                    array(
                        'pubkey'   => $pubkey,
                        'server'   => get_admin_url(),
                        'uniqueId' => $addUniqueId,
                        'userpwd'  => isset( $params['adminpwd'] ) ? $params['adminpwd'] : '', // require urlencoded.
                    ),
                    false,
                    $verifyCertificate,
                    $http_user,
                    $http_pass,
                    $sslVersion,
                    array( 'force_use_ipv4' => $force_use_ipv4 ),
                    $output
                );

                if ( isset( $information['error'] ) && '' !== $information['error'] ) {
                    $error = MainWP_Utility::esc_content( $information['error'] );
                    if ( is_array( $output ) ) {
                        if ( ! empty( $output['error_category'] ) ) {
                            $error_category = $output['error_category'];
                        }
                        if ( ! empty( $output['connection_step'] ) ) {
                            $connection_step = $output['connection_step'];
                        }
                        if ( ! empty( $output['error_code'] ) ) {
                            $error_code = $output['error_code'];
                        }
                    }
                } elseif ( isset( $information['register'] ) && 'OK' === $information['register'] ) {
                    $reported_site_url = isset( $information['siteurl'] ) ? trim( wp_unslash( $information['siteurl'] ) ) : '';

                    $corrected_url = static::maybe_correct_www_variant_url( $params['url'], $reported_site_url );
                    if ( $corrected_url !== $params['url'] ) {
                        MainWP_Logger::instance()->debug( ' :: register site :: corrected www variant from ' . $params['url'] . ' to ' . $corrected_url );
                        $params['url'] = $corrected_url;
                    }

                    $connection_step = 'save_site';
                    $groupids        = array();
                    $groupnames      = array();
                    $tmpArr          = array();
                    if ( isset( $params['groupids'] ) && is_array( $params['groupids'] ) ) {
                        foreach ( $params['groupids'] as $group ) {
                            if ( is_numeric( $group ) ) {
                                $groupids[] = $group;
                            } else {
                                $group = trim( $group );
                                if ( ! empty( $group ) ) {
                                    $tmpArr[] = $group;
                                }
                            }
                        }
                        foreach ( $tmpArr as $tmp ) {
                            $getgroup = MainWP_DB_Common::instance()->get_group_by_name( trim( $tmp ) );
                            if ( $getgroup ) {
                                if ( ! in_array( $getgroup->id, $groupids, true ) ) {
                                    $groupids[] = $getgroup->id;
                                }
                            } else {
                                $groupnames[] = trim( $tmp );
                            }
                        }
                    }

                    if ( isset( $params['groupnames_import'] ) && '' !== $params['groupnames_import'] ) {
                        $tmpArr = preg_split( '/[;,]/', $params['groupnames_import'] );
                        foreach ( $tmpArr as $tmp ) {
                            $group = MainWP_DB_Common::instance()->get_group_by_name( trim( $tmp ) );
                            if ( $group ) {
                                if ( ! in_array( $group->id, $groupids, true ) ) {
                                    $groupids[] = $group->id;
                                }
                            } else {
                                $groupnames[] = trim( $tmp );
                            }
                        }
                    }

                    if ( ! isset( $information['uniqueId'] ) || empty( $information['uniqueId'] ) ) {
                        $addUniqueId = '';
                    }

                    $http_user = isset( $params['http_user'] ) ? $params['http_user'] : '';
                    $http_pass = isset( $params['http_pass'] ) ? $params['http_pass'] : '';

                    /**
                     * Current user global.
                     *
                     * @global string
                     */
                    global $current_user;

                    $others = array(
                        'groupids'          => $groupids,
                        'groupnames'        => $groupnames,
                        'verifyCertificate' => $verifyCertificate || false === $verifyCertificate ? 2 : 0, // 2 use global.
                        'addUniqueId'       => $addUniqueId,
                        'http_user'         => $http_user,
                        'http_pass'         => $http_pass,
                        'sslVersion'        => $sslVersion,
                    );

                    $id = MainWP_DB::instance()->add_website( $current_user->ID, $params['name'], $params['url'], $params['wpadmin'], base64_encode( $pubkey ), base64_encode( $privkey ), $others ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions -- base64_encode() used for http encoding compatible.

                    if ( $id && isset( $params['clientid'] ) ) {
                        MainWP_DB::instance()->update_website_values( $id, array( 'client_id' => intval( $params['clientid'] ) ) );
                    }

                    if ( $id ) {
                        $obj_site           = (object) array( 'id' => $id );
                        $uploaded_site_icon = isset( $params['uploaded_site_icon'] )
                            ? $params['uploaded_site_icon']
                            : '';
                        $selected_site_icon = isset( $params['selected_site_icon'] )
                            ? $params['selected_site_icon']
                            : '';
                        $cust_icon_color    = isset( $params['cust_icon_color'] )
                            ? $params['cust_icon_color']
                            : '';
                        MainWP_DB::instance()->update_website_option( $obj_site, 'added_timestamp', time() );
                        MainWP_DB::instance()->update_website_option( $obj_site, 'signature_algo', 9999 ); // use global.
                        $icon_info = 'uploaded:' . $uploaded_site_icon
                            . ';selected:' . $selected_site_icon
                            . ';color:' . $cust_icon_color;
                        MainWP_DB::instance()->update_website_option( $obj_site, 'cust_site_icon_info', $icon_info );
                    }

                    if ( isset( $params['qsw_page'] ) && $params['qsw_page'] ) {
                        set_transient( 'mainwp_transient_just_connected_site_id', $id, HOUR_IN_SECONDS );
                        /* translators: 1: Opening div tag, 2: Site name wrapped in strong tag, 3: Closing div tag, 4: Continue button anchor tag. */
                        $message = sprintf( esc_html__( '%4$s%1$sCongratulations you have connected %2$s.%3$s After finishing the Quick Setup Wizard, you can add additional sites from the Add New Sites page. Proceeding to the next step in 3 seconds...', 'mainwp' ), '<div class="ui header">', '<strong>' . esc_html( $params['name'] ) . '</strong>', '</div>', '<a href="admin.php?page=mainwp-setup&step=monitoring" class="ui mini basic green right floated button">Continue</a>' );
                    } else {
                        /* translators: 1: Opening anchor tag for dashboard link, 2: Closing anchor tag, 3: Line break HTML tag. */
                        $message = sprintf( esc_html__( 'Site successfully added - Visit the Site\'s %1$sDashboard%2$s now.%3$s', 'mainwp' ), '<a href="admin.php?page=managesites&dashboard=' . $id . '" style="text-decoration: none;" title="' . esc_html__( 'Dashboard', 'mainwp' ) . '">', '</a>', '<br/>' );
                    }

                    $website = MainWP_DB::instance()->get_website_by_id( $id );

                    if ( $website ) { // to fix.

                        if ( ! empty( $information['regverify'] ) ) {
                            MainWP_DB::instance()->update_website_option( $website, 'register_verify_key', $information['regverify'] );
                        }

                        $glo_settings          = MainWP_Uptime_Monitoring_Handle::get_global_monitoring_settings();
                        $monitoring_glo_active = is_array( $glo_settings ) && isset( $glo_settings['active'] ) ? (int) $glo_settings['active'] : 1;
                        if ( $monitoring_glo_active ) {
                            MainWP_DB_Uptime_Monitoring::instance()->update_wp_monitor(
                                array(
                                    'wpid'            => $id,
                                    'active'          => -1,
                                    'interval'        => -1, // -1 - use global setting.
                                    'timeout'         => -1,
                                    'method'          => 'useglobal',
                                    'type'            => 'useglobal',
                                    'up_status_codes' => 'useglobal',
                                    'issub'           => 0, // primary monitor.
                                )
                            );
                        }

                        /**
                         * Fires immediately after a new website is added.
                         *
                         * @since 4.5.1.1
                         *
                         * @param object   $website  website data.
                         * @param array $information The array of information data .
                         */
                        do_action( 'mainwp_site_added', $website, $information );

                        /**
                         * New site added
                         *
                         * Fires after adding a website to MainWP Dashboard.
                         *
                         * @param int $id Child site ID.
                         *
                         * @since 3.4
                         */
                        do_action( 'mainwp_added_new_site', $id, $website );

                        MainWP_Sync::sync_init_empty_values( $website );

                        $connection_step = 'post_add_sync';

                        MainWP_Sync::sync_information_array( $website, $information );
                        self::maybe_fetch_initial_site_favicon( $id, $params );
                    }
                } else {
                    $error = sprintf( esc_html__( 'Undefined error occurred. Please try again. For additional help, contact the MainWP Support.', 'mainwp' ), '<a href="https://docs.mainwp.com/troubleshooting/potential-issues" target="_blank">', '</a> <i class="external alternate icon"></i>' ); // NOSONAR - noopener - open safe.
                }
            } catch ( MainWP_Exception $e ) {
                if ( 'HTTPERROR' === $e->getMessage() ) {
                    $error = 'HTTP error' . ( null !== $e->get_message_extra() ? ' - ' . $e->get_message_extra() : '' );
                } elseif ( 'NOMAINWP' === $e->getMessage() ) {
                    $error = MainWP_Error_Helper::get_error_not_detected_connect();
                } else {
                    $error = $e->getMessage();
                }
            }
        }

        $source_screen = 'manage_sites';
        $flow_type     = ! empty( $_POST['bulk'] ) ? 'bulk' : 'single'; //phpcs:ignore -- NOSONAR -nonce ok.
        if ( ! empty( $_POST['qsw_page'] ) ) { //phpcs:ignore -- NOSONAR -nonce ok.
            $flow_type     = 'wizard';
            $source_screen = 'onboarding_wizard';
        }
        if ( 'bulk' === $flow_type ) {
            $source_screen = 'quick_add_modal';
        }

        $telem_info = array(
            'flow_type'     => $flow_type,
            'source_screen' => $source_screen,
        );

        if ( empty( $id ) ) {
            $telem_info['error_message']  = $error;
            $telem_info['error_category'] = $error_category;
            $telem_info['error_code']     = $error_code;

            if ( ! empty( $connection_step ) ) {
                $telem_info['connection_step'] = $connection_step;
            }
            if ( is_array( $output ) && ! empty( $output['http_status'] ) ) {
                $telem_info['http_status'] = $output['http_status'];
            }
        }

        do_action( 'mainwp_after_add_site', array( $message, $error, $id, $existed_id ), $website, $params, $output, $telem_info );

        return array( $message, $error, $id, $existed_id );
    }

    /**
     * Method update_wp_site()
     *
     * Update Child Site.
     *
     * @param mixed $params Udate parameters.
     *
     * @return int Child Site ID on success and return 0 on failure.
     * @throws \MainWP_Exception Error message.
     *
     * @uses \MainWP\Dashboard\MainWP_System_Utility::can_edit_website()
     * @uses  \MainWP\Dashboard\MainWP_Utility::ctype_digit()
     */
    public static function update_wp_site( $params ) {
        if ( ! isset( $params['websiteid'] ) || ! MainWP_Utility::ctype_digit( $params['websiteid'] ) ) {
            return 0;
        }

        if ( isset( $params['is_staging'] ) ) {
            unset( $params['is_staging'] );
        }

        $website = MainWP_DB::instance()->get_website_by_id( $params['websiteid'] );
        if ( null === $website ) {
            return 0;
        }

        if ( ! MainWP_System_Utility::can_edit_website( $website ) ) {
            return 0;
        }

        $data     = array();
        $uniqueId = null;

        if ( isset( $params['name'] ) && ! empty( $params['name'] ) ) {
            $data['name'] = htmlentities( $params['name'] );
        }

        if ( isset( $params['wpadmin'] ) && ! empty( $params['wpadmin'] ) ) {
            $data['adminname'] = $params['wpadmin'];
        }

        if ( isset( $params['unique_id'] ) ) {
            $data['uniqueId'] = $params['unique_id'];
            $uniqueId         = $params['unique_id'];
        }

        if ( empty( $data ) ) {
            return 0;
        }

        MainWP_DB::instance()->update_website_values( $website->id, $data );
        if ( null !== $uniqueId ) {
            try {
                MainWP_Connect::fetch_url_authed( $website, 'update_values', array( 'uniqueId' => $uniqueId ) );
            } catch ( MainWP_Exception $e ) {
                // error update unique id.
            }
        }

        /**
         * Action: mainwp_updated_site
         *
         * Fires after updatig the child site options.
         *
         * @param int   $website->id Child site ID.
         * @param array $data        Child site data.
         *
         * @since 3.5.1
         */
        do_action( 'mainwp_updated_site', $website->id, $data );
        return $website->id;
    }
}
