<?php

/**
 * Custom functions that act independently of the theme templates
 *
 * Eventually, some of the functionality here could be replaced by core features.
 *
 * @package  Sparta
 * @since    1.0
 */
class Sparta_Helper
{
    /**
     * Variable to hold the initialization state.
     *
     * @var  boolean
     */
    protected static $initialized = false;

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

        // Register actions to do something.        
        add_action('body_class', array(__CLASS__, 'sparta_body_classes'));
        add_action('wp_head', array(__CLASS__, 'sparta_pingback_header'));

        add_filter('FHEE__content_espresso_events_details_template__the_content', array(__CLASS__, 'sparta_events_details_the_content'));
        add_filter('the_content_more_link', array(__CLASS__, 'sparta_modify_read_more_link'));

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


    public static function sparta_modify_read_more_link()
    {
        return '<a class="sparta-more-link" href="' . esc_url(get_permalink()) . '"><span>' . esc_html__('Read More', 'sparta') . '</span></a>';
    }

    /**
     * Adds custom classes to the array of body classes.
     *
     * @param array $classes Classes for the body element.
     * @return array
     */
    public static function sparta_body_classes($classes)
    {
        global $post;

        if (is_page()):
            $meta_htrans = esc_html(get_post_meta($post->ID, 'univer_page_header_trans', true));
            if ($meta_htrans == 'yes'):
                $classes[] = 'meta-htrans';
            endif;
            $page_meta_no_padding_top = esc_html(get_post_meta($post->ID, 'univer_no_padding_top', true));
            $page_meta_no_padding_bottom = esc_html(get_post_meta($post->ID, 'univer_no_padding_bottom', true));
            if ($page_meta_no_padding_top == 'yes'):
                $classes[] = 'page-pdt0';
            endif;
            if ($page_meta_no_padding_bottom == 'yes'):
                $classes[] = 'page-pdb0';
            endif;
        endif;

        if (is_multi_author()) :
            $classes[] = 'group-blog';
        endif;

        // Adds a class of hfeed to non-singular pages.
        if (!is_singular()) :
            $classes[] = 'hfeed';
        endif;


        return $classes;
    }

    /**
     * Add a pingback url auto-discovery header for singularly identifiable articles.
     */
    public static function sparta_pingback_header()
    {
        if (is_singular() && pings_open()) :
            echo '<link rel="pingback" href="', esc_url(get_bloginfo('pingback_url')), '">';
        endif;
    }

    /**
     * Get all registered sidebars.
     *
     * @return  array
     */
    public static function get_sidebars()
    {
        global $wp_registered_sidebars;

        // Get custom sidebars.
        $custom_sidebars = get_option('sparta_theme_sidebars');

        // Prepare output.
        $output = array();

        if (is_customize_preview()) :
            $output[] = esc_html__('-- Select Sidebar --', 'sparta');
        endif;

        if (!empty($wp_registered_sidebars)) :
            foreach ($wp_registered_sidebars as $sidebar) :
                $output[$sidebar['id']] = $sidebar['name'];
            endforeach;
        endif;

        if (!empty($custom_sidebars)) :
            foreach ($custom_sidebars as $sidebar) :
                $output[$sidebar['id']] = $sidebar['name'];
            endforeach;
        endif;

        return $output;
    }

    public static function sparta_date_meta()
    {
        $time_string = '%2$s';
        $time_string = sprintf($time_string,
            esc_attr(get_the_date('c')),
            esc_html(get_the_date()),
            esc_attr(get_the_modified_date('c')),
            esc_html(get_the_modified_date())
        );

        $date_format = get_option('date_format');
        ?>
        <div class="vk-blog-item-time">
            <ul class="vk-blog-item-time-sub">
                <?php
                if ($date_format === 'F j, Y') {
                    $timedate = explode(' ', $time_string);
                    echo '<li><span class="fjy">'. esc_attr($timedate[0]) .'</span></li>';
                    echo '<li><span>'. esc_attr($timedate[1]) . ' ' . esc_attr($timedate[2]) .'</span></li>';

                } elseif ($date_format === 'm/d/Y' || $date_format === 'd/m/Y') {
                    $timedate = explode('/', $time_string);
                    echo '<li><span>'. esc_attr($timedate[0]).'</span></li>';
                    echo '<li><span>'. esc_attr($timedate[1]) . '/' . esc_attr($timedate[2]).'</span></li>';
                } elseif ($date_format === 'Y-m-d') {
                    $timedate = explode('-', $time_string);
                    echo '<li><span class="ymd">'.esc_attr($timedate[0]).'</span></li>';
                    echo '<li><span>'.esc_attr($timedate[1]) . '-' . esc_attr($timedate[2]).'</span></li>';
                } elseif ($date_format === 'j M') {
                    $timedate = explode(' ', $time_string);
                    echo '<li><span>'.esc_attr($timedate[0]).'</span></li>';
                    echo '<li><span>'.esc_attr($timedate[1]).'</span></li>';

                } else {
                    echo '<li class="date-custom firstword">';
                    echo sprintf(
                        esc_html_x('%s', 'post date', 'sparta'), $time_string
                    );
                    echo '</li>';
                }
                ?>
            </ul>
        </div>
        <?php
    }

    public static function sparta_vk_post_meta_on()
    {
        $time_string = '<time class="entry-date published updated" datetime="%1$s">%2$s</time>';
        $time_string = sprintf($time_string,
            esc_attr(get_the_date('c')),
            esc_html(get_the_date()),
            esc_attr(get_the_modified_date('c')),
            esc_html(get_the_modified_date())
        );

        ?>
        <ul class="vk-list vk-list-inline vk-list-post-meta">
            <li><i class="vk-icon ti-calendar"></i>
                <?php echo sprintf(
                    esc_html_x('%s', 'post date', 'sparta'), $time_string
                ); ?></li>
            <?php
            $categories_list = get_the_category_list(esc_html__(', ', 'sparta'));
            if ($categories_list) {
                echo '<li><i class="vk-icon ti-folder"></i>';
                printf(esc_html__('%1$s', 'sparta'), $categories_list);
                echo '</li>';
            }
            ?>
            <?php
            if (get_the_author()) {
                echo '<li><i class="vk-icon ti-user"></i>';
                echo sprintf(
                    esc_html_x('%s', 'post author', 'sparta'),
                    '<span class="author-name">' . esc_html(get_the_author()) . '</span>'
                );

                echo '</li>';
            }
            ?>
        </ul>
        <?php
    }

    public static function sparta_vk_post_meta_full()
    {
        ?>
        <ul class="vk-list vk-list-inline vk-list-post-meta">
            <?php
            if (get_the_author()) {
                echo '<li><i class="vk-icon ti-user"></i>';
                echo sprintf(
                    esc_html_x('%s', 'post author', 'sparta'),
                    '<span class="author-name">' . esc_html(get_the_author()) . '</span>'
                );
                echo '</li>';
            }

            echo '<li class="comments-numb"><i class="vk-icon ti-comment"></i>';
            comments_number('0', '1', '%');

            echo '</li>';
            $categories_list = get_the_category_list(esc_html__(', ', 'sparta'));
            if ($categories_list) {
                echo '<li><i class="vk-icon ti-folder"></i>';
                printf(esc_html__('%1$s', 'sparta'), $categories_list);
                echo '</li>';
            }
            ?>
        </ul>
        <?php
    }

    /** override event */
    public static function sparta_events_details_the_content()
    {
        the_content();

    }


    /**
     * Display navigation to next/previous set of posts when applicable.
     */
    public static function sparta_paging_nav()
    {
        // Don't print empty markup if there's only one page.
        if ($GLOBALS['wp_query']->max_num_pages < 2) {
            return;
        }

        $paged = get_query_var('paged') ? intval(get_query_var('paged')) : 1;
        $pagenum_link = html_entity_decode(get_pagenum_link());
        $query_args = array();
        $url_parts = explode('?', $pagenum_link);

        if (isset ($url_parts[1])) {
            wp_parse_str($url_parts[1], $query_args);
        }

        $pagenum_link = remove_query_arg(array_keys($query_args), $pagenum_link);
        $pagenum_link = trailingslashit($pagenum_link) . '%_%';

        $format = $GLOBALS['wp_rewrite']->using_index_permalinks() && !strpos($pagenum_link, 'index.php') ? 'index.php/' : '';
        $format .= $GLOBALS['wp_rewrite']->using_permalinks() ? user_trailingslashit('page/%#%', 'paged') : '?paged=%#%';

        // Set up paginated links.
        $links = paginate_links(array(
            'sparta' => $pagenum_link,
            'format' => $format,
            'total' => $GLOBALS['wp_query']->max_num_pages,
            'current' => $paged,
            'mid_size' => 1,
            'add_args' => array_map('urlencode', $query_args),
            'prev_text' => wp_kses(__('<i class=\'fa fa-long-arrow-left\'></i>', 'sparta'), array('i' => array('class' => array()))),
            'next_text' => wp_kses(__('<i class=\'fa fa-long-arrow-right\'></i>', 'sparta'), array('i' => array('class' => array()))),
        ));

        if ($links) :
            ?>
            <div class="box-pagination">
                <nav aria-label="pagination">

                    <div class="pagination vk-pagination univer-pagination">
                        <?php echo wp_kses($links, array(
                            'a' => array(
                                'href' => array(),
                                'class' => array()
                            ),
                            'i' => array(
                                'class' => array()
                            ),
                            'span' => array(
                                'class' => array()
                            )
                        )); ?>
                    </div><!--/ .pagination -->
                </nav>
            </div>
        <?php
        endif;
    }

    /**
     * Render page loader.
     *
     * @return  string
     */
    public static function sparta_page_loader($output = NULL)
    {
        $type = get_theme_mod('sparta_effect_type', 'none');

        // Loader effects css
        $effects_css = get_theme_mod('sparta_css_animation_type', '1');
        $effects_image = get_theme_mod('sparta_page_effect_image', '');

        if ('css' == $type) {
            $output .= '<div class="pageloader">';
            $output .= '<div class="sparta-loader-' . esc_attr($effects_css) . '"><div class="sparta-loader"></div></div>';
            $output .= '</div>';
        } elseif ('image' == $type && !empty($effects_image)) {
            $output .= '<div class="pageloader"><div class="loader-img">';
            $output .= '<img src="' . esc_url($effects_image) . '" />';
            $output .= '</div></div>';
        }

        return apply_filters('sparta_page_loader', $output);
    }


    public static function sparta_posted_meta()
    {
        $time_string = '<time class="entry-date published updated" datetime="%1$s">%2$s</time>';

        if (get_the_time('U') !== get_the_modified_time('U')) {
            $time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time><time class="updated" datetime="%3$s">%4$s</time>';
        }

        $time_string = sprintf($time_string,
            esc_attr(get_the_date('c')),
            get_the_date(),
            esc_attr(get_the_modified_date('c')),
            get_the_modified_date()
        );

        $byline = sprintf(
            esc_html_x('%s', 'post author', 'sparta'),
            '<span class="author vcard"><a class="url fn n" href="' . esc_url(get_author_posts_url(get_the_author_meta('ID'))) . '">' . esc_html(get_the_author()) . '</a></span>'
        );

        echo '<span class="byline"> ' . $byline . '</span>';

        printf('<span class="posted-on"><i class="fa fa-calendar" aria-hidden="true"></i>%1$s <a href="%2$s" rel="bookmark">%3$s</a></span>',
            esc_html_x('', 'Used before publish date.', 'sparta'),
            esc_url(get_permalink()),
            $time_string
        );

    }

    public static function sparta_espresso_event_dates_detail($EVT_ID = 0, $date_format = '', $time_format = '', $echo = TRUE, $show_expired = NULL, $format = TRUE, $add_breaks = TRUE, $limit = NULL)
    {

        $date_format = !empty($date_format) ? $date_format : get_option('date_format');
        $time_format = !empty($time_format) ? $time_format : get_option('time_format');
        $date_format = apply_filters('FHEE__espresso_list_of_event_dates__date_format', $date_format);
        $time_format = apply_filters('FHEE__espresso_list_of_event_dates__time_format', $time_format);
        $datetimes = EEH_Event_View::get_all_date_obj($EVT_ID, $show_expired, FALSE, $limit);
        if (!$format) {
            return apply_filters('FHEE__espresso_list_of_event_dates__datetimes', $datetimes);
        }

        if (is_array($datetimes) && !empty($datetimes)) {
            global $post;
            $html = $format ? '<div class="sparta-sidebar-datetimes ee-clearfix">' : '';
            foreach ($datetimes as $datetime) {

                if ($datetime instanceof EE_Datetime) {

                    $timestart = str_replace(' ', '&nbsp;', $datetime->get_i18n_datetime('DTT_EVT_start', 'l, F j, Y @g:i a'));
                    $timeend = str_replace(' ', '&nbsp;', $datetime->get_i18n_datetime('DTT_EVT_end', 'l, F j, Y @g:i a'));

                    $datestart = explode("@", $timestart);
                    $datesend = explode('@', $timeend);

                    if (count($datestart) == 2) {
                        $html .= '<div class="datetimes-wap"><h3 class="starttime-icon">' . esc_html__('Start time', 'sparta') . '</h3>';
                        $html .= '<span>' . $datestart[1] . '</span>';
                        $html .= '<span>' . $datestart[0] . '</span>';
                        $html .= '</div>';
                    }

                    if (count($datesend) == 2) {
                        $html .= '<div class="datetimes-wap"><h3 class="endtime-icon">' . esc_html__('Finish time', 'sparta') . '</h3>';
                        $html .= '<span>' . $datesend[1] . '</span>';
                        $html .= '<span>' . $datesend[0] . '</span>';
                        $html .= '</div>';
                    }
                }
            }

            $html .= $format ? '</div>' : '';
        } else {
            $html = $format ? '<p><span class="dashicons dashicons-marker pink-text"></span>' . esc_html__('There are no upcoming dates for this event.', 'sparta') . '</p>' : '';
        }

        return $html;
    }


}