<?php
/**
 * Custom template tags for this theme
 *
 * Eventually, some of the functionality here could be replaced by core features.
 *
 * @package United Blog
 */
/**
 * Displays the site logo, either text or image.
 *
 * @param array $args Arguments for displaying the site logo either as an image or text.
 * @param bool $display Display or return the HTML.
 * @return string Compiled HTML based on our arguments.
 * @since United Blog 1.0
 *
 */
function united_blog_site_logo($args = array(), $display = true)
{
    $logo = get_custom_logo();
    $site_title = get_bloginfo('name');
    $contents = '';
    $classname = '';
    $defaults = array(
        'logo' => '%1$s<span class="screen-reader-text">%2$s</span>',
        'logo_class' => 'site-logo',
        'title' => '<a href="%1$s">%2$s</a>',
        'title_class' => 'site-title',
        'home_wrap' => '<h1 class="%1$s">%2$s</h1>',
        'single_wrap' => '<div class="%1$s faux-heading">%2$s</div>',
        'condition' => (is_front_page() || is_home()) && !is_page(),
    );
    $args = wp_parse_args($args, $defaults);
    /**
     * Filters the arguments for `united_blog_site_logo()`.
     *
     * @param array $args Parsed arguments.
     * @param array $defaults Function's default arguments.
     * @since United Blog 1.0
     *
     */
    $args = apply_filters('united_blog_site_logo_args', $args, $defaults);
    if (has_custom_logo()) {
        $contents = sprintf($args['logo'], $logo, esc_html($site_title));
        $classname = $args['logo_class'];
    } else {
        $contents = sprintf($args['title'], esc_url(get_home_url(null, '/')), esc_html($site_title));
        $classname = $args['title_class'];
    }
    $wrap = $args['condition'] ? 'home_wrap' : 'single_wrap';
    $html = sprintf($args[$wrap], $classname, $contents);
    /**
     * Filters the arguments for `united_blog_site_logo()`.
     *
     * @param string $html Compiled HTML based on our arguments.
     * @param array $args Parsed arguments.
     * @param string $classname Class name based on current view, home or single.
     * @param string $contents HTML for site title or logo.
     * @since United Blog 1.0
     *
     */
    $html = apply_filters('united_blog_site_logo', $html, $args, $classname, $contents);
    if (!$display) {
        return $html;
    }
    echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}

/**
 * Displays the site description.
 *
 * @param bool $display Display or return the HTML.
 * @return string The HTML to display.
 * @since United Blog 1.0
 *
 */
function united_blog_site_description($display = true)
{
    $description = get_bloginfo('description');
    if (!$description) {
        return;
    }
    $wrapper = '<div class="site-description">%s</div><!-- .site-description -->';
    $html = sprintf($wrapper, esc_html($description));
    /**
     * Filters the HTML for the site description.
     *
     * @param string $html The HTML to display.
     * @param string $description Site description via `bloginfo()`.
     * @param string $wrapper The format used in case you want to reuse it in a `sprintf()`.
     * @since United Blog 1.0
     *
     */
    $html = apply_filters('united_blog_site_description', $html, $description, $wrapper);
    if (!$display) {
        return $html;
    }
    echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}

/**
 * Filters classes of wp_list_pages items to match menu items.
 *
 * Filter the class applied to wp_list_pages() items with children to match the menu class, to simplify.
 * styling of sub levels in the fallback. Only applied if the match_menu_classes argument is set.
 *
 * @param string[] $css_class An array of CSS classes to be applied to each list item.
 * @param WP_Post $page Page data object.
 * @param int $depth Depth of page, used for padding.
 * @param array $args An array of arguments.
 * @return array CSS class names.
 * @since United Blog 1.0
 *
 */
function united_blog_filter_wp_list_pages_item_classes($css_class, $page, $depth, $args)
{
    // Only apply to wp_list_pages() calls with match_menu_classes set to true.
    $match_menu_classes = isset($args['match_menu_classes']);
    if (!$match_menu_classes) {
        return $css_class;
    }
    // Add current menu item class.
    if (in_array('current_page_item', $css_class, true)) {
        $css_class[] = 'current-menu-item';
    }
    // Add menu item has children class.
    if (in_array('page_item_has_children', $css_class, true)) {
        $css_class[] = 'menu-item-has-children';
    }
    return $css_class;
}

add_filter('page_css_class', 'united_blog_filter_wp_list_pages_item_classes', 10, 4);
/**
 * Adds a Sub Nav Toggle to the Expanded Menu and Mobile Menu.
 *
 * @param stdClass $args An object of wp_nav_menu() arguments.
 * @param WP_Post $item Menu item data object.
 * @return stdClass An object of wp_nav_menu() arguments.
 * @since United Blog 1.0
 *
 */
function united_blog_add_sub_toggles_to_main_menu($args, $item)
{
    // Add sub menu toggles to the Expanded Menu with toggles.
    if (isset($args->show_toggles) && $args->show_toggles) {
        // Wrap the menu item link contents in a div, used for positioning.
        $args->before = '<div class="ancestor-wrapper">';
        $args->after = '';
        // Add a toggle to items with children.
        if (in_array('menu-item-has-children', $item->classes, true)) {
            $toggle_target_string = '.menu-modal .menu-item-' . $item->ID . ' > .sub-menu';
            $toggle_duration = united_blog_toggle_duration();
            // Add the sub menu toggle.
            $args->after .= '<button class="toggle sub-menu-toggle" data-toggle-target="' . $toggle_target_string . '" data-toggle-type="slidetoggle" data-toggle-duration="' . absint($toggle_duration) . '" aria-expanded="false"><span class="screen-reader-text">' .
                /* translators: Hidden accessibility text. */
                __('Show sub menu', 'united-blog') .
                '</span>' . united_blog_get_theme_svg('chevron-down') . '</button>';
        }
        // Close the wrapper.
        $args->after .= '</div><!-- .ancestor-wrapper -->';
        // Add sub menu icons to the primary menu without toggles.
    } elseif ('primary' === $args->theme_location) {
        if (in_array('menu-item-has-children', $item->classes, true)) {
            $args->after = '<span class="icon"></span>';
        } else {
            $args->after = '';
        }
    }
    return $args;
}

add_filter('nav_menu_item_args', 'united_blog_add_sub_toggles_to_main_menu', 10, 2);
/**
 * Toggles animation duration in milliseconds.
 *
 * @return int Duration in milliseconds
 * @since United blog 1.0
 *
 */
function united_blog_toggle_duration()
{
    /**
     * Filters the animation duration/speed used usually for submenu toggles.
     *
     * @param int $duration Duration in milliseconds.
     * @since United blog 1.0
     *
     */
    $duration = apply_filters('united_blog_toggle_duration', 250);
    return $duration;
}

if (!function_exists('united_blog_posted_on')) :
    /**
     * Prints HTML with meta information for the current post-date/time.
     */
    function united_blog_posted_on()
    {
        $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')),
            esc_html(get_the_date()),
            esc_attr(get_the_modified_date('c')),
            esc_html(get_the_modified_date())
        );
        $archive_year = get_the_time('Y');
        $archive_month = get_the_time('m');
        $archive_day = get_the_time('d');
        $posted_on = sprintf(
        /* translators: %s: post date. */
            esc_html_x('Posted on %s', 'post date', 'united-blog'),
            '<a href="' . esc_url(get_day_link($archive_year, $archive_month, $archive_day)) . '" rel="bookmark">' . $time_string . '</a>'
        );
        echo '<span class="posted-on">' . $posted_on . '</span>'; // WPCS: XSS OK.
    }
endif;
if (!function_exists('united_blog_posted_by')) :
    /**
     * Prints HTML with meta information for the current author.
     */
    function united_blog_posted_by()
    {
        $byline = sprintf(
        /* translators: %s: post author. */
            esc_html_x('by %s', 'post author', 'united-blog'),
            '<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>'; // WPCS: XSS OK.
    }
endif;
if (!function_exists('united_blog_entry_tags')) :
    /**
     * Prints HTML with meta information for the categories, tags and comments.
     */
    function united_blog_entry_tags()
    {
        // Hide category and tag text for pages.
        if ('post' === get_post_type()) {
            /* translators: used between list items, there is a space after the comma */
            $tags_list = get_the_tag_list('', esc_html_x(', ', 'list item separator', 'united-blog'));
            if ($tags_list) {
                /* translators: 1: list of tags. */
                printf('<span class="tags-links">' . esc_html__('Tagged In %1$s', 'united-blog') . '</span>', $tags_list); // WPCS: XSS OK.
            }
        }
    }
endif;
if (!function_exists('united_blog_post_categories')) :
    /**
     * Display post categories.
     *
     * @param $show_color Show Categories Display Style.
     * @param $limit Get all/partial categories.
     *
     * @since 1.0.0
     */
    function united_blog_post_categories($show_color = null, $limit = 0)
    {
        $categories = get_the_category(get_the_ID());
        if (empty($categories)) {
            return;
        }
        if (0 != $limit) {
            $limit = absint($limit);
            if (count($categories) > $limit) {
                $categories = array_slice($categories, 0, $limit);
            }
        }
        if (null == $show_color) {
            $show_color = 'none';
        }
        $wrapper_class = $show_color;
        ?>
        <div class="entry-categories <?php echo esc_attr($wrapper_class); ?>">
            <span class="screen-reader-text"><?php esc_html_e('Categories', 'united-blog'); ?></span>
            <?php
            $style_attr = '';
            if ('none' != $show_color) :
                if ('display_as_color' == $show_color) :
                    $style_attr = ' style="color:value;"';
                else :
                    $style_attr = ' style="background-color:value;"';
                endif;
            endif;
            global $wp_rewrite;
            $rel = (is_object($wp_rewrite) && $wp_rewrite->using_permalinks()) ? 'rel="category tag"' : 'rel="category"';
            $separator = ' ';
            $thelist = '';
            $i = 0;
            foreach ($categories as $category) {
                $class = '';
                if (0 < $i) {
                    $thelist .= $separator;
                }
                $build_style_attr = '';
                if ('none' != $show_color) {
                    $color = get_term_meta($category->term_id, 'category_color', true);
                    if ($color) {
                        $build_style_attr = str_replace('value', $color, $style_attr);
                    } else {
                        $build_style_attr = '';
                    }
                    if ('display_as_bg' == $show_color) :
                        $class = ' class="category-background-color"';
                    endif;
                }
                $thelist .= '<a href="' . esc_url(get_category_link($category->term_id)) . '" ' . $rel . $class . $build_style_attr . '>' . $category->name . '</a>';
                ++$i;
            }
            echo $thelist;
            ?>
        </div><!-- .entry-categories -->
        <?php
    }
endif;
if (!function_exists('united_blog_post_meta_info')) :
    /**
     * Display post meta info.
     *
     * @param array $enabled_post_meta Enabled Post Meta.
     * @param string $settings Additinal Settings
     *
     * @since 1.0.0
     */
    function united_blog_post_meta_info($enabled_post_meta = array(), $settings = array())
    {
        if ($enabled_post_meta && !empty($enabled_post_meta)) :
            // Filter out valid metas.
            $valid_post_metas = array('author', 'date', 'comment', 'favorites', 'read_time');
            $enabled_post_meta = array_intersect($enabled_post_meta, $valid_post_metas);
            $enabled_post_meta = array_values($enabled_post_meta);
            if (!empty($enabled_post_meta)) :
                $wrapper_class = '';
                if (empty($settings) || !is_array($settings)) {
                    $settings = array(
                        'date_format' => 'format_2',
                        'author_image' => false,
                        'show_icons' => true,
                    );
                } else {
                    if (!isset($settings['date_format'])) {
                        $settings['date_format'] = 'format_2';
                    }
                    if (!isset($settings['author_image'])) {
                        $settings['author_image'] = false;
                    }
                    if (!isset($settings['show_icons'])) {
                        $settings['show_icons'] = true;
                    }
                }
                global $post;
                ?>
                <div class="entry-meta entry-meta-list<?php echo esc_attr($wrapper_class); ?>">
                    <?php
                    // Author.
                    $author_image = get_avatar(get_the_author_meta('ID'), 30, '', '', array('class' => 'author-avatar-image'));
                    if (in_array('author', $enabled_post_meta)) {
                        ?>
                        <div class="meta-list-item post-author">
                            <?php
                            $author_url = get_author_posts_url(get_the_author_meta('ID'));
                            $author_name = get_the_author_meta('display_name');
                            if ($settings['author_image']) {
                                ?>
                                <?php echo wp_kses_post($author_image); ?>
                                <a href="<?php echo esc_url($author_url); ?>" class="text-decoration-reset">
                                    <?php
                                    echo esc_html($author_name);
                                    ?>
                                </a>
                                <?php
                            } else {
                                printf(
                                    __('By %s', 'united-blog'),
                                    '<a href="' . esc_url($author_url) . '" class="text-decoration-reset">' . esc_html($author_name) . '</a>'
                                );
                            }
                            ?>
                        </div>
                        <?php
                    }
                    // Date.
                    if (in_array('date', $enabled_post_meta)) {
                        ?>
                        <div class="meta-list-item post-date">
                            <?php
                            if (true == $settings['show_icons']) :
                                united_blog_the_theme_svg('calendar');
                            endif;
                            ?>
                            <?php
                            if ('format_1' == $settings['date_format']) {
                                echo esc_html(human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ' . __('ago', 'united-blog'));
                            } else {
                                echo esc_html(get_the_date());
                            }
                            ?>
                        </div>
                        <?php
                    }
                    // Comment.
                    if (in_array('comment', $enabled_post_meta)) {
                        if (!post_password_required() && (comments_open() || get_comments_number())) {
                            ?>
                            <div class="meta-list-item post-comment">
                                <?php
                                $number = get_comments_number(get_the_ID());
                                if (0 == $number) {
                                    $respond_link = get_permalink() . '#respond';
                                    $comment_link = apply_filters('respond_link', $respond_link, get_the_ID());
                                } else {
                                    $comment_link = get_comments_link();
                                }
                                ?>
                                <?php
                                if (true == $settings['show_icons']) :
                                    united_blog_the_theme_svg('calendar');
                                    ?>
                                    <a href="<?php echo esc_url($comment_link); ?>" class="text-decoration-reset">
                                        <?php
                                        printf(
                                        /* translators: %s: Comment count number. */
                                            esc_html(_nx('%s comment', '%s comments', $number, 'Comments title', 'united-blog')),
                                            esc_html(number_format_i18n($number))
                                        );
                                        ?>
                                    </a>
                                <?php
                                elseif ('1' == $number) :
                                    ?>
                                    <a href="<?php echo esc_url($comment_link); ?>" class="text-decoration-reset">
                                        <?php
                                        esc_html_e('1 comment', 'united-blog');
                                        ?>
                                    </a>
                                <?php
                                else :
                                    ?>
                                    <a href="<?php echo esc_url($comment_link); ?>" class="text-decoration-reset">
                                        <?php
                                        printf(
                                        /* translators: %s: Comment count number. */
                                            esc_html(_nx('%s comment', '%s comments', $number, 'Comments title', 'united-blog')),
                                            esc_html(number_format_i18n($number))
                                        );
                                        ?>
                                    </a>
                                <?php endif;
                                ?>
                            </div>
                            <?php
                        }
                    }
                    if ((in_array('favorites', $enabled_post_meta)) && class_exists('Favorites')) { ?>
                        <div class="meta-list-item post-favorite">
                            <?php
                            echo get_favorites_button($post->ID); ?>
                        </div>
                    <?php }
                    if (in_array('read_time', $enabled_post_meta)) { ?>
                        <div class="meta-list-item post-read-time">
                            <?php united_blog_get_readtime(); ?>
                        </div>
                    <?php } ?>
                </div>
            <?php
            endif;
        endif;
    }
endif;
if (!function_exists('united_blog_single_post_comment')) :
    /**
     * Displays an optional post thumbnail.
     *
     * Wraps the post thumbnail in an anchor element on index views, or a div
     * element when on single views.
     */
    function united_blog_single_post_comment()
    { ?>
        <div class="meta-list-item post-comment">
            <?php
            $number = get_comments_number(get_the_ID());
            if (0 == $number) {
                $respond_link = get_permalink() . '#respond';
                $comment_link = apply_filters('respond_link', $respond_link, get_the_ID());
            } else {
                $comment_link = get_comments_link();
            }
            ?>
            <?php
            if ('1' === $number) :
                ?>
                <a href="<?php echo esc_url($comment_link); ?>" class="text-decoration-reset">
                    <?php
                    esc_html_e('1 comment', 'united-blog');
                    ?>
                </a>
            <?php
            else :
                ?>
                <a href="<?php echo esc_url($comment_link); ?>" class="text-decoration-reset">
                    <?php
                    printf(
                    /* translators: %s: Comment count number. */
                        esc_html(_nx('%s comment', '%s comments', $number, 'Comments title', 'united-blog')),
                        esc_html(number_format_i18n($number))
                    );
                    ?>
                </a>
            <?php endif;
            ?>
        </div>
        <?php
    }
endif;
/**
 * Displays menu description in primary menu
 *
 * @param string $item_output The menu item's starting HTML output.
 * @param WP_Post $item Menu item data object.
 * @param int $depth Depth of the menu. Used for padding.
 * @param stdClass $args An object of wp_nav_menu() arguments.
 * @return string The menu item output with menu description.
 * @since United Blog 1.0
 *
 */
function united_blog_show_main_menu_nav_description($item_output, $item, $depth, $args)
{
    if (!empty($item->description)) {
        $item_output = str_replace($args->link_after . '</a>', '<span class="menu-item-description">' . $item->description . '</span>' . $args->link_after . '</a>', $item_output);
    }
    return $item_output;
}

add_filter('walker_nav_menu_start_el', 'united_blog_show_main_menu_nav_description', 10, 4);



if (!function_exists('united_blog_estimated_read_time')) :
    /**
     * Estimated reading time in minutes
     *
     * @param $content
     * @param $with_gutenberg
     *
     * @return int estimated time in minutes
     */
    function united_blog_estimated_read_time($content = '', $with_gutenberg = false)
    {
        // In case if content is build with gutenberg parse blocks.
        if ($with_gutenberg) {
            $blocks = parse_blocks($content);
            $contentHtml = '';
            foreach ($blocks as $block) {
                $contentHtml .= render_block($block);
            }
            $content = $contentHtml;
        }
        // Remove HTML tags from string.
        $content = wp_strip_all_tags($content);
        // When content is empty return 0.
        if (!$content) {
            return 0;
        }
        // Count words containing string.
        $words_count = str_word_count($content);
        // Words per minute.
        $words_per_minute = 200;
        // Calculate time for read all words and round.
        $minutes = ceil($words_count / $words_per_minute);
        return $minutes;
    }
endif;

if (!function_exists('united_blog_get_readtime')) :
    /**
     * Print archive excerpt
     *
     * @return string Page ID.
     * @since 1.0.0
     *
     */
    function united_blog_get_readtime()
    { ?>
        <span class="screen-reader-text"><?php esc_html_e('Estimated read time', 'united-blog'); ?></span>
        <?php united_blog_the_theme_svg('hourglass'); ?>
        <?php
        $read_time = united_blog_estimated_read_time(get_the_content());
        printf( /* translators: %s: Read Time. */
            esc_html__('%s min read', 'united-blog'),
            number_format_i18n($read_time)
        );
        ?>

    <?php }
endif;

