<?php if ( ! defined( 'ABSPATH' ) ) exit( 'No direct script access allowed' );
/**
 * Etheme Admin Panel Dashboard.
 *
 * Add admin panel dashboard pages to admin menu.
 * Output dashboard pages.
 *
 * @since   5.0.0
 * @version 1.0.5
 */
class EthemeAdmin{

    /**
     * TGMPA instance storage
     *
     * @var object
     */
    protected $tgmpa_instance;

    /**
     * TGMPA Menu slug
     *
     * @var string
     */
    protected $tgmpa_menu_slug = 'tgmpa-install-plugins';

    /**
     * TGMPA Menu url
     *
     * @var string
     */
    protected $tgmpa_url = 'themes.php?page=tgmpa-install-plugins';

    protected $theme_name;

	/**
	 * Panel page
	 *
	 * @var array
	 */
	protected $page = array();

    // ! Main construct/ add actions
    function __construct(){

        add_action( 'admin_menu', array( $this, 'et_add_menu_page' ) );
        add_action( 'admin_head', array( $this, 'et_add_menu_page_target') );
        add_action( 'wp_ajax_et_ajax_panel_popup', array($this, 'et_ajax_panel_popup') );
        add_action( 'wp_ajax_et_create_child_theme', array($this, 'et_create_child_theme') );
	    add_action( 'wp_ajax_et_plugins_actions', array($this, 'et_plugins_actions') );
	    add_action( 'wp_ajax_et_delete_transient', array($this, 'et_delete_transient') );

	    add_action( 'wp_ajax_et_panel_ajax', array($this, 'et_panel_ajax') );

        $current_theme         = wp_get_theme();
        $this->theme_name      = strtolower( preg_replace( '#[^a-zA-Z]#', '', $current_theme->get( 'Name' ) ) );

        if ( class_exists( 'TGM_Plugin_Activation' ) && isset( $GLOBALS['tgmpa'] ) ) {
            add_action( 'init', array( $this, 'get_tgmpa_instanse' ), 30 );
            add_action( 'init', array( $this, 'set_tgmpa_url' ), 40 );
        }

        add_action( 'admin_init', array( $this, 'admin_redirects' ), 30 );

        add_filter( 'tgmpa_load', array( $this, 'tgmpa_load' ), 10, 1 );
        add_action( 'wp_ajax_envato_setup_plugins', array( $this, 'ajax_plugins' ) );

	    add_action('admin_init',array($this,'add_page_admin_script'), 1140);

	    if(!is_child_theme()){
            add_action( 'after_switch_theme', array( $this, 'switch_theme' ) );
        }

	    if ( ! $this->set_page_data() ){
		    return;
	    }
    }

	/**
	 * enqueue scripts for current panel page
	 *
	 * @version  1.0.0
	 * @since  7.0.0
	 */
    public function add_page_admin_script(){
        if ( isset($this->page['script']) && ! empty($this->page['script']) ){
	        wp_enqueue_script('etheme_panel_'.$this->page['script'],ETHEME_BASE_URI.'framework/panel/js/'.$this->page['script'].'.js', array('jquery','etheme_admin_js'), false,true);
        }
    }

	/**
	 * Set panel page data
	 *
	 * @version  1.0.0
	 * @since  7.0.0
	 */
    public function set_page_data(){
        if (! isset($_GET['page'])){
            return false;
        }
	    switch ( $_GET['page'] ) {
		    case 'et-panel-system-requirements':
			    $this->page['template'] = 'system-requirements';
			    break;
		    case 'et-panel-changelog':
			    $this->page['template'] = 'changelog';
			    break;
		    case 'et-panel-support':
			    $this->page['template'] = 'support';
			    $this->page['class'] = 'youtube';
			    break;
		    case 'et-panel-demos':
			    $this->page['template'] = 'demos';
			    break;
		    case 'et-panel-custom-fonts':
			    $this->page['template'] = 'custom-fonts';
			    break;
		    case 'et-panel-social':
			    $this->page['script'] = 'instagram';
			    $this->page['template'] = 'instagram';
			    $this->page['class'] = 'instagram';
			    break;
		    case 'et-panel-plugins':
			    $this->page['template'] = 'plugins';
			    break;
		    case 'et-panel-generator':
			    $this->page['script'] = 'generator';
			    $this->page['template'] = 'generator';
			    $this->page['class'] = 'generator';
			    break;
		    default:
			    $this->page['template'] = 'welcome';
			    break;
	    }
        return true;
    }

	/**
	 * Require page classes
	 *
	 * require page classes when ajax process and return the callbacks for ajax requests
	 *
	 * @version  1.0.0
	 * @since  7.0.0
     * @param string $class class filename
	 */
    public function require_class($class=''){
        if (! $class){
            return;
        }
	    require_once( apply_filters('etheme_file_url', ETHEME_CODE . 'panel/classes/'.$class.'.php') );
    }

	/**
	 * Global panel ajax
     *
     * require page classes when ajax process and return the callbacks for ajax requests
	 *
	 * @version  1.0.0
	 * @since  7.0.0
	 */
    public function et_panel_ajax(){
        if ( isset($_POST['action_type']) ){
	        switch ( $_POST['action_type'] ) {
		        case 'et_generator':
			        $this->require_class('generator');
			        $class = new Etheme_Generator;
			        $class->generator();
			        break;
		        case 'et_generator_remover':
			        $this->require_class('generator');
			        $class = new Etheme_Generator;
			        $class->generator_remover();
			        break;
		        case 'et_instagram_user_add':
			        $this->require_class('instagram');
			        $class = new Instagram();
			        $class->et_instagram_user_add();
			        break;
                case 'et_instagram_user_remove':
	                $this->require_class('instagram');
                    $class = new Instagram();
                    $class->et_instagram_user_remove();
                    break;
		        case 'et_instagram_save_settings':
		            $this->require_class('instagram');
			        $class = new Instagram();
			        $class->et_instagram_save_settings();
			        break;
		        default:
			        break;
	        }
        }
    }

    /**
     * Add admin panel dashboard pages to admin menu.
     *
     * @since   5.0.0
     * @version 1.0.2
     */
    public function et_add_menu_page(){
        $system = new Etheme_System_Requirements();
        $system->system_test();
        $result = $system->result();

        $is_et_core = class_exists('ETC\App\Controllers\Admin\Import');
        $is_activated = etheme_is_activated();
	    $info = '<span class="awaiting-mod" style="position: relative;min-width: 16px;height: 16px;margin: 2px 0 0 6px; background: #fff;"><span class="dashicons dashicons-warning" style="width: auto;height: auto;vertical-align: middle;position: absolute;left: -3px;top: -3px; color: var(--et_admin_orange-color); font-size: 22px;"></span></span>';
	    $icon = ETHEME_CODE_IMAGES . 'wp-icon.svg';
	    $label = 'XStore';
	    $show_pages = array(
		    'welcome',
		    'system_requirements',
		    'demos',
		    'plugins',
		    'customize',
		    'generator',
		    'custom_fonts',
		    'social',
		    'support',
		    'changelog',
            'sponsors'
        );
	    
	    $xstore_branding_settings = get_option( 'xstore_white_label_branding_settings', array() );
	
	    if ( count($xstore_branding_settings) && isset($xstore_branding_settings['control_panel'])) {
	        if ( $xstore_branding_settings['control_panel']['icon'] )
	            $icon = $xstore_branding_settings['control_panel']['icon'];
		    if ( $xstore_branding_settings['control_panel']['label'] )
			    $label = $xstore_branding_settings['control_panel']['label'];
		    
		    $show_pages_parsed = array();
		    foreach ( $show_pages as $show_page ) {
                if ( isset($xstore_branding_settings['control_panel']['page_'.$show_page]))
                    $show_pages_parsed[] = $show_page;
		    };
		    $show_pages = $show_pages_parsed;
        }
	    
        add_menu_page( 
            $label . ' ' . ( ( !$is_activated || !$result ) ? $info : '' ),
            $label . ' ' . ( ( !$is_activated || !$result ) ? $info : '' ),
            'manage_options', 
            'et-panel-welcome',
            array( $this, 'etheme_panel_page' ),
	        $icon,
            65
        );
	
	    if ( in_array('welcome', $show_pages) ) {
		    add_submenu_page(
			    'et-panel-welcome',
			    esc_html__( 'Welcome', 'xstore' ),
			    esc_html__( 'Welcome', 'xstore' ),
			    'manage_options',
			    'et-panel-welcome',
			    array( $this, 'etheme_panel_page' )
		    );
	    }
	
	    if ( in_array('system_requirements', $show_pages) ) {


		    $server_label = esc_html__( 'Server Requirements', 'xstore' );

		    if (!$result){
			    $server_label = esc_html__( 'Server Reqs.', 'xstore' );
			    $server_label .= ' ' . $info;
            }

		    add_submenu_page(
			    'et-panel-welcome',
			    $server_label,
			    $server_label,
			    'manage_options',
			    'et-panel-system-requirements',
			    array( $this, 'etheme_panel_page' )
		    );
	    }
        
        if ( $is_activated ) {
	
	        if ( in_array('demos', $show_pages) ) {
		        add_submenu_page(
			        'et-panel-welcome',
			        esc_html__( 'Import Demos', 'xstore' ),
			        esc_html__( 'Import Demos', 'xstore' ),
			        'manage_options',
			        'et-panel-demos',
			        array( $this, 'etheme_panel_page' )
		        );
	        }
	
	        if ( in_array('plugins', $show_pages) ) {
		        add_submenu_page(
			        'et-panel-welcome',
			        esc_html__( 'Plugins Installer', 'xstore' ),
			        esc_html__( 'Plugins Installer', 'xstore' ),
			        'manage_options',
			        'et-panel-plugins',
			        array( $this, 'etheme_panel_page' )
		        );
	        }
	
	        if ( in_array('generator', $show_pages) ) {
		        add_submenu_page(
			        'et-panel-welcome',
			        esc_html__( 'Files Generator', 'xstore' ),
			        esc_html__( 'Files Generator', 'xstore' ),
			        'manage_options',
			        'et-panel-generator',
			        array( $this, 'etheme_panel_page' )
		        );
	        }

        }

//        if ( ! etheme_is_activated() && ! class_exists( 'Kirki' ) ) {
            // add_submenu_page(
            //     'et-panel-welcome',
            //     esc_html__( 'Setup Wizard', 'xstore' ),
            //     esc_html__( 'Setup Wizard', 'xstore' ),
            //     'manage_options',
            //     admin_url( 'themes.php?page=xstore-setup' ),
            //     ''
            // );
//        } elseif( ! etheme_is_activated() ){
//
//        } elseif( ! class_exists( 'Kirki' ) ){
//            add_submenu_page(
//                'et-panel-welcome',
//                esc_html__( 'Plugins installer', 'xstore' ),
//                esc_html__( 'Plugins installer', 'xstore' ),
//	            'manage_options',
//	            'et-panel-plugins',
//	            array( $this, 'etheme_panel_page' )
//            );
//        }
//        else {
//
//            add_submenu_page(
//                'et-panel-welcome',
//                esc_html__( 'Install Plugins', 'xstore' ),
//                esc_html__( 'Install Plugins', 'xstore' ),
//                'manage_options',
//                admin_url( 'themes.php?page=install-required-plugins&plugin_status=all' ),
//                ''
//            );
//        }

        if ( $is_activated && $is_et_core ) {

            if ( ! class_exists( 'Kirki' ) ) {
//                add_submenu_page(
//                    'et-panel-welcome',
//                    'Theme Options',
//                    'Theme Options',
//                    'manage_options',
//                    admin_url( 'themes.php?page=install-required-plugins&plugin_status=all' ),
//                    ''
//                );
            }
            elseif ( get_option('et_options') && (!get_option( 'xstore_theme_migrated', false ) ) ) {
	            if ( in_array('customize', $show_pages) ) {
		            add_submenu_page(
			            'et-panel-welcome',
			            'Theme Options',
			            'Theme Options',
			            'manage_options',
			            add_query_arg( 'xstore_theme_migrate_options', 'true', wp_customize_url() ),
			            ''
		            );
		            add_submenu_page(
			            'et-panel-welcome',
			            'Header Builder',
			            'Header Builder',
			            'manage_options',
			            ( get_option( 'etheme_header_builder', false ) ? add_query_arg( 'xstore_theme_migrate_options', 'true', admin_url( '/customize.php?autofocus[panel]=header-builder' ) ) : add_query_arg( 'xstore_theme_migrate_options', 'true', admin_url( '/customize.php?autofocus[section]=header-builder' ) ) ),
			            ''
		            );
		            add_submenu_page(
			            'et-panel-welcome',
			            'Single Product Builder',
			            'Single Product Builder',
			            'manage_options',
			            ( get_option( 'etheme_single_product_builder', false ) ? add_query_arg( 'xstore_theme_migrate_options', 'true', admin_url( '/customize.php?autofocus[panel]=single_product' ) ) : add_query_arg( 'xstore_theme_migrate_options', 'true', admin_url( '/customize.php?autofocus[section]=single_product' ) ) ),
			            ''
		            );
	            }
            }
            else {
	            if ( in_array('customize', $show_pages) ) {
		            add_submenu_page(
			            'et-panel-welcome',
			            'Theme Options',
			            'Theme Options',
			            'manage_options',
			            wp_customize_url(),
			            ''
		            );
		            add_submenu_page(
			            'et-panel-welcome',
			            'Header Builder',
			            'Header Builder',
			            'manage_options',
			            ( get_option( 'etheme_header_builder', false ) ? admin_url( '/customize.php?autofocus[panel]=header-builder' ) : admin_url( '/customize.php?autofocus[section]=header-builder' ) ),
			            ''
		            );
		            add_submenu_page(
			            'et-panel-welcome',
			            'Single Product Builder',
			            'Single Product Builder',
			            'manage_options',
			            ( get_option( 'etheme_single_product_builder', false ) ? admin_url( '/customize.php?autofocus[panel]=single_product_builder' ) : admin_url( '/customize.php?autofocus[section]=single_product_builder' ) ),
			            ''
		            );
	            }
            }
	
	        if ( in_array('social', $show_pages) ) {
		        add_submenu_page(
			        'et-panel-welcome',
			        esc_html__( 'Instagram API', 'xstore' ),
			        esc_html__( 'Instagram API', 'xstore' ),
			        'manage_options',
			        'et-panel-social',
			        array( $this, 'etheme_panel_page' )
		        );
	        }
	
	        if ( in_array('custom_fonts', $show_pages) ) {
		        add_submenu_page(
			        'et-panel-welcome',
			        esc_html__( 'Custom Fonts', 'xstore' ),
			        esc_html__( 'Custom Fonts', 'xstore' ),
			        'manage_options',
			        'et-panel-custom-fonts',
			        array( $this, 'etheme_panel_page' )
		        );
	        }
	
	        if ( in_array('support', $show_pages) ) {
		        add_submenu_page(
			        'et-panel-welcome',
			        esc_html__( 'Tutorials & Support', 'xstore' ),
			        esc_html__( 'Tutorials & Support', 'xstore' ),
			        'manage_options',
			        'et-panel-support',
			        array( $this, 'etheme_panel_page' )
		        );
	        }
	
	        if ( in_array('changelog', $show_pages) ) {
		        add_submenu_page(
			        'et-panel-welcome',
			        esc_html__( 'Changelog', 'xstore' ),
			        esc_html__( 'Changelog', 'xstore' ),
			        'manage_options',
			        'et-panel-changelog',
			        array( $this, 'etheme_panel_page' )
		        );
	        }
        }
        
        else {
	        if ( in_array('customize', $show_pages) ) {
		        add_submenu_page(
			        'et-panel-welcome',
			        'Theme Options',
			        'Theme Options',
			        'manage_options',
			        admin_url( 'themes.php?page=install-required-plugins&plugin_status=all' ),
			        ''
		        );
	        }
        }

        if ( $is_activated && in_array('sponsors', $show_pages) ) {
	        add_submenu_page(
		        'et-panel-welcome',
		        esc_html__( 'Get WPML', 'xstore' ),
		        esc_html__( 'Get WPML', 'xstore' ),
		        'manage_options',
		        'https://wpml.org/?aid=46060&affiliate_key=YI8njhBqLYnp',
		        ''
	        );
	
	        add_submenu_page(
		        'et-panel-welcome',
		        esc_html__( 'Customization Service', 'xstore' ),
		        esc_html__( 'Customization Service', 'xstore' ),
		        'manage_options',
		        'https://wpkraken.io/?ref=8theme',
		        ''
	        );
            if ( $is_et_core ) {
		        add_submenu_page(
			        'et-panel-welcome',
			        esc_html__( 'Rate Theme', 'xstore' ),
			        esc_html__( 'Rate Theme', 'xstore' ),
			        'manage_options',
			        'https://themeforest.net/item/xstore-responsive-woocommerce-theme/reviews/15780546',
			        ''
		        );
	        }
        }
    }

    /**
     * Add target blank to some dashboard pages.
     *
     * @since   6.2
     * @version 1.0.0
     */
    public function et_add_menu_page_target() {
        ob_start(); ?>
            <script type="text/javascript">
                jQuery(document).ready( function($) {
                    $('#adminmenu .wp-submenu a[href*=themeforest]').attr('target','_blank');
                });
            </script>
        <?php echo ob_get_clean();
    }

    /**'
     * Show Add admin panel dashboard pages.
     *
     * @since   5.0.0
     * @version 1.0.4
     */
    public function etheme_panel_page(){
        ob_start();
            get_template_part( 'framework/panel/templates/page', 'header' );
                get_template_part( 'framework/panel/templates/page', 'navigation' );
                echo '<div class="et-row etheme-page-content">';
                    if (isset($this->page['class']) && ! empty($this->page['class'])){
                        $this->require_class($this->page['class']);
                    }
	                if (isset($this->page['template']) && ! empty($this->page['template'])){
		                get_template_part( 'framework/panel/templates/page', $this->page['template'] );
	                }
                echo '</div>';
            get_template_part( 'framework/panel/templates/page', 'footer' );
        echo ob_get_clean();
    }


    public function et_ajax_panel_popup(){
        $response = array();

        if ( isset( $_POST['type'] ) && $_POST['type'] == 'instagram' ) {
            ob_start();
            get_template_part( 'framework/panel/templates/popup-instagram', 'content' );
            $response['content'] = ob_get_clean();
        } else {
            ob_start();
            get_template_part( 'framework/panel/templates/popup-import', 'head' );
            $response['head'] = ob_get_clean();
            
            ob_start();
                get_template_part( 'framework/panel/templates/popup-import', 'content');
            $response['content'] = ob_get_clean();
        }
        wp_send_json($response);
    }

    public function et_create_child_theme(){
        $parent_theme_title = 'XStore';
        $parent_theme_template = 'xstore';
        $parent_theme_name = get_stylesheet();
        $parent_theme_dir = get_stylesheet_directory();

        // isset($_REQUEST['theme_name']) && isset($_REQUEST['theme_template']) && current_user_can('manage_options')

        $new_theme_title = $_POST['theme_name'];
        $new_theme_template = $_POST['theme_template'];

        // Turn a theme name into a directory name
        $new_theme_name = sanitize_title( $new_theme_title );
        $theme_root = get_theme_root();

        // Validate theme name
        $new_theme_path = $theme_root.'/'.$new_theme_name;
        if ( file_exists( $new_theme_path ) ) {
            // Don't create child theme.
        } else{
            // Create Child theme
            wp_mkdir_p( $new_theme_path );

            $plugin_folder = get_template_directory().'/framework/thirdparty/child-theme/';

            // Make style.css
            ob_start();
            require $plugin_folder.'child-theme-css.php';
            $css = ob_get_clean();

            global $wp_filesystem;

            if ( empty( $wp_filesystem ) ) {
                require_once ( ABSPATH . '/wp-admin/includes/file.php' );
                WP_Filesystem();
            }

            $wp_filesystem->put_contents( $new_theme_path.'/style.css', $css, FS_CHMOD_FILE );

            //file_put_contents( $new_theme_path.'/style.css', $css );

            // Copy functions.php
            copy( $plugin_folder.'functions.php', $new_theme_path.'/functions.php' );
            
            // Copy screenshot
            copy( $plugin_folder.'screenshot.png', $new_theme_path.'/screenshot.png' );

            // Make child theme an allowed theme (network enable theme)
            $allowed_themes = get_site_option( 'allowedthemes' );
            $allowed_themes[ $new_theme_name ] = true;
            update_site_option( 'allowedthemes', $allowed_themes );
        }
        
        // Switch to theme
        if($parent_theme_template !== $new_theme_name){
            update_option('xstore_has_child', $new_theme_name);
            switch_theme( $new_theme_name, $new_theme_name );

            $response = array();
            $response['type'] = 'success';
            $response['new_theme_title'] = $new_theme_title;
            $response['new_theme_path'] = 'wp-content/themes/' . $new_theme_name;
        } else {
            $response['type'] = 'error';
        }
       wp_send_json($response);
    }


    public function get_popup_plugin_list($version){
        $versions = etheme_get_demo_versions();
        $version = $versions[$version];


        $instance = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
        $plugins  = array(
            'all'      => array(), // Meaning: all plugins which still have open actions.
            'install'  => array(),
            'update'   => array(),
            'activate' => array(),
        );

        foreach ( $instance->plugins as $slug => $plugin ) {

            $new_is_plugin_active = (
                ( ! empty( $instance->plugins[ $slug ]['is_callable'] ) && is_callable( $instance->plugins[ $slug ]['is_callable'] ) )
                || in_array( $instance->plugins[ $slug ]['file_path'], (array) get_option( 'active_plugins', array() ) ) || is_plugin_active_for_network( $instance->plugins[ $slug ]['file_path'] )
            );
            
            if ( $new_is_plugin_active && false === $instance->does_plugin_have_update( $slug ) ) {
                // No need to display plugins if they are installed, up-to-date and active.
                continue;
            } else {
                $plugins['all'][ $slug ] = $plugin;

                if ( ! $instance->is_plugin_installed( $slug ) ) {
                    $plugins['install'][ $slug ] = $plugin;
                } else {
                    if ( false !== $instance->does_plugin_have_update( $slug ) ) {
                        $plugins['update'][ $slug ] = $plugin;
                        // unset($plugins['all'][ $slug ]);
                    }

                    if ( $instance->can_plugin_activate( $slug ) ) {
                        $plugins['activate'][ $slug ] = $plugin;
                    }
                }
            }
        }

        $required = array_filter($plugins['all'], function($el) {
            return $el['required'];
        });

	    $to_show = array();
	    foreach ( $version['plugins'] as $item ) {
	        if (isset($plugins['all'][$item]) && $plugins['all'][$item]){
		        $to_show[$item]=$plugins['all'][$item];
	        }
        }

        $return = array_merge($required,$to_show);

        foreach ($return as $key => $value) {
            if ( array_key_exists($key, $plugins['install']) ) {
                $return[$key]['btn_text'] = esc_html__( 'Install', 'xstore' );
                $return[$key]['btn_type'] = 'install';
            } else if( array_key_exists($key, $plugins['activate']) ){
                $return[$key]['btn_text'] = esc_html__( 'Activate', 'xstore' );
                $return[$key]['btn_type'] = 'activate';
            } else if(array_key_exists($key, $plugins['update'])){
	            unset($return[$key]);
            }
        }

        return $return;
    }


    public function switch_theme() {
        set_transient( '_' . $this->theme_name . '_activation_redirect', 1 );
    }

    public function admin_redirects() {
        ob_start();
        if ( ! get_transient( '_' . $this->theme_name . '_activation_redirect' ) || get_option( 'envato_setup_complete', false ) ) {
            return;
        }
        delete_transient( '_' . $this->theme_name . '_activation_redirect' );
        // wp_safe_redirect( admin_url( $this->page_url ) );
        wp_safe_redirect( admin_url( 'admin.php?page=et-panel-welcome' ) );
        exit;
    }

    public function ajax_plugins() {
        if ( ! check_ajax_referer( 'envato_setup_nonce', 'wpnonce' ) || empty( $_POST['slug'] ) ) {
            wp_send_json_error( array( 'error' => 1, 'message' => esc_html__( 'No Slug Found', 'xstore' ) ) );
        }
        $json = array();
        // send back some json we use to hit up TGM
        $plugins = $this->_get_plugins();
        // what are we doing with this plugin?
        foreach ( $plugins['activate'] as $slug => $plugin ) {
            if ( $_POST['slug'] == $slug ) {
                $json = array(
                    'url'           => admin_url( $this->tgmpa_url ),
                    'plugin'        => array( $slug ),
                    'tgmpa-page'    => $this->tgmpa_menu_slug,
                    'plugin_status' => 'all',
                    '_wpnonce'      => wp_create_nonce( 'bulk-plugins' ),
                    'action'        => 'tgmpa-bulk-activate',
                    'action2'       => - 1,
                    'message'       => esc_html__( 'Activating Plugin', 'xstore' ),
                );
                break;
            }
        }
        foreach ( $plugins['update'] as $slug => $plugin ) {
            if ( $_POST['slug'] == $slug ) {
                $json = array(
                    'url'           => admin_url( $this->tgmpa_url ),
                    'plugin'        => array( $slug ),
                    'tgmpa-page'    => $this->tgmpa_menu_slug,
                    'plugin_status' => 'all',
                    '_wpnonce'      => wp_create_nonce( 'bulk-plugins' ),
                    'action'        => 'tgmpa-bulk-update',
                    'action2'       => - 1,
                    'message'       => esc_html__( 'Updating Plugin', 'xstore' ),
                );
                break;
            }
        }
        foreach ( $plugins['install'] as $slug => $plugin ) {
            if ( $_POST['slug'] == $slug ) {
                $json = array(
                    'url'           => admin_url( $this->tgmpa_url ),
                    'plugin'        => array( $slug ),
                    'tgmpa-page'    => $this->tgmpa_menu_slug,
                    'plugin_status' => 'all',
                    '_wpnonce'      => wp_create_nonce( 'bulk-plugins' ),
                    'action'        => 'tgmpa-bulk-install',
                    'action2'       => - 1,
                    'message'       => esc_html__( 'Installing Plugin', 'xstore' ),
                );
                break;
            }
        }

        if ( $json ) {
            $json['hash'] = md5( serialize( $json ) ); // used for checking if duplicates happen, move to next plugin
            wp_send_json( $json );
        } else {
            wp_send_json( array( 'done' => 1, 'message' => esc_html__( 'Success', 'xstore' ) ) );
        }
        exit;

    }

    private function _get_plugins( $version = false ) {
        $instance = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
        $plugins  = array(
            'all'      => array(), // Meaning: all plugins which still have open actions.
            'install'  => array(),
            'update'   => array(),
            'activate' => array(),
        );

        foreach ( $instance->plugins as $slug => $plugin ) {

            $new_is_plugin_active = (
                ( ! empty( $instance->plugins[ $slug ]['is_callable'] ) && is_callable( $instance->plugins[ $slug ]['is_callable'] ) )
                || in_array( $instance->plugins[ $slug ]['file_path'], (array) get_option( 'active_plugins', array() ) ) || is_plugin_active_for_network( $instance->plugins[ $slug ]['file_path'] )
            );
            
            if ( $new_is_plugin_active && false === $instance->does_plugin_have_update( $slug ) ) {
                // No need to display plugins if they are installed, up-to-date and active.
                continue;
            } else {
                $plugins['all'][ $slug ] = $plugin;

                if ( ! $instance->is_plugin_installed( $slug ) ) {
                    $plugins['install'][ $slug ] = $plugin;
                } else {
                    if ( false !== $instance->does_plugin_have_update( $slug ) ) {
                        $plugins['update'][ $slug ] = $plugin;
                    }

                    if ( $instance->can_plugin_activate( $slug ) ) {
                        $plugins['activate'][ $slug ] = $plugin;
                    }
                }
            }
        }

        return $plugins;
    }

    public function tgmpa_load( $status ) {
        return is_admin() || current_user_can( 'install_themes' );
    }

    /**
     * Get configured TGMPA instance
     *
     * @access public
     * @since 1.1.2
     */
    public function get_tgmpa_instanse() {
        $this->tgmpa_instance = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
    }

    /**
     * Update $tgmpa_menu_slug and $tgmpa_parent_slug from TGMPA instance
     *
     * @access public
     * @since 1.1.2
     */
    public function set_tgmpa_url() {

        $this->tgmpa_menu_slug = ( property_exists( $this->tgmpa_instance, 'menu' ) ) ? $this->tgmpa_instance->menu : $this->tgmpa_menu_slug;
        $this->tgmpa_menu_slug = apply_filters( $this->theme_name . '_theme_setup_wizard_tgmpa_menu_slug', $this->tgmpa_menu_slug );

        $tgmpa_parent_slug = ( property_exists( $this->tgmpa_instance, 'parent_slug' ) && $this->tgmpa_instance->parent_slug !== 'themes.php' ) ? 'admin.php' : 'themes.php';

        $this->tgmpa_url = apply_filters( $this->theme_name . '_theme_setup_wizard_tgmpa_url', $tgmpa_parent_slug . '?page=' . $this->tgmpa_menu_slug );

    }

	/**
	 * Plugins page actions
	 *
	 * @version  1.0.0
	 * @since  6.3.4
	 */
	public function et_plugins_actions() {
            check_admin_referer( 'envato_setup_nonce', 'wpnonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json('no access ');
        }

			if ( $_POST['type'] === 'deactivate'  ) { // phpcs:ignore WordPress.Security

				$instance = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );

				foreach ( $instance->plugins as $plugin ) {
					if ( $plugin['slug'] === $_POST['slug'] ) {
						deactivate_plugins( $plugin['file_path'] );
					}
				}
			}
        wp_send_json('success');
	}

	/**
	 * Delete transient by ajax
	 *
	 * @version  1.0.0
	 * @since  6.3.4
	 */
	public function et_delete_transient() {
		if (delete_transient($_POST['transient'])) {
			wp_send_json('success');
		}
	}
}
new EthemeAdmin;