<?php
defined('ABSPATH') || die('Cheatin\' uh?');

/**
 * Handles the parameters and url
 *
 * @author Squirrly
 */
class NXTLVL_Classes_Helpers_Tools
{

    /**
     * 
     *
     * @var array Options, User Metas, Package and Plugin details 
     */
    public static $options, $usermeta, $allplugins = array();

    public function __construct()
    {
        self::$options = $this->getOptions();

        NXTLVL_Classes_ObjController::getClass('NXTLVL_Classes_HookController')->setHooks($this);
    }

    /**
     * This hook will save the current version in database
     *
     * @return void
     */
    function hookInit()
    {
        //Load the languages pack
        $this->loadMultilanguage();

        //If the token si not yet set, run the instalation process
        //check the User Roles, DB and DevKit
        if(!self::getOption('strb_api')){
            self::install();
        }

        //add setting link in plugin
        add_filter('plugin_action_links', array($this, 'hookActionlink'), 5, 2);
    }

    /**
     * Install the required data
     *
     * @return void
     */
    public static function install(){

    }

    /**
     * Add a link to settings in the plugin list
     *
     * @param  array  $links
     * @param  string $file
     * @return array
     */
    public function hookActionlink($links, $file)
    {
        if ($file == _NXTLVL_NAME_ . '/index.php') {
            $link = '<a href="' . self::getAdminUrl('strb_settings') . '">' . esc_html__("Getting started", 'nextlvl') . '</a>';
            array_unshift($links, $link);
        }

        return $links;
    }

    /**
     * Load the Options from user option table in DB
     *
     * @param string $action
     * @return array|mixed|object
     */
    public static function getOptions($action = '')
    {
        $default = array(
            'strb_version' => NEXT_LVL,
            'strb_use' => 1,
            'strb_subscribe' => 0,
            'strb_inposts' => 1,
            'strb_strictposts' => 0,
            'strb_inpages' => 0,
            'strb_ineachpost' => 0,
            'strb_showopengraph' => 1,
            'strb_shortcode' => 1,
            'strb_powered_by' => 1,
            // --
            'strb_position' => 'down',
            'anh_crt_posts' => 3,
            'strb_author' => array(),
            'strb_theme' => 'business',
            'strb_achposttheme' => 'drop-down',
            'strb_titlefontsize' => 'default',
            'strb_descfontsize' => 'default',
        );
        $options = json_decode(get_option(NXTLVL_OPTION), true);

        // if (is_array($options)) {
        //     $options = @array_merge($default, $options);
        // } else {
        //     $options = $default;
        // }

        // $options['strb_themes'] = array('business', 'fancy', 'minimal','new-theme', 'drop-down', 'topstar', 'topstar-round');
        // $options['strb_achpostthemes'] = array('drop-down', 'topstar', 'topstar-round');
        // $options['strb_titlefontsizes'] = array('default', '10px', '12px', '14px', '16px', '18px', '20px', '24px', '26px', '30px');
        // $options['strb_descfontsizes'] = array('default', '10px', '12px', '14px', '16px', '18px', '20px', '24px', '26px', '30px');

        return $options;
    }

    /**
     * Get the option from database
     *
     * @param  $key
     * @return mixed
     */
    public static function getOption($key)
    {
        if (!isset(self::$options[$key])) {
            self::$options = self::getOptions();

            if (!isset(self::$options[$key])) {
                self::$options[$key] = false;
            }
        }

        return apply_filters('strb_option_' . $key, self::$options[$key]);
    }

    /**
     * Save the Options in user option table in DB
     *
     * @param null   $key
     * @param string $value
     */
    public static function saveOptions($key = null, $value = '')
    {
        if (isset($key)) {
            self::$options[$key] = $value;
        }

        update_option(NXTLVL_OPTION, wp_json_encode(self::$options));
    }

    /**
     * Get user metas
     *
     * @param  null $user_id
     * @return array|mixed
     */
    public static function getUserMetas($user_id = null)
    {
        if (!isset($user_id)) {
            $user_id = get_current_user_id();
        }

        $default = array('strb_auto_sticky' => 0,);

        $usermeta = get_user_meta($user_id);
        $usermetatmp = array();
        if (is_array($usermeta)) foreach ($usermeta as $key => $values) {
            $usermetatmp[$key] = $values[0];
        }
        $usermeta = $usermetatmp;

        if (is_array($usermeta)) {
            $usermeta = array_merge((array)$default, (array)$usermeta);
        } else {
            $usermeta = $default;
        }
        self::$usermeta = $usermeta;
        return $usermeta;
    }

    /**
     * Get use meta
     *
     * @param  $value
     * @return bool
     */
    public static function getUserMeta($value)
    {
        if (!isset(self::$usermeta[$value])) {
            self::getUserMetas();
        }

        if (isset(self::$usermeta[$value])) {
            return apply_filters('strb_usermeta_' . $value, self::$usermeta[$value]);
        }

        return false;
    }

    /**
     * Save user meta
     *
     * @param $key
     * @param $value
     * @param null $user_id
     */
    public static function saveUserMeta($key, $value, $user_id = null)
    {
        if (!isset($user_id)) {
            $user_id = get_current_user_id();
        }
        self::$usermeta[$key] = $value;
        update_user_meta($user_id, $key, $value);
    }

    /**
     * Delete User meta
     *
     * @param $key
     * @param null $user_id
     */
    public static function deleteUserMeta($key, $user_id = null)
    {
        if (!isset($user_id)) {
            $user_id = get_current_user_id();
        }
        unset(self::$usermeta[$key]);
        delete_user_meta($user_id, $key);
    }

    /**
     * Get the option from database
     *
     * @param  $key
     * @return mixed
     */
    public static function getMenuVisible($key)
    {
        if(self::getOption('strb_auto_devkit')) {
            if (!isset(self::$options['menu'][$key])) {
                self::$options = self::getOptions();

                if (!isset(self::$options['menu'][$key])) {
                    self::$options['menu'][$key] = false;
                }
            }

            return apply_filters('strb_menu_visible', self::$options['menu'][$key], $key);
        }

        return true;
    }

    /**
     * Set the header type
     *
     * @param string $type
     */
    public static function setHeader($type)
    {
        if (self::getValue('strb_debug') == 'on') {
            return;
        }

        switch ($type) {
        case 'json':
            header('Content-Type: application/json');
            break;
        case 'ico':
            header('Content-Type: image/x-icon');
            break;
        case 'png':
            header('Content-Type: image/png');
            break;
        case'text':
            header("Content-type: text/plain");
            break;
        case'html':
            header("Content-type: text/html");
            break;
        }
    }

    /**
     * Get a value from $_POST / $_GET
     * if unavailable, take a default value
     *
     * @param  string $key           Value key
     * @param  mixed  $defaultValue  (optional)
     * @param  bool   $htmlcode
     * @param  bool   $keep_newlines
     * @return mixed Value
     */
    public static function getValue($key, $defaultValue = false, $keep_newlines = false)
    {
        if (!isset($key) || (isset($key) && $key == '')) {
            return $defaultValue;
        }

        //Get the params from forms
        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
            $ret = (isset($_POST[$key]) ? $_POST[$key] : (isset($_GET[$key]) ? $_GET[$key] : ''));
        } else {
            $ret = (isset($_GET[$key]) ? $_GET[$key] : '');
        }

        //Start sanitization of each param
        //based on the type
        if (is_array($ret)) { //if array, sanitize each value from the array
            if (!empty($ret)) {
                foreach ($ret as &$row) {
                    if (!is_array($row)) {
                        $row = sanitize_text_field($row); //sanitize
                    }
                }
            }
        } elseif (is_string($ret) && $ret <> '' && $keep_newlines && function_exists('sanitize_textarea_field')) {
            $ret = sanitize_textarea_field($ret);
        }  else{
            $ret = sanitize_text_field($ret);
        }

        if (!$ret) {
            return $defaultValue;
        } else {
            return wp_unslash($ret);
        }

    }

    /**
     * Set the Nonce action
     *
     * @param  $action
     * @param  string $name
     * @param  bool   $referer
     * @param  bool   $echo
     * @return string
     */
    public static function setNonce($action, $name = '_wpnonce', $referer = true, $echo = true)
    {
        $nonce_field = '<input type="hidden" name="' . esc_attr($name) . '" value="' . esc_attr(wp_create_nonce($action)) . '" />';

        if ($referer) {
            $nonce_field .= wp_referer_field(false);
        }

        if ($echo) {
            echo $nonce_field;
        }

        return $nonce_field;
    }

    /**
     * Check if the parameter is set
     *
     * @param  string $key
     * @return boolean
     */
    public static function getIsset($key)
    {
        return (isset($_GET[$key]) || isset($_POST[$key]));
    }

    /**
     * Load the multilanguage support from .mo
     */
    private function loadMultilanguage()
    {
        load_plugin_textdomain(_NXTLVL_NAME_, false, _NXTLVL_NAME_ . '/languages/');
    }

    /**
     * Hook the activate process
     */
   

    /**
     * Hook the deactivate process
     */
    public function strb_activate()
    {
        set_transient('strb_activate', true);

        //Install & Initialize
        self::install();
        //register_uninstall_hook(__FILE__,$this->strb_delete());           

    }
    // public static function strb_deactivate()
    // {  
    //     $users = get_users( array('meta_key'=>'strb_user_theme')) ;
    //     foreach ( $users as $user ) {   
    //         NXTLVL_Classes_Helpers_Tools::deleteUserMeta("strb_user_main_meta", $user->ID);
    //         NXTLVL_Classes_Helpers_Tools::deleteUserMeta("strb_user_theme", $user->ID);}
    //     delete_option('strb_options');
    //     //echo "Data removed successfully!";
    // } 
   


    /**
     * Empty the cache from other plugins
     */
    public static function emptyCache()
    {
        try {
            //////////////////////////////////////////////////////////////////////////////
            if (function_exists('w3tc_pgcache_flush')) {
                w3tc_pgcache_flush();
            }

            if (function_exists('w3tc_minify_flush')) {
                w3tc_minify_flush();
            }
            if (function_exists('w3tc_dbcache_flush')) {
                w3tc_dbcache_flush();
            }
            if (function_exists('w3tc_objectcache_flush')) {
                w3tc_objectcache_flush();
            }
            //////////////////////////////////////////////////////////////////////////////

            if (function_exists('wp_cache_clear_cache')) {
                wp_cache_clear_cache();
            }

            if (function_exists('rocket_clean_domain') && function_exists('rocket_clean_minify') && function_exists('rocket_clean_cache_busting')) {
                // Remove all cache files
                rocket_clean_domain();
                rocket_clean_minify();
                rocket_clean_cache_busting();
            }
            //////////////////////////////////////////////////////////////////////////////

            if (function_exists('apc_clear_cache')) {
                // Remove all apc if enabled
                apc_clear_cache();
            }
            //////////////////////////////////////////////////////////////////////////////

            if (class_exists('Cache_Enabler_Disk') && method_exists('Cache_Enabler_Disk', 'clear_cache')) {
                // clear disk cache
                Cache_Enabler_Disk::clear_cache();
            }
            //////////////////////////////////////////////////////////////////////////////

            if (class_exists('LiteSpeed_Cache')) {
                LiteSpeed_Cache::get_instance()->purge_all();
            }
            //////////////////////////////////////////////////////////////////////////////

            if (self::isPluginInstalled('hummingbird-performance/wp-hummingbird.php')) {
                do_action('wphb_clear_page_cache');
            }
            //////////////////////////////////////////////////////////////////////////////

            if (class_exists('WpeCommon')) {
                if (method_exists('WpeCommon', 'purge_memcached')) {
                    WpeCommon::purge_memcached();
                }
                if (method_exists('WpeCommon', 'clear_maxcdn_cache')) {
                    WpeCommon::clear_maxcdn_cache();
                }
                if (method_exists('WpeCommon', 'purge_varnish_cache')) {
                    WpeCommon::purge_varnish_cache();
                }
            }
            //////////////////////////////////////////////////////////////////////////////

            if (self::isPluginInstalled('sg-cachepress/sg-cachepress.php') && class_exists('Supercacher')) {
                if (method_exists('Supercacher', 'purge_cache') && method_exists('Supercacher', 'delete_assets')) {
                    Supercacher::purge_cache();
                    Supercacher::delete_assets();
                }
            }

            //Clear the fastest cache
            global $wp_fastest_cache;
            if (isset($wp_fastest_cache) && method_exists($wp_fastest_cache, 'deleteCache')) {
                $wp_fastest_cache->deleteCache();
            }
            //////////////////////////////////////////////////////////////////////////////
        } catch (Exception $e) {

        }
    }

    /**
     * Check if it's Ajax Call
     * @return bool
     */
    public static function isAjax()
    {
        return (defined('DOING_AJAX') && DOING_AJAX);
    }

    /**
     * Check if a plugin is installed
     *
     * @param  $name
     * @return bool
     */
    public static function isPluginInstalled($name)
    {
        if (empty(self::$allplugins)) {
            self::$allplugins = (array)get_option('active_plugins', array());

            if (is_multisite()) {
                self::$allplugins = array_merge(array_values(self::$allplugins), array_keys(get_site_option('active_sitewide_plugins')));
            }
        }

        if (!empty(self::$allplugins)) {
            return in_array($name, self::$allplugins, true);
        }

        return false;
    }

    /**
     * Check whether the theme is active.
     *
     * @param string $theme Theme folder/main file.
     *
     * @return boolean
     */
    public static function isThemeActive( $theme )
    {
        if (function_exists('wp_get_theme') ) {
            $themes = wp_get_theme();

            if (isset($themes->name) && stripos($themes->name, $theme) !== false) {
                return true;
            }

            if (isset($themes->template) && stripos($themes->template, $theme) !== false) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if frontend and user is logged in
     *
     * @return bool
     */
    public static function isFrontAdmin()
    {
        return (!is_admin() && (function_exists('is_user_logged_in') && is_user_logged_in()));
    }

    /**
     * Check if user is in dashboard
     *
     * @return bool
     */
    public static function isBackedAdmin()
    {
        return (is_admin() || is_network_admin());
    }

    /**
     * Check if the current website is an E-commerce website
     *
     * @return bool
     */
    public static function isEcommerce()
    {

        if(self::isPluginInstalled('woocommerce/woocommerce.php')) {
            return true;
        }

        $products = array('product', 'wpsc-product');
        $post_types = get_post_types(array('public' => true));

        foreach ($products as $type) {
            if (in_array($type, array_keys($post_types))) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if it's an AMP Endpoint
     *
     * @return bool|void
     */
    public static function isAMPEndpoint()
    {
        if (defined('AMPFORWP_AMP_QUERY_VAR')) {
            $url_path = trim(parse_url(add_query_arg(array()), PHP_URL_PATH), '/');
            $explode_path = explode('/', $url_path);
            if (AMPFORWP_AMP_QUERY_VAR === end($explode_path)) {
                return true;
            }
        }

        if (function_exists('is_amp_endpoint')) {
            return is_amp_endpoint();
        }

        if (function_exists('is_amp') && is_amp()) {
            return is_amp();
        }

        if (function_exists('ampforwp_is_amp_endpoint')) {
            return ampforwp_is_amp_endpoint();
        }

        return false;
    }

    /**
     * Check the user capability for the roles attached
     *
     * @param  $cap
     * @param  mixed ...$args
     * @return bool
     */
    public static function userCan($cap, ...$args )
    {

        if (current_user_can($cap, ...$args)) {
            return true;
        }

        $user = wp_get_current_user();
        if (count((array)$user->roles) > 1) {
            foreach ($user->roles as $role) {
                $role_object = get_role($role);
                if ($role_object->has_cap($cap)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Get the admin url for the specific age
     *
     * @param  string $page
     * @param  string $tab
     * @param  array  $args
     * @return string
     */
    public static function getAdminUrl($page, $tab = null, $args = array())
    {
        if (strpos($page, '.php')) {
            $url = admin_url($page);
        } else {
            $url = admin_url('admin.php?page=' . $page);
        }

        if (isset($tab) && $tab <> '') {
            $url .= '&tab=' . $tab;
        }

        if (!empty($args)) {
            if (strpos($url, '?') !== false) {
                $url .= '&';
            } else {
                $url .= '?';
            }
            $url .= join('&', $args);
        }

        return apply_filters('strb_menu_url', $url, $page, $tab, $args);
    }

    /**
     * Instantiates the WordPress filesystem.
     *
     * @static
     * @access public
     * @return object
     */
    public static function initFilesystem()
    {
        // The WordPress filesystem.
        global $wp_filesystem;

        if (! function_exists('WP_Filesystem') ) {
            include_once ABSPATH . 'wp-admin/includes/file.php';
        }

        WP_Filesystem();

        if (!$wp_filesystem->connect()) {
            add_filter( 'filesystem_method', function ($method) {
                return 'direct';
            }, 1
            );
            WP_Filesystem();
        }

        return $wp_filesystem;
    }

    /**
     * Get the first key of the given array without affecting
     * the internal array pointer
     */
    public static function arrayKeyFirst( array $arr ) {
        foreach ( $arr as $key => $value ) {
            return $key;
        }
    }
}
