<?php
/**
 * @version    1.0
 * @package    Sparta
 * @author     Univer Team <support@univertheme.com>
 * @copyright  Copyright (C) 2014 Univertheme.com. All Rights Reserved.
 * @license    GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
 *
 */

/**
 * Plug additional setup supports.
 *
 * @package  Sparta
 * @since    1.0
 */
class Sparta_After_Setup
{
    /**
     * Variable to hold the initialization state.
     *
     * @var  boolean
     */
    protected static $initialized = false;

    protected static $plugins;

    protected static $tgmpa;

    /**
     * Initialize functions.
     *
     * @return  void
     */
    public static function initialize()
    {
        // Do nothing if start functions already initialized.
        if (self::$initialized) {
            return;
        }

        self::$tgmpa = isset($GLOBALS['tgmpa']) ? $GLOBALS['tgmpa'] : TGM_Plugin_Activation::get_instance();

        add_action('tgmpa_register', array(__CLASS__, 'register_required_plugins'));
        add_action('wp_ajax_uni_install_framework', array(__CLASS__, 'ajax_install_framework'));
        add_action('wp_ajax_uni_active_framework', array(__CLASS__, 'ajax_active_framework'));

        // Register actions to do something.
        add_action('after_setup_theme', array(__CLASS__, 'sparta_setup'));
        add_filter('wp_link_pages_args', array(__CLASS__, 'wp_link_pages_args_prevnext_add'));

        // Register actions to do something.
        add_action('widgets_init', array(__CLASS__, 'sparta_widgets_init'));

        add_action( 'enqueue_block_editor_assets', array(__CLASS__, 'sparta_enqueue_gutenberg') );

        // State that initialization completed.
        self::$initialized = true;
    }

    public static function sparta_enqueue_gutenberg() {

        $protocol = is_ssl() ? 'https' : 'http';
        $sparta_body_block_fonts = add_query_arg(
            array(
                'family' => urldecode('"Source Sans Pro":300,300i,400,400i,600,600i,700,700i,900,900i'),
                'subset' => urlencode('latin,latin-ext'),
            ),
            "{$protocol}://fonts.googleapis.com/css"
        );
        wp_enqueue_style('sparta-body-block-fonts', esc_url($sparta_body_block_fonts), false);


        $sparta_heading_block_fonts = add_query_arg(
            array(
                'family' => urldecode('"Playfair Display":400,400i,700,700i,900,900i'),
                'subset' => urlencode('latin,latin-ext'),
            ),
            "{$protocol}://fonts.googleapis.com/css"
        );
        wp_enqueue_style('sparta-heading-block-fonts', esc_url($sparta_heading_block_fonts), false);
    }


    /**
     * Register widget area.
     *
     * @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
     */
    public static function sparta_widgets_init()
    {
        register_sidebar(array(
            'name' => esc_html__('Sidebar', 'sparta'),
            'id' => 'sidebar-1',
            'description' => esc_html__('Add widgets here.', 'sparta'),
            'before_widget' => '<section id="%1$s" class="widget vk-box %2$s">',
            'after_widget' => '</section>',
            'before_title' => '<h3 class="widget-title">',
            'after_title' => '</h3>',
        ));

        register_sidebar(array(
            'name' => esc_html__('Woocommer Sidebar', 'sparta'),
            'id' => 'sidebar-woo',
            'description' => esc_html__('Add widgets here.', 'sparta'),
            'before_widget' => '<section id="%1$s" class="widget vk-box %2$s">',
            'after_widget' => '</section>',
            'before_title' => '<h3 class="widget-title">',
            'after_title' => '</h3>',
        ));

        register_sidebar(array(
            'name' => esc_html__('Site Flyout Sidebar', 'sparta'),
            'id' => 'site-flyout',
            'description' => esc_html__('Add widgets here.', 'sparta'),
            'before_widget' => '<section id="%1$s" class="widget vk-box %2$s">',
            'after_widget' => '</section>',
            'before_title' => '<h3 class="widget-title">',
            'after_title' => '</h3>',
        ));

        register_sidebar(array(
            'name' => esc_html__('Footer 1', 'sparta'),
            'id' => 'sidebar-footer-1',
            'description' => esc_html__('Add widgets here.', 'sparta'),
            'before_widget' => '<section id="%1$s" class="widget vk-box %2$s">',
            'after_widget' => '</section>',
            'before_title' => '<h3 class="widget-title">',
            'after_title' => '</h3>',
        ));

        register_sidebar(array(
            'name' => esc_html__('Footer 2', 'sparta'),
            'id' => 'sidebar-footer-2',
            'description' => esc_html__('Add widgets here.', 'sparta'),
            'before_widget' => '<section id="%1$s" class="widget vk-box %2$s">',
            'after_widget' => '</section>',
            'before_title' => '<h3 class="widget-title">',
            'after_title' => '</h3>',
        ));
        register_sidebar(array(
            'name' => esc_html__('Footer 3', 'sparta'),
            'id' => 'sidebar-footer-3',
            'description' => esc_html__('Add widgets here.', 'sparta'),
            'before_widget' => '<section id="%1$s" class="widget vk-box %2$s">',
            'after_widget' => '</section>',
            'before_title' => '<h3 class="widget-title">',
            'after_title' => '</h3>',
        ));
        register_sidebar(array(
            'name' => esc_html__('Footer 4', 'sparta'),
            'id' => 'sidebar-footer-4',
            'description' => esc_html__('Add widgets here.', 'sparta'),
            'before_widget' => '<section id="%1$s" class="widget vk-box %2$s">',
            'after_widget' => '</section>',
            'before_title' => '<h3 class="widget-title">',
            'after_title' => '</h3>',
        ));

        register_sidebar(array(
            'name' => esc_html__('Footer Bottom', 'sparta'),
            'id' => 'sidebar-footer-bottom',
            'description' => esc_html__('Add widgets here.', 'sparta'),
            'before_widget' => '<section id="%1$s" class="widget vk-box %2$s">',
            'after_widget' => '</section>',
            'before_title' => '<h3 class="widget-title">',
            'after_title' => '</h3>',
        ));
    }


    /**
     * Add prev and next links to a numbered link list
     */
    public static function wp_link_pages_args_prevnext_add($args)
    {
        global $page, $numpages, $more, $pagenow;

        if (!$args['next_or_number'] == 'next_and_number')
            return $args; # exit early

        $args['next_or_number'] = 'number'; # keep numbering for the main part       


        if (!$more)
            return $args; # exit early

        if ($page - 1) # there is a previous page
            $args['before'] .= _wp_link_page($page - 1)
                . $args['link_before'] . $args['previouspagelink'] . $args['link_after'] . '</a>';

        if ($page < $numpages) # there is a next page
            $args['after'] = _wp_link_page($page + 1)
                . $args['link_before'] . $args['nextpagelink'] . $args['link_after'] . '</a>'
                . $args['after'];


        return $args;
    }

    function remove_core_updates()
    {
        global $wp_version;
        return (object)array('last_checked' => time(), 'version_checked' => $wp_version,);
    }

    /**
     * Sets up theme defaults and registers support for various WordPress features.
     *
     * Note that this function is hooked into the after_setup_theme hook, which
     * runs before the init hook. The init hook is too late for some features, such
     * as indicating support for post thumbnails.
     */
    public static function sparta_setup()
    {
        /*
         * Make theme available for translation.
         * Translations can be filed in the /languages/ directory.
         * If you're building a theme based on Y Te Nam Hai, use a find and replace
         * to change 'sparta' to the name of your theme in all the template files.
         */
        load_theme_textdomain('sparta', get_parent_theme_file_path() . '/languages');

        // Add default posts and comments RSS feed links to head.
        add_theme_support('automatic-feed-links');

        /*
         * Let WordPress manage the document title.
         * By adding theme support, we declare that this theme does not use a
         * hard-coded <title> tag in the document head, and expect WordPress to
         * provide it for us.
         */
        add_theme_support('title-tag');

        /*
         * Switch default core markup for search form, comment form, and comments
         * to output valid HTML5.
         */
        add_theme_support('html5', array(
            'search-form',
            'comment-form',
            'comment-list',
            'gallery',
            'caption',
        ));

        // Set up the WordPress core custom background feature.
        add_theme_support('custom-background', apply_filters('sparta_custom_background_args', array(
            'default-color' => 'ffffff',
            'default-image' => '',
        )));

        // Add theme support for selective refresh for widgets.
        add_theme_support('customize-selective-refresh-widgets');

        /**
         * Register admin menu locations.
         * This theme uses wp_nav_menu() in one location.
         */

        register_nav_menus(array(
            'main-menu' => esc_html__('Primary', 'sparta'),
            'footer' => esc_html__('Footer Copyright', 'sparta'),
        ));

        add_theme_support('post-formats', array(
            'aside',
            'image',
            'video',
            'quote',
            'link',
            'gallery',
            'status',
            'audio',
            'chat'
        ));
        add_theme_support('post-thumbnails');

        add_image_size('sparta-thumb-grid', 380, 270, array('center', 'center'));
        add_image_size('sparta-thumb-list', 500, 420, array('center', 'center'));
        add_image_size('sparta-thumb-square', 320, 320, array('center', 'center'));

        add_theme_support('custom-header', apply_filters('sparta_custom_header_args', array(
            'default-image' => '',
            'default-text-color' => '000000',
            'width' => 1000,
            'height' => 250,
            'flex-height' => true,
            'wp-head-callback' => array(__CLASS__, 'sparta_header_style'),
            0
        )));
        $GLOBALS['content_width'] = apply_filters('sparta_content_width', 640);

        // Add support for editor styles.
        add_theme_support( 'editor-styles' );

        // Enqueue editor styles.
        add_editor_style( 'style-editor.css' );

        add_theme_support( 'wp-block-styles' );
        add_theme_support( 'align-wide' );

    }

    /**
     * Styles the header image and text displayed on the blog.
     *
     * @see sparta_custom_header_setup().
     */

    public static function sparta_header_style()
    {
        $header_text_color = get_header_textcolor();

        /*
         * If no custom options for text are set, let's bail.
         * get_header_textcolor() options: Any hex value, 'blank' to hide text. Default: add_theme_support( 'custom-header' ).
         */
        if (get_theme_support('custom-header', 'default-text-color') === $header_text_color) {
            return;
        }
        ?>
        <style type="text/css">
            <?php
                // Has the text been hidden?
                if ( ! display_header_text() ) :
            ?>
            .site-title,
            .site-description {
                position: absolute;
                clip: rect(1px, 1px, 1px, 1px);
            }

            <?php
                // If the user has set a custom color for the text use that.
                else :
            ?>
            .site-title a,
            .site-description {
                color: #<?php echo esc_attr( $header_text_color ); ?>;
            }

            <?php endif; ?>
        </style>
        <?php
    }

    /*tgm*/
    public static function register_required_plugins()
    {
        if (!isset(self::$plugins)) {
            self::$plugins = apply_filters('core_tgmpa_array', array(
                array(
                    'name' => 'Univer Core',
                    'slug' => 'univercore',
                    'required' => true,
                    'version' => '',
                    'source' => get_parent_theme_file_path() . '/inc/plugins/univercore.zip',
                ),
            ));
        }

        $config = array(
            'id' => 'sparta',                 // Unique ID for hashing notices for multiple instances of TGMPA.
            'default_path' => '',                      // Default absolute path to bundled plugins.
            'menu' => 'tgmpa-install-plugins', // Menu slug.
            'has_notices' => true,                    // Show admin notices or not.
            'dismissable' => true,                    // If false, a user cannot dismiss the nag message.
            'dismiss_msg' => '',                      // If 'dismissable' is false, this message will be output at top of nag.
            'is_automatic' => false,                   // Automatically activate plugins after installation or not.
            'message' => '',                      // Message to output right before the plugins table.
        );

        tgmpa(self::$plugins, $config);
    }

    public static function ajax_install_framework()
    {
        if (!check_ajax_referer('uni_nonce', 'wpnonce') || empty($_POST['slug'])) {
            exit(0);
        }

        $json = array();
        $tgmpa_url = self::$tgmpa->get_tgmpa_url();

        if ($_POST['slug'] === 'install') {
            $json = array(
                'url' => $tgmpa_url,
                'plugin' => array('univercore'),
                'tgmpa-page' => self::$tgmpa->menu,
                '_wpnonce' => wp_create_nonce('bulk-plugins'),
                'action' => 'tgmpa-bulk-install',
                'action2' => -1,
                'message' => esc_html__('Installing', 'sparta'),
            );
        } elseif ($_POST['slug'] === 'active') {
            $json = array(
                'url' => $tgmpa_url,
                'plugin' => array('univercore'),
                'tgmpa-page' => self::$tgmpa->menu,
                '_wpnonce' => wp_create_nonce('bulk-plugins'),
                'action' => 'tgmpa-bulk-activate',
                'action2' => -1,
                'message' => esc_html__('Activating', 'sparta'),
            );
        }

        if ($json) {
            wp_send_json($json);
        } else {
            wp_send_json(array('done' => 1, 'message' => esc_html__('Success', 'sparta')));
        }

        exit;
    }

}