<?php
/**
 * =======================================
 * MainWP Database Updater Admin
 * =======================================
 */
namespace MainWP\Extensions\DatabaseUpdater;

class MainWP_Database_Updater_Admin {

    public $version = '1.2';

    /**
     * Static variable to hold the single instance of the class.
     *
     * @static
     *
     * @var mixed Default null
     */
    static $instance = null;

    /**
     * Get Instance
     *
     * Creates public static instance.
     *
     * @static
     *
     * @return MainWP_Database_Updater_Admin
     */
    static function get_instance() {
        if ( null == self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Method get_class_name()
     *
     * Get Class Name.
     *
     * @return string __CLASS__
     */
    public static function get_class_name() {
        return __CLASS__;
    }


    /**
     * Constructor
     *
     * Runs each time the class is called.
     */
    public function __construct() {
        add_action( 'init', array( &$this, 'init' ) );
        add_action( 'init', array( &$this, 'localization' ) );
    }

    /**
     * Initiate Hooks
     *
     * Initiates hooks for the Database Updater extension.
     */
    public function init() {
        add_filter( 'plugin_row_meta', array( &$this, 'plugin_row_meta' ), 10, 2 );
        add_action( 'admin_init', array( &$this, 'admin_init' ) );
        add_filter( 'mainwp_log_specific_actions', array( &$this, 'hook_mainwp_log_specific_actions' ), 10, 2 );
        add_filter( 'mainwp_sync_others_data', array( $this, 'hook_sync_others_data' ), 10, 2 );
        add_action( 'mainwp_site_synced', array( $this, 'hook_synced_site' ), 10, 2 );
        add_filter( 'mainwp_page_hearder_tabs_updates', array( $this, 'hook_page_hearder_tabs_updates' ), 10, 1 );
        add_filter( 'mainwp_sub_leftmenu_updates', array( $this, 'hook_sub_leftmenu_updates' ), 10, 1 );
        add_action( 'mainwp_updates_overview_after_update_details', array( $this, 'hook_overview_after_update_details' ), 10, 3 );
        add_filter( 'mainwp_pages_updates_render_tabs', array( $this, 'hook_pages_updates_render_tabs' ), 10, 2 );
        add_filter( 'mainwp_updates_hide_show_updates_per', array( $this, 'hook_hide_show_updates_per' ), 10, 2 );

        add_filter( 'mainwp_sitestable_getcolumns', array( $this, 'hook_manage_sites_column' ), 10 );
        add_filter( 'mainwp_sitestable_prepare_extra_view', array( $this, 'hook_manage_sites_prepare_extra_view' ), 10 );
        add_filter( 'mainwp_sitestable_website', array( $this, 'hook_manage_sites_website' ), 10, 2 );
        add_filter( 'mainwp_available_updates_count_custom_fields_data', array( $this, 'hook_updates_count_custom_fields_data' ), 10, 2 );
        add_filter( 'mainwp_database_updater_supported_plugins', array( $this, 'hook_database_updater_supported_plugins' ), 10, 2 );
        add_action( 'mainwp_individual_updates_tabs', array( &$this, 'hook_individual_updates_tabs' ), 10, 2 );
    }

    /**
     * Localization
     *
     * Sets the localization domain.
     */
    public function localization() {
        load_plugin_textdomain( 'mainwp-database-updater-extension', false, dirname( dirname( plugin_basename( __FILE__ ) ) ) . '/languages/' );
    }

    /**
     * Plugin Row Meta
     *
     * Displays the meta in the plugin row on the WP > Plugins > Installed Plugins page.
     *
     * @param array  $plugin_meta Plugin meta data.
     * @param string $plugin_file Plugin file.
     *
     * @return array  $plugin_meta Plugin meta data.
     */
    public function plugin_row_meta( $plugin_meta, $plugin_file ) {
        if ( MAINWP_DATABASE_UPDATER_PLUGIN_SLUG != $plugin_file ) {
            return $plugin_meta;
        }

        $slug     = basename( $plugin_file, '.php' );
        $api_data = get_option( $slug . '_APIManAdder' );

        if ( ! is_array( $api_data ) || ! isset( $api_data['activated_key'] ) || $api_data['activated_key'] != 'Activated' || ! isset( $api_data['api_key'] ) || empty( $api_data['api_key'] ) ) {
            return $plugin_meta;
        }

        $plugin_meta[] = '<a href="?do=checkUpgrade" title="Check for updates.">Check for updates now</a>';

        return $plugin_meta;
    }

    /**
     * Admin Init
     *
     * Initiates admin hooks.
     */
    public function admin_init() {

        $is_overview = isset( $_GET['page'] ) && 'mainwp_tab' == $_GET['page'] && ! isset( $_GET['id'] ) && ! isset( $_GET['do'] ) ? true : false;
        $is_update   = isset( $_GET['page'] ) && 'UpdatesManage' == $_GET['page'] && isset( $_GET['tab'] ) && 'plugin-db-updates' == $_GET['tab'] ? true : false;
        $is_update   = $is_update || ( isset( $_GET['page'] ) && 'managesites' == $_GET['page'] && isset( $_GET['updateid'] ) );
        if ( $is_overview || $is_update ) {
            wp_enqueue_style( 'mainwp-database-updater-extension', MAINWP_DATABASE_UPDATER_PLUGIN_URL . 'css/mainwp-database-updater.css', array(), $this->version );
            wp_enqueue_script( 'mainwp-database-updater-extension', MAINWP_DATABASE_UPDATER_PLUGIN_URL . 'js/mainwp-database-updater.js', array( 'jquery' ), $this->version );
        }
    }



    public function hook_mainwp_log_specific_actions( $input ) {
        $input[ MAINWP_DATABASE_UPDATER_LOG_PRIORITY ] = 'Database Updater';
        return $input;
    }

    /**
     * Render tabs
     *
     * Renders the extension page tabs.
     */
    public function render_tabs( $website = false ) {
        MainWP_Database_Updater_Overview::get_instance()->gen_tabs_general( $website );
    }


    /**
     * Send data to Child Site on Sync.
     *
     * @param array $data Array of data to send.
     * @param array $website Array of previously saved Child Site data.
     * @return array|mixed
     */
    public function hook_sync_others_data( $data, $website = null ) {
        if ( ! is_array( $data ) ) {
            $data = array();
        }
        $data['syncDBUpdater'] = 1;
        return $data;
    }

    /**
     * Grab data via sync_others_data() from Child Site when synced
     * and update stored Child Site Data.
     *
     * @param array $website  Array of previously saved Child Site data.
     * @param array $information Array of data sent from Child Site.
     */
    public function hook_synced_site( $website, $information = array() ) {
        if ( $website && is_array( $information ) && isset( $information['syncDBUpdaterResponse'] ) ) {
            $data = $information['syncDBUpdaterResponse'];

            // DB updates format:
            // $data['plugin_db_upgrades']['elementor/elementor.php']     = array(
            //     'update'     => array(
            //         'new_db_version' => '6.0',
            //         'slug'           => 'elementor/elementor.php',
            //     ),
            //     'Name'       => 'Elementor',
            //     'db_version' => '5.0',
            // );
            // $data['plugin_db_upgrades']['woocommerce/woocommerce.php'] = array(
            //     'update'     => array(
            //         'new_db_version' => '6.0',
            //         'slug'           => 'woocommerce/woocommerce.php',
            //     ),
            //     'Name'       => 'WooCommerce',
            //     'db_version' => '5.0',
            // );

            if ( ! is_array( $data ) || ! isset( $data['plugin_db_upgrades'] ) ) {
                return;
            }
            MainWP_Database_Updater_Utility::update_website_option( $website, 'plugin_db_upgrades', ( is_array( $data['plugin_db_upgrades'] ) ? wp_json_encode( $data['plugin_db_upgrades'] ) : '' ) );
        }
    }

    public function get_individual_total_db_updates() {
        return $this->get_total_db_updates( true );
    }

    public function get_total_db_updates( $individual = false ) {
        global $mainwp_database_updater_total_count, $mainwp_database_updater_all_plugins_db, $mainwp_database_updater_individual_total_count, $mainwp_database_updater_individual_all_plugins_db;

        if ( $individual && null !== $mainwp_database_updater_individual_total_count ) {
            return $mainwp_database_updater_individual_total_count;
        }

        if ( ! $individual && null !== $mainwp_database_updater_total_count ) {
            return $mainwp_database_updater_total_count;
        }

        $current_site_id = 0;

        if ( $individual ) {
            $current_site_id = isset( $_GET['dashboard'] ) && ! empty( $_GET['dashboard'] ) ? intval( $_GET['dashboard'] ) : 0;
        }

        $websites = MainWP_Database_Updater_Updates_Plugins::get_sites();

        $userExtension = apply_filters( 'mainwp_get_user_extension', false );

        $total_plugin_db_upgrades            = 0;
        $total_individual_plugin_db_upgrades = 0;

        $supported_plugins = MainWP_Database_Updater_Updates_Plugins::get_supported_plugins();

        MainWP_Database_Updater_Utility::data_seek( $websites );

        while ( $websites && ( $website = MainWP_Database_Updater_Utility::fetch_object( $websites ) ) ) {

            $plugin_db_upgrades = isset( $website->plugin_db_upgrades ) && ! empty( $website->plugin_db_upgrades ) ? json_decode( $website->plugin_db_upgrades, true ) : array();

            if ( $website->is_ignorePluginUpdates ) {
                $plugin_db_upgrades = array();
            }

            if ( is_array( $plugin_db_upgrades ) && ! $website->is_ignorePluginUpdates ) {
                $_ignored_plugins = json_decode( $website->ignored_plugins, true );
                if ( is_array( $_ignored_plugins ) ) {
                    $plugin_db_upgrades = array_diff_key( $plugin_db_upgrades, $_ignored_plugins );
                }

                $_ignored_plugins = json_decode( $userExtension->ignored_plugins, true );
                if ( is_array( $_ignored_plugins ) ) {
                    $plugin_db_upgrades = array_diff_key( $plugin_db_upgrades, $_ignored_plugins );
                }
                // supported the WC plugin.
                if ( is_array( $plugin_db_upgrades ) ) {
                    foreach ( $supported_plugins as $supp_slug ) {
                        if ( isset( $plugin_db_upgrades[ $supp_slug ] ) ) {
                            ++$total_plugin_db_upgrades;
                            $mainwp_database_updater_all_plugins_db[] = array(
                                'id'          => $website->id,
                                'name'        => $website->name,
                                'plugin_slug' => $supp_slug,
                            );
                        }

                        if ( $current_site_id && $current_site_id === (int) $website->id ) {
                            if ( isset( $plugin_db_upgrades[ $supp_slug ] ) ) {
                                ++$total_individual_plugin_db_upgrades;
                                $mainwp_database_updater_individual_all_plugins_db[] = array(
                                    'id'          => $website->id,
                                    'name'        => $website->name,
                                    'plugin_slug' => $supp_slug,
                                );
                            }
                        }
                    }
                }
            }
        }

        MainWP_Database_Updater_Utility::free_result( $websites );

        if ( $individual ) {
            $mainwp_database_updater_individual_total_count = $total_individual_plugin_db_upgrades;
            return $total_individual_plugin_db_upgrades;
        } else {
            $mainwp_database_updater_total_count = $total_plugin_db_upgrades;
            return $total_plugin_db_upgrades;
        }
    }

    /**
     * Method hook_page_hearder_tabs_updates().
     * Hook page hearder tabs updates.
     *
     * @param array $tabs  Array of previously saved Child Site data.
     */
    public function hook_page_hearder_tabs_updates( $tabs ) {
        if ( ! is_array( $tabs ) ) {
            $tabs = array();
        }

        $total_plugin_db_upgrades = $this->get_total_db_updates();

        $add_tab = array(
            'slug'           => 'plugin-db-updates',
            'title'          => esc_html__( 'Database Updates', 'mainwp-database-updater-extension' ),
            'total_upgrades' => $total_plugin_db_upgrades,
        );

        $return = array();
        foreach ( $tabs as $slug => $tab ) {
            if ( 'abandoned-plugins' === $slug ) {
                $return['plugin-db-updates'] = $add_tab;
            }
            $return[ $slug ] = $tab;
        }

        if ( ! isset( $return['plugin-db-updates'] ) ) {
            $return['plugin-db-updates'] = $add_tab;
        }
        return $return;
    }

    /**
     * Method hook_sub_leftmenu_updates().
     * Hook sub leftmenu updates.
     *
     * @param array $submenus  sub menus.
     */
    public function hook_sub_leftmenu_updates( $submenus ) {
        if ( ! is_array( $submenus ) ) {
            $submenus = array();
        }

        $updates_count = $this->get_total_db_updates();

        $label_color = '';
        if ( 0 < $updates_count ) {
            $label_color = ' blue ';
        }

        $add_menu = array(
            'title'      => esc_html__( 'Database', 'mainwp' ) . ' <span class="ui ' . $label_color . ' label">' . intval( $updates_count ) . '</span>',
            'parent_key' => 'UpdatesManage',
            'href'       => 'admin.php?page=UpdatesManage&tab=plugin-db-updates',
            'slug'       => 'UpdatesManage',
            'right'      => '',
        );

        $added  = false;
        $return = array();
        foreach ( $submenus as $menu ) {
            if ( 'admin.php?page=UpdatesManage&tab=abandoned-plugins' === $menu['href'] ) {
                $return[] = $add_menu;
                $added    = true;
            }
            $return[] = $menu;
        }

        if ( ! $added ) {
            $return[] = $add_menu;
        }
        return $return;
    }

    function hook_overview_after_update_details( $currentSite = false, $globalView = false ) {

        global $mainwp_database_updater_all_plugins_db, $mainwp_database_updater_individual_all_plugins_db;

        $db_updater_all_plugins = array();

        if ( $globalView ) {
            $updates_count          = $this->get_total_db_updates();
            $db_updater_all_plugins = $mainwp_database_updater_all_plugins_db;
        } else {
            $updates_count          = $this->get_individual_total_db_updates();
            $db_updater_all_plugins = $mainwp_database_updater_individual_all_plugins_db;
        }
        ?>
        <div class="ui card" id="mainwp-database-updater-overview-db-updates-row-info">
            <div class="content">
                <div class="header">
                    <span class="ui large text"><i class="database icon"></i> <?php echo intval( $updates_count ); ?></span>
                </div>
                <div class="description"><?php esc_html_e( 'Available database updates.', 'mainwp-database-updater-extension' ); ?></div>
            </div>
            <div class="extra content">
                <div class="ui two column grid">
                    <div class="left aligned middle aligned column">
                        <a href="#" onclick="<?php echo $updates_count ? "return mainwp_database_updater_global_upgrade_all('plugin_db');" : 'javascript:void(0)'; ?>" class="ui mini <?php echo $updates_count ? '' : 'disabled'; ?> green mainwp-update-all-button button "><?php esc_html_e( 'Update All', 'mainwp-database-updater-extension' ); ?></a>
                    </div>
                    <div class="right aligned middle aligned column">
                        <a href="admin.php?page=UpdatesManage&tab=plugin-db-updates"><?php esc_html_e( 'See Details', 'mainwp-database-updater-extension' ); ?></a>
                    </div>
                </div>
            </div>
        </div>

        <div id="wp_plugin_database_updater_db_upgrades">
            <?php

            $user_can_update_plugins = MainWP_Database_Updater_Updates_Plugins::user_can_update_plugins();
            if ( $user_can_update_plugins && is_array( $db_updater_all_plugins ) ) {
                foreach ( $db_updater_all_plugins as $item ) {
                    ?>
                    <div updated="0" site_id="<?php echo intval( $item['id'] ); ?>" site_name="<?php echo esc_attr( $item['name'] ); ?>" plugin_db_slug="<?php echo esc_attr( $item['plugin_slug'] ); ?>" ></div>
                    <?php
                }
            }
            ?>
        </div>

        <?php
    }

    public function hook_pages_updates_render_tabs( $value, $current_tab ) {
        if ( 'plugin-db-updates' === $current_tab ) {
            $this->render_tabs();
            return true;
        }
        return $value;
    }
    public function hook_individual_updates_tabs( $website ) {
        ?>
        <div id="plugin-db-updates" class="ui tab" data-tab="dbupdates">
        <?php
        $this->render_tabs( $website );
        ?>
        </div>
        <?php
    }

    public function hook_hide_show_updates_per( $value, $current_tab ) {
        if ( 'plugin-db-updates' === $current_tab ) {
            return true;
        }
        return $value;
    }

    /**
     * Manage Sites Column
     *
     * Adds the custom column in the Manage Sites and Monitoring tables.
     *
     * @param array $columns Table comlumns.
     *
     * @return array $columns Table comlumns.
     */
    public function hook_manage_sites_column( $columns ) {
        $columns['database_updater_total'] = '<i class="database icon"></i>';
        return $columns;
    }

    /**
     * Manage Sites Column
     *
     * Adds the custom column in the Manage Sites and Monitoring tables.
     *
     * @param array $extra_view extra_view.
     *
     * @return array $extra_view extra_view.
     */
    public function hook_manage_sites_prepare_extra_view( $extra_view ) {
        if ( is_array( $extra_view ) ) {
            $extra_view[] = 'plugin_db_upgrades';
        }
        return $extra_view;
    }

    /**
     * Manage Sites Column
     *
     * Adds the custom column in the Manage Sites and Monitoring tables.
     *
     * @param array  $website website.
     * @param object $userExtension userExtension.
     *
     * @return array $extra_view extra_view.
     */
    public function hook_manage_sites_website( $website, $userExtension = false ) {

        if ( is_array( $website ) && isset( $website['plugin_db_upgrades'] ) ) {
            $supported_plugins        = MainWP_Database_Updater_Updates_Plugins::get_supported_plugins();
            $total_plugin_db_upgrades = 0;

            $plugin_db_upgrades = json_decode( $website['plugin_db_upgrades'], true );
            if ( $website['is_ignorePluginUpdates'] ) {
                $plugin_db_upgrades = array();
            }

            if ( is_array( $plugin_db_upgrades ) && ! $website['is_ignorePluginUpdates'] ) {
                $_ignored_plugins = json_decode( $website['ignored_plugins'], true );
                if ( is_array( $_ignored_plugins ) ) {
                    $plugin_db_upgrades = array_diff_key( $plugin_db_upgrades, $_ignored_plugins );
                }

                $_ignored_plugins = json_decode( $userExtension->ignored_plugins, true );
                if ( is_array( $_ignored_plugins ) ) {
                    $plugin_db_upgrades = array_diff_key( $plugin_db_upgrades, $_ignored_plugins );
                }

                // supported the WC plugin.
                if ( is_array( $plugin_db_upgrades ) ) {
                    foreach ( $supported_plugins as $supp_slug ) {
                        if ( isset( $plugin_db_upgrades[ $supp_slug ] ) ) {
                            ++$total_plugin_db_upgrades;
                        }
                    }
                }
            }
            $website['database_updater_total'] = '<a href="admin.php?page=UpdatesManage&tab=plugin-db-updates" class="ui ' . MainWP_Database_Updater_Utility::color_code( $total_plugin_db_upgrades ) . ' label">' . $total_plugin_db_upgrades . '</a>';
        }
        return $website;
    }

    /**
     * Method hook_updates_count_custom_fields_data().
     */
    public function hook_updates_count_custom_fields_data( $data, $what = '' ) {
        if ( 'updates_count' === $what ) {
            return array( 'plugin_db_upgrades' );
        }
        return $data;
    }

    /**
     * Method hook_database_updater_supported_plugins().
     */
    public function hook_database_updater_supported_plugins( $data, $what = '' ) {
        return MainWP_Database_Updater_Updates_Plugins::get_supported_plugins();
    }
}
