<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       http://xplodedthemes.com
 * @since      1.0.0
 *
 * @package    XT_Woo_Floating_Cart
 * @subpackage XT_Woo_Floating_Cart/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    XT_Woo_Floating_Cart
 * @subpackage XT_Woo_Floating_Cart/welcome
 * @author     XplodedThemes <helpdesk@xplodedthemes.com>
 */
class XT_Woo_Floating_Cart_Welcome {

    /**
     * Core class reference.
     *
     * @since    1.0.0
     * @access   private
     * @var      XT_Woo_Floating_Cart    core    Core Class
     */
    private $core;

    public $sections = [];
    public $default_section;


    /**
     * Initialize the class and set its properties.
     *
     * @since    1.0.0
     * @param    obj    $core    Plugin core class.
     */
    public function __construct( &$core, $sections ) {

        $this->core = $core;
        $this->sections = $sections;

        if(!empty($this->sections)) {
            $this->default_section = current($this->sections)['id'];
        }

        if(!empty($_GET['section'])) {
            $this->active_section = esc_html($_GET['section']);
        }else{
            $this->active_section = $this->default_section;
        }

        $this->core->plugin_loader()->add_action( 'admin_menu', $this, 'settings_menu', 1);
        $this->core->plugin_loader()->add_action( 'admin_body_class', $this, 'admin_body_class', 1);
        $this->core->plugin_loader()->add_action( 'admin_enqueue_scripts', $this, 'enqueue_styles', 1);
        $this->core->plugin_loader()->add_action( 'admin_enqueue_scripts', $this, 'enqueue_scripts', 1);
        $this->core->plugin_loader()->add_filter( 'plugin_action_links_' . plugin_basename( $this->core->plugin_file() ), $this, 'action_links', 99);

    }

    function admin_body_class( $classes ) {

        $screen = get_current_screen();

        if(!empty($screen) && strpos($screen->base, $this->core->plugin_slug()) !== false) {
            $classes .= ' xt-welcome-page';
        }

        return $classes;
    }

    /**
     * Register the stylesheets for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueue_styles() {

        /**
         * This function is provided for demonstration purposes only.
         *
         * An instance of this class should be passed to the run() function
         * defined in XT_Woo_Floating_Cart_Loader as all of the hooks are defined
         * in that particular class.
         *
         * The XT_Woo_Floating_Cart_Loader will then create the relationship
         * between the defined hooks and the functions defined in this
         * class.
         */

        wp_enqueue_style( $this->core->plugin_slug('welcome'), $this->core->plugin_url( 'admin/welcome/assets/css', 'welcome.css'), array(), $this->core->plugin_version(), 'all' );

    }

    /**
     * Register the JavaScript for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueue_scripts() {

        /**
         * This function is provided for demonstration purposes only.
         *
         * An instance of this class should be passed to the run() function
         * defined in XT_Woo_Floating_Cart_Loader as all of the hooks are defined
         * in that particular class.
         *
         * The XT_Woo_Floating_Cart_Loader will then create the relationship
         * between the defined hooks and the functions defined in this
         * class.
         */

        wp_enqueue_script( $this->core->plugin_slug(), $this->core->plugin_url( 'admin/welcome/assets/js', 'welcome'.$this->core->script_suffix.'.js'), array( 'jquery' ), $this->core->plugin_version(), false );

    }

    function action_links( $links ) {

        foreach($this->sections as $i => $section) {

            if(empty($section['action_link'])) {
                continue;
            }

            $id = $i > 0 ? $section['id'] : '';
            $url = $this->get_section_url($id);

            $action_link = $section['action_link'];

            if(is_array($action_link)) {

                $url = !empty($action_link['url']) ? $action_link['url'] : $url;
                $title = !empty($action_link['title']) ? $action_link['title'] : $section['title'];
                $color = !empty($action_link['color']) ? $action_link['color'] : '';

            }else{

                $title = $section['title'];
                $color = '';
            }

            $links[] = '<a style="color: '.$color.'" href="'. esc_url( $url ) .'">'.$title.'</a>';

        }

        return $links;
    }

    public function settings_menu() {

        add_menu_page( $this->core->plugin()->name, $this->core->plugin()->menu_name, 'manage_options', $this->core->plugin_slug(), array($this, 'settings_page'), $this->core->plugin_icon() );

        foreach($this->sections as $section) {

            $id = $section['id'];
            $title = !empty($section['menu_title']) ? $section['menu_title'] : $section['title'];
            $show_menu = $section['show_menu'];
            $redirect = !empty($section['external']) ? $section['external'] : '';
            $redirect = !empty($section['redirect']) ? $section['redirect'] : $redirect;
            $submenu_parent = $show_menu ? $this->core->plugin_slug() : null;

            if($id == $this->default_section) {
                add_submenu_page( $submenu_parent, $title, $title, 'manage_options', $this->core->plugin_slug(), array($this, 'settings_page'));
            }else{
                add_submenu_page( $submenu_parent, $title, $title, 'manage_options', $this->core->plugin_slug($id), function() use ($id, $redirect) {

                    if(!$redirect) {
                        $this->active_section = $id;
                        $this->settings_page();
                    }else{
                        wp_redirect($redirect);
                        exit;
                    }
                });
            }
        }
    }


    public function settings_page() {

        if ( !current_user_can( 'manage_options' ) )  {
            wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
        }
        ?>
        <div class="wrap about-wrap <?php echo $this->core->plugin_slug("welcome-wrap"); ?>">

            <div class="xt-welcome-header">

                <div class="xt-version">
                    V.<?php echo $this->core->plugin_version(); ?>
                    <?php if(!$this->core->fs()->can_use_premium_code__premium_only()): ?><em>LITE VERSION</em><?php endif; ?>
                </div>

                <div class="about-text">
                    <img class="xt-logo" src="<?php echo esc_url( $this->core->plugin_url('admin/assets/images', 'logo.png' )); ?>" class="image-50" />
                </div>

                <script type="text/javascript" src="//xplodedthemes.com/widgets/xt-follow/xt-follow-min.js"></script>
                <script type="text/javascript">
                    XT_FOLLOW.init();
                </script>

            </div>

            <?php $this->show_nav(); ?>

            <div class="xt-welcome-section xt-<?php echo $this->get_section_id(); ?>-section">

                <?php $this->show_section(); ?>

            </div>

        </div>
        <?php
    }

    public function show_nav() {

        echo '<div class="nav-tab-wrapper">';

        foreach($this->sections as $section) {

            $id = $section['id'];
            $url = $this->get_section_url($id);
            $featured = !empty($section['featured']);

            $target = '_self';

            if(!empty($section['external'])) {
                $url = $section['external'];
                $target = '_blank';
            }

            if(!empty($section['redirect'])) {
                $url = $section['redirect'];
                $target = '_self';
            }

            if(!empty($section['target'])) {
                $target = $section['target'];
            }

            $classes = array();

            if($this->is_section($id)) {
                $classes[] = 'nav-tab-active';
            }

            if($featured) {
                $classes[] = 'nav-tab-featured';
            }

            echo '<a href="'.$url.'" class="nav-tab '.implode(" ", $classes).'" target="'.$target.'">'.$section['title'].'</a>';
        }

        echo '</div>';
    }

    public function show_section() {

        $section = $this->get_section();
        $id = $section['id'];
        $url = $this->get_section_url($id, array('nocache' => '1')) ;

        if(!empty($section['content'])) {
            $content = $section['content'];

            if (!empty($content['show_refresh'])) {

                echo '
                <a class="xt-refresh-link" href="' . $url . '">
                    <span class="dashicons dashicons-image-rotate"></span> Refresh
                </a>';
            }

            if (!empty($content['title'])) {

                echo '<h3>' . $content['title'] . '</h3>';
            }

            if ($content['type'] === 'template') {

                if(file_exists($content['template'])) {
                    include($content['template']);
                }

            } else if ($content['type'] === 'function') {

                echo $content['function']();

            } else if ($content['type'] === 'html') {

                echo $content['html'];

            } else if ($content['type'] === 'url') {

                $json_decode = !empty($content['json']);
                echo $this->remote_get($content['url'], $json_decode);

            } else if ($content['type'] === 'frame') {

                echo '<iframe src="'.$content['frame'].'" frameborder="no" style="min-height:2000px;width:100%"></iframe>';
            }
        }
    }

    public function is_section($section) {

        return $this->active_section === $section;
    }


    public function get_url() {

        return esc_url($this->core->plugin_admin_url());
    }

    public function get_section() {

        $section_key = array_search($this->active_section, array_column($this->sections, 'id'));
        $section = $this->sections[$section_key];

        return $section;
    }

    public function get_section_id() {

        return $this->active_section;
    }

    public function get_section_url($section = '', $args = array()) {

        if($section == $this->default_section) {
            $section = '';
        }
        return esc_url($this->core->plugin_admin_url($section, $args));
    }

    public function remote_get( $url, $json_decode = false ) {

        $cache_key = md5($url);

        $content = get_site_transient( $cache_key );

        if ( $content === false || !empty($_GET['nocache']) !== null ) {

            if(!empty($_GET['nocache'])) {
                $url = add_query_arg('nocache', $_GET['nocache'], $url);
            }

            $response = wp_remote_get( $url, array( 'sslverify' => false ) );

            // Stop here if the is an error.
            if ( is_wp_error( $response ) ) {

                $content = '';

                // Set temporary transient.
                set_site_transient($cache_key, $content, MINUTE_IN_SECONDS );

            }else{

                // Retrieve data from the body and decode json format.
                $content = wp_remote_retrieve_body( $response );

                set_site_transient($cache_key, $content, DAY_IN_SECONDS );
            }

        }

        if($json_decode) {
            $content = json_decode($content , true );
        }

        return $content;
    }
}
