<?php

class MainWP_Wordfence_Plugin {

    // Singleton
    private static $instance = null;

    static function get_instance() {
        if ( null == self::$instance ) {
            self::$instance = new MainWP_Wordfence_Plugin();
        }

        return self::$instance;
    }

    public function __construct() {
    }

    public function admin_init() {
        do_action( 'mainwp_ajax_add_action', 'mainwp_wfc_active_plugin', array( $this, 'ajax_active_plugin' ) );
        do_action( 'mainwp_ajax_add_action', 'mainwp_wfc_upgrade_plugin', array( $this, 'ajax_upgrade_plugin' ) );
        do_action( 'mainwp_ajax_add_action', 'mainwp_wfc_showhide_plugin', array( $this, 'ajax_showhide_plugin' ) );
        do_action( 'mainwp_ajax_add_action', 'mainwp_wfc_scan_now', array( $this, 'ajax_scan_now' ) );
        do_action( 'mainwp_ajax_add_action', 'mainwp_wfc_kill_scan_now', array( $this, 'ajax_kill_scan_now' ) );
        do_action( 'mainwp_ajax_add_action', 'mainwp_wfc_load_more_dashboard_sites', array( $this, 'ajax_load_more_dashboard_sites' ) );
    }

    public static function gen_plugin_dashboard_tab( $websites, $paged, $last ) {
        ?>
        <table id="mainwp-wordfence-sites-table" class="ui single line table" style="width:100%;">
            <thead>
                <tr>
                    <th class="no-sort collapsing check-column"><span class="ui checkbox"><input type="checkbox" id="cb-select-all-top"></span></th>
                    <th class="collapsing center aligned"><?php esc_html_e( 'Status', 'mainwp-wordfence-extension' ); ?></th>
                    <th><?php esc_html_e( 'Site', 'mainwp-wordfence-extension' ); ?></th>
                    <th class="collapsing right aligned"><?php esc_html_e( 'Last Scan', 'mainwp-wordfence-extension' ); ?></th>
                    <th class="collapsing center aligned"><?php esc_html_e( 'Version', 'mainwp-wordfence-extension' ); ?></th>
                    <th class="collapsing center aligned"><?php esc_html_e( 'Hidden', 'mainwp-wordfence-extension' ); ?></th>
                    <th class="no-sort collapsing"><?php esc_html_e( '', 'mainwp-wordfence-extension' ); ?></th>
                </tr>
            </thead>
            <tbody id="mainwp-wordfence-sites-table-body" last-paged="<?php echo $last ? '1' : '0'; ?>" load-paged="<?php echo intval( $paged ); ?>">
                <?php
                if ( is_array( $websites ) && count( $websites ) > 0 ) {
                    self::get_plugin_dashboard_table_row( $websites );
                }
                ?>
            </tbody>
        </table>
        <?php
    }

    public static function get_plugin_dashboard_table_row( $websites ) {
        $location    = 'admin.php?page=Wordfence';
        $plugin_slug = 'wordfence/wordfence.php';
        $plugin_name = 'Wordfence Security – Firewall & Malware Scan';

        foreach ( $websites as $website ) {
            $website_id = $website['id'];
            $lastscan   = isset( $website['lastscan'] ) ? $website['lastscan'] : 0;
            $status     = isset( $website['status'] ) ? $website['status'] : 0;

            $class_active = ( isset( $website['wordfence_active'] ) && ! empty( $website['wordfence_active'] ) ) ? 'plugin-active' : 'error';
            $class_update = ( isset( $website['wordfence_upgrade'] ) ) ? 'warning' : '';
            $class_update = ( 'error' !== $class_active ) ? $class_update : '';

            if ( empty( $status ) ) {
                $icon_status = '<i class="shield alternate grey large icon"></i>';
            } elseif ( 1 == $status ) {
                    $icon_status = '<i class="shield alternate large green icon"></i>';
            } else {
                $icon_status = '<i class="shield alternate red large icon"></i>';
            }

            $version = '';
            if ( isset( $website['wordfence_upgrade'] ) ) {
                if ( isset( $website['wordfence_upgrade']['new_version'] ) ) {
                    $version = $website['wordfence_upgrade']['new_version'];
                }
            }

            ?>
            <tr class="<?php echo esc_attr( $class_active . ' ' . $class_update ); ?>" website-id="<?php echo intval( $website_id ); ?>" plugin-name="<?php echo esc_attr( $plugin_name ); ?>" plugin-slug="<?php echo esc_attr( $plugin_slug ); ?>" version="<?php echo esc_attr( ( isset( $website['wordfence_plugin_version'] ) ) ? $website['wordfence_plugin_version'] : 'N/A' ); ?>">
                <td class="check-column"><span class="ui checkbox"><input type="checkbox" name="checked[]"></span></td>
                <td class="center aligned"><span class="wfc-scan-working"><i class="notched circle loading large icon" style="display:none"></i> <span class="status"></span> </span><a href="admin.php?page=Extensions-Mainwp-Wordfence-Extension&action=result&site_id=<?php echo intval( $website_id ); ?>"><?php echo $icon_status; ?></a></td>
                <td class="website-name">
                    <div>
                        <a class="open_newwindow_wpadmin" data-position="right center" data-inverted
                            data-tooltip="<?php esc_attr_e( 'Jump to the WP Admin.', 'mainwp-wordfence-extension' ); ?>"
                            target="_blank" rel="noopener noreferrer"
                            href="admin.php?page=SiteOpen&newWindow=yes&websiteid=<?php echo esc_attr( $website_id ); ?>&_opennonce=<?php echo esc_attr( wp_create_nonce( 'mainwp-admin-nonce' ) ); ?>"><i
                                class="sign in icon"></i></a>
                        <a href="admin.php?page=managesites&dashboard=<?php echo esc_attr( $website_id ); ?>"
                            data-tooltip="<?php esc_attr_e( 'Go to the site overview.', 'mainwp-wordfence-extension' ); ?>"
                            data-inverted data-position="right center" class="mainwp-site-name-link">
                            <?php echo esc_html( $website['name'] ); ?>
                        </a>
                    </div>
                    <span class="ui small text">
                        <a href="<?php echo esc_url( $website['url'] ?? '' ); ?>" target="_blank" rel="noopener noreferrer"
                            class="open_site_url ui grey text"
                            data-tooltip="<?php esc_attr_e( 'Go to the website.', 'mainwp-wordfence-extension' ); ?>"
                            data-position="right center" data-inverted><?php echo esc_html( $website['url'] ?? '' ); ?></a>
                    </span>
                </td>            
                
                <td class="right aligned"><?php echo ! empty( $lastscan ) ? esc_html_e( apply_filters( 'mainwp_get_time_elapsed_string', $lastscan ) ) : 'N/A'; ?></td>
                <td class="center aligned"><span class="updating"></span> <?php echo ( isset( $website['wordfence_upgrade'] ) ) ? '<i class="exclamation circle icon"></i>' : ''; ?> <?php echo ( isset( $website['wordfence_plugin_version'] ) ) ? $website['wordfence_plugin_version'] : 'N/A'; ?></td>
                <td class="wp-wordfence-visibility center aligned"><?php echo ( 1 == $website['hide_wordfence'] ) ? __( 'Yes', 'mainwp-wordfence-extension' ) : __( 'No', 'mainwp-wordfence-extension' ); ?></td>
                <td class="not-selectable">
                    <div class="ui left pointing dropdown" style="z-index:999">
                        <a href="javascript:void(0)"><i class="ellipsis vertical icon"></i></a>
                        <div class="menu">
                            <a class="item" href="admin.php?page=managesites&dashboard=<?php echo intval( $website_id ); ?>"><?php esc_html_e( 'Overview', 'mainwp-wordfence-extension' ); ?></a>
                            <a class="item" href="admin.php?page=managesites&id=<?php echo intval( $website_id ); ?>"><?php esc_html_e( 'Edit', 'mainwp-wordfence-extension' ); ?></a>
                            <a class="item" href="admin.php?page=SiteOpen&newWindow=yes&websiteid=<?php echo intval( $website_id ); ?>&location=<?php echo base64_encode( $location ); ?>&_opennonce=<?php echo wp_create_nonce( 'mainwp-admin-nonce' ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Open Wordfence', 'mainwp-wordfence-extension' ); ?></a>
                            <?php if ( 1 == $website['hide_wordfence'] ) : ?>
                            <a class="item mwp_wfc_showhide_plugin" href="javascript:void(0)" showhide="show"><?php esc_html_e( 'Unhide Plugin', 'mainwp-wordfence-extension' ); ?></a>
                            <?php else : ?>
                            <a class="item mwp_wfc_showhide_plugin" href="javascript:void(0)" showhide="hide"><?php esc_html_e( 'Hide Plugin', 'mainwp-wordfence-extension' ); ?></a>
                            <?php endif; ?>

                            <?php if ( isset( $website['wordfence_active'] ) && empty( $website['wordfence_active'] ) ) : ?>
                            <a class="item mwp_wfc_active_plugin" href="#"><?php esc_html_e( 'Activate Plugin', 'mainwp-wordfence-extension' ); ?></a>
                            <?php else : ?>
                            <a class="item mwp_wfc_scan_now_lnk" href="#"><?php esc_html_e( 'Scan Site', 'mainwp-wordfence-extension' ); ?></a>
                            <a class="item" href="admin.php?page=Extensions-Mainwp-Wordfence-Extension&action=traffic&site_id=<?php echo intval( $website_id ); ?>"><?php esc_html_e( 'Live Traffic', 'mainwp-wordfence-extension' ); ?></a>
                            <a class="item" href="admin.php?page=Extensions-Mainwp-Wordfence-Extension&action=blocking&site_id=<?php echo intval( $website_id ); ?>"><?php esc_html_e( 'Blocking', 'mainwp-wordfence-extension' ); ?></a>
                            <a class="item" href="admin.php?page=Extensions-Mainwp-Wordfence-Extension&action=result&site_id=<?php echo intval( $website_id ); ?>"><?php esc_html_e( 'Scan Results', 'mainwp-wordfence-extension' ); ?></a>
                            <?php endif; ?>

                            <?php if ( isset( $website['wordfence_upgrade'] ) ) : ?>
                            <a class="item mwp_wfc_upgrade_plugin" href="#"><?php esc_html_e( 'Update Plugin', 'mainwp-wordfence-extension' ); ?></a>
                            <?php endif; ?>
                        </div>
                    </div>
        </td>
        </tr>
            <?php
        }
    }


    public function ajax_load_more_dashboard_sites() {
        do_action( 'mainwp_secure_request', 'mainwp_wfc_load_more_dashboard_sites' );
        $nonce = isset( $_POST['nonce'] ) ? $_POST['nonce'] : null;
        if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'wfc-nonce' ) ) {
            die( json_encode( array( 'error' => 'Invalid request!' ) ) );
        }
        $paged          = isset( $_POST['paged'] ) ? $_POST['paged'] : 0;
        $selected_group = 0;
        if ( isset( $_POST['mainwp_wfc_plugin_groups_select'] ) ) {
            $selected_group = intval( $_POST['mainwp_wfc_plugin_groups_select'] );
        }
        $data     = MainWP_Wordfence::get_webites_with_wordfence( false, $selected_group );
        $websites = $data['result'];
        $last     = $data['last'];

        $result = '';

        if ( is_array( $websites ) && count( $websites ) > 0 ) :
            ob_start();
            if ( is_array( $websites ) && count( $websites ) > 0 ) {
                self::get_plugin_dashboard_table_row( $websites );
            }
            $result = ob_get_clean();
        endif;

        die(
            wp_json_encode(
                array(
                    'result' => $result,
                    'last'   => $last,
                )
            )
        );
    }


    public function get_websites_with_the_plugin( $websites, $selected_group = 0, $active_only = false ) {
        $websites_wordfence = array();

        if ( is_array( $websites ) && count( $websites ) ) {
            if ( empty( $selected_group ) ) {
                foreach ( $websites as $website ) {
                    if ( $website && $website->plugins != '' ) {
                        $settings = MainWP_Wordfence_DB::get_instance()->get_setting_by( 'site_id', $website->id );
                        $plugins  = json_decode( $website->plugins, 1 );
                        if ( is_array( $plugins ) && count( $plugins ) != 0 ) {
                            foreach ( $plugins as $plugin ) {
                                if ( 'wordfence/wordfence.php' == $plugin['slug'] ) {
                                    if ( $active_only && ! $plugin['active'] ) {
                                        continue;
                                    }
                                    $site = MainWP_Wordfence_Utility::map_site( $website, array( 'id', 'name', 'url' ) );
                                    if ( $plugin['active'] ) {
                                        $site['wordfence_active'] = 1;
                                    } else {
                                        $site['wordfence_active'] = 0;
                                    }
                                    // get upgrade info
                                    $site['wordfence_plugin_version'] = $plugin['version'];
                                    $plugin_upgrades                  = json_decode( $website->plugin_upgrades, 1 );
                                    if ( is_array( $plugin_upgrades ) && count( $plugin_upgrades ) > 0 ) {
                                        if ( isset( $plugin_upgrades['wordfence/wordfence.php'] ) ) {
                                            $upgrade = $plugin_upgrades['wordfence/wordfence.php'];
                                            if ( isset( $upgrade['update'] ) ) {
                                                $site['wordfence_upgrade'] = $upgrade['update'];
                                            }
                                        }
                                    }

                                    $site['lastscan']       = $settings->lastscan;
                                    $site['status']         = $settings->status;
                                    $site['hide_wordfence'] = $settings->isHidden;
                                    $websites_wordfence[]   = $site;
                                    break;
                                }
                            }
                        }
                    }
                }
            } else {
                global $mainWPWordfenceExtensionActivator;

                $group_websites = apply_filters( 'mainwp_getdbsites', $mainWPWordfenceExtensionActivator->get_child_file(), $mainWPWordfenceExtensionActivator->get_child_key(), array(), array( $selected_group ) );
                $sites          = array();
                foreach ( $group_websites as $site ) {
                    $sites[] = $site->id;
                }
                foreach ( $websites as $website ) {
                    if ( $website && $website->plugins != '' && in_array( $website->id, $sites ) ) {
                        $plugins = json_decode( $website->plugins, 1 );
                        if ( is_array( $plugins ) && count( $plugins ) != 0 ) {
                            foreach ( $plugins as $plugin ) {
                                if ( 'wordfence/wordfence.php' == $plugin['slug'] ) {
                                    if ( $active_only && ! $plugin['active'] ) {
                                        continue;
                                    }
                                    $site = MainWP_Wordfence_Utility::map_site( $website, array( 'id', 'name', 'url' ) );
                                    if ( $plugin['active'] ) {
                                        $site['wordfence_active'] = 1;
                                    } else {
                                        $site['wordfence_active'] = 0;
                                    }
                                    $site['wordfence_plugin_version'] = $plugin['version'];

                                    // get upgrade info.
                                    $plugin_upgrades = json_decode( $website->plugin_upgrades, 1 );
                                    if ( is_array( $plugin_upgrades ) && count( $plugin_upgrades ) > 0 ) {
                                        if ( isset( $plugin_upgrades['wordfence/wordfence.php'] ) ) {
                                            $upgrade = $plugin_upgrades['wordfence/wordfence.php'];
                                            if ( isset( $upgrade['update'] ) ) {
                                                $site['wordfence_upgrade'] = $upgrade['update'];
                                            }
                                        }
                                    }
                                    $settings               = MainWP_Wordfence_DB::get_instance()->get_setting_by( 'site_id', $website->id );
                                    $site['hide_wordfence'] = $settings->isHidden;
                                    $site['lastscan']       = $settings->lastscan;
                                    $site['status']         = $settings->status;
                                    $websites_wordfence[]   = $site;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

        // if search action
        $search_sites = array();
        if ( isset( $_GET['s'] ) && ! empty( $_GET['s'] ) ) {
            $find = trim( $_GET['s'] );
            foreach ( $websites_wordfence as $website ) {
                if ( stripos( $website['name'], $find ) !== false || stripos( $website['url'], $find ) !== false ) {
                    $search_sites[] = $website;
                }
            }
            $websites_wordfence = $search_sites;
        }
        unset( $search_sites );

        return $websites_wordfence;
    }

    public function ajax_active_plugin() {
        do_action( 'mainwp_secure_request', 'mainwp_wfc_active_plugin' );
        do_action( 'mainwp_activePlugin' );
        die();
    }

    public function ajax_upgrade_plugin() {
        do_action( 'mainwp_secure_request', 'mainwp_wfc_upgrade_plugin' );
        do_action( 'mainwp_upgradePluginTheme' );
        die();
    }

    public function ajax_showhide_plugin() {
        do_action( 'mainwp_secure_request', 'mainwp_wfc_showhide_plugin' );
        $siteid   = isset( $_POST['websiteId'] ) ? intval( $_POST['websiteId'] ) : null;
        $showhide = isset( $_POST['showhide'] ) && in_array( $_POST['showhide'], array( 'show', 'hide' ) )
                        ? sanitize_text_field( $_POST['showhide'] )
                        : null;
        if ( null !== $siteid && null !== $showhide ) {
            global $mainWPWordfenceExtensionActivator;
            $post_data   = array(
                'mwp_action' => 'set_showhide',
                'showhide'   => $showhide,
            );
            $information = apply_filters( 'mainwp_fetchurlauthed', $mainWPWordfenceExtensionActivator->get_child_file(), $mainWPWordfenceExtensionActivator->get_child_key(), $siteid, 'wordfence', $post_data );

            if ( is_array( $information ) && isset( $information['result'] ) && 'SUCCESS' === $information['result'] ) {

                $update = array(
                    'site_id'  => $siteid,
                    'isHidden' => ( 'hide' === $showhide ? 1 : 0 ),
                );
                MainWP_Wordfence_DB::get_instance()->update_setting( $update );

            }
            die( json_encode( $information ) );
        }
        die();
    }

    function ajax_scan_now() {
        do_action( 'mainwp_secure_request', 'mainwp_wfc_scan_now' );
        $siteid = isset( $_POST['siteId'] ) ? intval( $_POST['siteId'] ) : 0;
        if ( ! empty( $siteid ) ) {
            global $mainWPWordfenceExtensionActivator;
            $post_data   = array( 'mwp_action' => 'start_scan' );
            $information = apply_filters( 'mainwp_fetchurlauthed', $mainWPWordfenceExtensionActivator->get_child_file(), $mainWPWordfenceExtensionActivator->get_child_key(), $siteid, 'wordfence', $post_data );
            if ( ( isset( $information['result'] ) && 'SUCCESS' == $information['result'] ) ||
                ( isset( $information['error'] ) && 'SCAN_RUNNING' == $information['error'] )
            ) {
                $update = array(
                    'site_id'  => $siteid,
                    'lastscan' => time(),
                );
                MainWP_Wordfence_DB::get_instance()->update_setting( $update );
            }
            die( json_encode( $information ) );
        }
        die();
    }

    function ajax_kill_scan_now() {
        do_action( 'mainwp_secure_request', 'mainwp_wfc_kill_scan_now' );
        $siteid = isset( $_POST['siteId'] ) ? intval( $_POST['siteId'] ) : 0;
        if ( ! empty( $siteid ) ) {
            global $mainWPWordfenceExtensionActivator;
            $post_data   = array( 'mwp_action' => 'kill_scan' );
            $information = apply_filters( 'mainwp_fetchurlauthed', $mainWPWordfenceExtensionActivator->get_child_file(), $mainWPWordfenceExtensionActivator->get_child_key(), $siteid, 'wordfence', $post_data );
            die( json_encode( $information ) );
        }
        die();
    }
}
