<?php
if ( !function_exists( 'DGgetPostViews' ) ) {
    function DGgetPostViews($postID) {
        $count_key = 'post_views_count';
        $count = get_post_meta($postID, $count_key, true);
        if($count==''){
            delete_post_meta($postID, $count_key);
            add_post_meta($postID, $count_key, '0');
            return "0 View";
        }
        return $count.' Views';
    }
}

if ( !function_exists( 'DGsetPostViews' ) ) {
    function DGsetPostViews($postID) {
        $count_key = 'post_views_count';
        $count = get_post_meta($postID, $count_key, true);
        if($count==''){
            $count = 0;
            delete_post_meta($postID, $count_key);
            add_post_meta($postID, $count_key, '0');
        }else{
            $count++;
            update_post_meta($postID, $count_key, $count);
        }
    }
}

if ( !function_exists( 'dgbm_filter_the_content_in_the_main_loop' ) ) {
    function dgbm_filter_the_content_in_the_main_loop( $content ) {
        if ( is_single() && in_the_loop() && is_main_query() ) {
            DGsetPostViews(get_the_ID());
        }
        return $content;
    }
    add_filter( 'the_content', 'dgbm_filter_the_content_in_the_main_loop' );
}


/**
 * Add a filter for post content
 * @return content
 */
if ( ! function_exists( 'dgbm_get_post_content_output' ) ) {
    function dgbm_get_post_content_output( $content_text, $content_length ) {
        $content_text = ($content_length > 0) && !empty($content_text) ? 
                        substr($content_text, 0, $content_length) . '...': $content_text ;
        return $content_text;
    }
    add_filter('dgbm_get_post_content', 'dgbm_get_post_content_output', 10, 2);
}

/**
 * Render post meta
 * take $args and $location
 * 
 * render HTML
 */
if ( ! function_exists( 'dgbm_render_post_meta_html' ) ) {
    function dgbm_render_post_meta_html($args = array(), $location='default', $id=0) {
        $markup = array(
            'default'       => '',
            'top'           => '',
            'bottom'        => '',
            'over-image'    => array(
                'over-image-top' => '',
                'over-image-bottom' => ''
            )
        );
        $post_meta = dgbm_post_meta_array( $args, $location, $id );
        $sapartor = 'on' === $args['use_meta_icon'] ? '' : '<span class="pipe-separator">|</span>';

        foreach ( $post_meta as $key => $value ) {
            $with_seperator = '' !== $value ? $sapartor . $value : '';
            $over_image_classes = ' post-meta-over-image over-image-top';

            if ( ($key == 'author' && $args['author_location'] === $location) ||
             ($key == 'date' && $args['date_location'] === $location) || 
             ($key == 'category' && $args['category_location'] === $location) || 
             ($key == 'comment' && $args['comment_location'] === $location) ) {
                if ( 'over-image' == $location ) {
                    $markup[$location]['over-image-top'] .= $key == 'author' || $key == 'date' ? $value : '';
                    $markup[$location]['over-image-bottom'] .= $key == 'category' || $key == 'comment' ? $value : '' ;
                } else {
                    $markup[$location] .= '' === $markup[$location] ? $value : $with_seperator;
                }
            }
            
        }

        $html = '';
        if( 'over-image' == $location ) {
            $over_image_top_markup = '' !== $markup['over-image']['over-image-top'] ? 
            sprintf('<p class="post-meta%2$s">%1$s</p>', $markup[$location]['over-image-top'],$over_image_classes ) : '';
            $over_image_bottom_markup = '' !== $markup['over-image']['over-image-bottom'] ? 
            sprintf('<p class="post-meta over-image-bottom">%1$s</p>',$markup[$location]['over-image-bottom'],$over_image_classes) : '';

            $html = sprintf('%1$s %2$s', 
            $over_image_top_markup,
            $over_image_bottom_markup, 
            $over_image_classes );
        } else if( '' !== $markup[$location] && 'over-image' !== $location ) {
            $html = sprintf('<p class="post-meta post-meta-position-%2$s">%1$s</p>', $markup[$location], $location );
        }

        return '' !== $markup[$location] ? $html : '';
    }
}
/**
 * Create post meta array
 * 
 * @return array
 */
if ( ! function_exists( 'dgbm_post_meta_array' ) ) {
    function dgbm_post_meta_array( $args = array() , $location = 'default', $id=0 ) {
        $post_meta = array();
        $category_list = '';

        if ($args['post_type'] === 'project') {
            $category_list = get_the_term_list($id, 'project_category', '', ', ');
        } else {
            $category_list = get_the_term_list($id, 'category', '', ', ');
        }
    
        $meta_icon = 'on' === $args['use_meta_icon'] ? '<span class="meta-icon"></span>' : '';
        $post_meta['author'] = 'on' === $args['show_author'] ? 
        et_get_safe_localization( sprintf( __( '%s', 'dg-blog-module' ), '<span class="author vcard">' . $meta_icon .  et_pb_get_the_author_posts_link() . '</span>' ) ) : '';
        
        $post_meta['date'] = 'on' === $args['show_date'] ? 
        et_get_safe_localization( sprintf( __( '%s', 'dg-blog-module' ), '<span class="published">' .$meta_icon. esc_html( get_the_date( $args['meta_date'] ) ) . '</span>' ) ) : '';
    
        $post_meta['category'] = 'on' === $args['show_categories'] && !empty($category_list) ? 
        sprintf( '<span class="categories">%2$s %1$s</span>', $category_list, $meta_icon ) : '';
    
        $comments = sprintf( esc_html( _nx( '%s Comment', '%s Comments', get_comments_number(), 'number of comments', 'dg-blog-module' ) ), number_format_i18n( get_comments_number() ) );
        $post_meta['comment'] = 'on' === $args['show_comments'] ? 
        sprintf( '<span class="comments">%2$s %1$s</span>', $comments, $meta_icon ) : '';
    
        return $post_meta;
    }
}


/**
 * Render the image with default image size
 * @return html output
 */
if ( ! function_exists( 'dgbm_print_default_image' ) ) {
    function dgbm_print_default_image($thumbnail = '', $alttext = '',  $class = '' ) {
        if ( is_array( $thumbnail ) ) {
            extract( $thumbnail ); // phpcs:ignore WordPress.PHP.DontExtract
        }
        $output = '<img src="' . esc_url( $thumbnail )  . '"';
    
        if ( ! empty( $class ) ) $output .= " class='" . esc_attr( $class ) . "' ";
    
        $output .= " alt='" . esc_attr( wp_strip_all_tags( $alttext ) ) . "' />";
        echo et_core_intentionally_unescaped( $output, 'html' );
    }
}

/**
 * Get the thumbnail url
 * @return $thumbnail
 */
if ( ! function_exists( 'dgbm_get_thumbnail_url' ) ) {

    function dgbm_get_thumbnail_url( $thumbnail , $use_timthumb, $option, $width, $height ) {
        if ( is_array( $thumbnail ) ) {
			extract( $thumbnail ); // phpcs:ignore WordPress.PHP.DontExtract
		}

		if ( empty( $post ) ) global $post, $et_theme_image_sizes;

		$output = '';
		$raw = false;

        $et_post_id = ! empty( $et_post_id ) ? (int) $et_post_id : $post->ID;
        
        if ( has_post_thumbnail( $et_post_id ) ) {
            if ( 'default_image' !== $option) {
                $thumb_array['use_timthumb'] = false;

                $image_size_name = $width . 'x' . $height;
                $et_size = isset( $et_theme_image_sizes ) && array_key_exists( $image_size_name, $et_theme_image_sizes ) ? $et_theme_image_sizes[$image_size_name] : array( $width, $height );
    
                $et_attachment_image_attributes = wp_get_attachment_image_src( get_post_thumbnail_id( $et_post_id ), $et_size );
                $thumbnail = $et_attachment_image_attributes[0];
            } else {
                $thumbnail = $thumbnail;
            }
		} else {
            $thumbnail = '';
        }

        return $thumbnail;
    }

}

/**
 * Full width column open
 */
function dgbm_column_open($args, $class) {
    if ('full-width' === $args['layout'] && 'image-top' !== $args['layout_styles'] ) {
        echo '<div class="'.esc_attr($class).'">';
    }
}
/**
 * Full width column close
 */
function dgbm_column_close($args = array()) {
    if ('full-width' === $args['layout'] && 'image-top' !== $args['layout_styles'] ) {
        echo '</div>';
    }
}


/**
 * VB HTML on AJAX request
 * @return json response
 */
add_action( 'wp_ajax_dgbm_requestdata', 'dgbm_requestdata' );

function dgbm_requestdata() {
    global $paged, $post, $wp_query;
        
    $dg_paged = is_front_page() ? get_query_var( 'page' ) : get_query_var( 'paged' );
    $data = json_decode(file_get_contents('php://input'), true);
    if (! wp_verify_nonce( $data['et_admin_load_nonce'], 'et_admin_load_nonce' )) {
        wp_die();
    }
    $options = $data['props'];

    $defaults = array(
        'post_type'                     => '',
        'title_tag'                     => '',
        'posts_number'                  => '',
        'include_categories'            => '',
        'show_thumbnail'                => '',
        'show_excerpt'                  => '',
        'show_author'                   => '',
        'show_date'                     => '',
        'show_categories'               => '',
        'show_comments'                 => '',
        'show_more'                     => '',
        'read_more_text'				=> '',
        'use_button_icon'				=> '',
        'button_icon'					=> '',
        'image_size'					=> '',
        'show_excerpt_length'			=> '',
        'type'							=> '',
        'orderby'						=> '',
        'offset_number'					=> '',
        'button_at_bottom'				=> '',
        'use_meta_icon'					=> '',
        'show_pagination'				=> '',
        'layout'						=> '',
        'layout_styles'					=> '',
        'item_in_desktop'				=> '',
        'item_in_tablet'				=> '',
        'item_in_mobile'				=> '',
        'equal_height'					=> '',
        'equal_height_column'			=> '',
        'image_as_background'			=> '',
        'use_overlay_icon'				=> '',
        'select_overlay_icon'			=> '',
        'author_location'				=> '',
        'date_location'					=> '',
        'category_location'				=> '',
        'comment_location'				=> '',
        'meta_date'						=> '',
        'related_posts'                 => '',
        'use_post_excerpt'              => ''
    );


    $args = wp_parse_args( $options, $defaults );
    
    if ( is_front_page() ) {
        $paged = $dg_paged; //phpcs:ignore WordPress.WP.GlobalVariablesOverride
    }    
    
    $query_args = array(
        'post_type' => $args['post_type'], // added in version 1.0.6
        'post_status'    => 'publish',
        'posts_per_page' => intval( $args['posts_number'] ),
    );

    if ( '' !== $args['include_categories'] && '3' === $args['type'] && $args['post_type'] === 'post') {
        $query_args['cat'] = $args['include_categories'];
    }

    // added at version 1.0.5
    if ($data['is_single'] === 'on' && $args['related_posts'] === 'on' && $args['post_type'] === 'post') {
        if ( $data['single_id'] !== null) {
            $query_args['category__in'] = wp_get_post_categories($data['single_id']);
            $query_args['post__not_in'] = array($data['single_id']);
        } 
    }

    if ( ! is_search() ) {
        $paged = $dg_paged; //phpcs:ignore WordPress.WP.GlobalVariablesOverride
        $query_args['paged'] = $dg_paged;
    }


    // support pagination in VB
    if ( isset( $args['__page'] ) ) {
        $paged = $args['__page']; //phpcs:ignore WordPress.WP.GlobalVariablesOverride
    }

    // process icon
    $button_icon = '' !== $args['button_icon'] ?  esc_attr( et_pb_process_font_icon($args['button_icon']) ) : '9';
    $data_icon = ('on' === $args['use_button_icon']) ? 
    sprintf( 'data-icon="%1$s"', $button_icon ) : '';

    $overlay_icon = '' !== $args['select_overlay_icon'] ? esc_attr( et_pb_process_font_icon($args['select_overlay_icon']) ) : '1';
    $data_overlay_icon = 'on' === $args['use_overlay_icon'] ? 
    sprintf('data-ovrlayicon=%1$s', $overlay_icon) : '';
    
    // orderby
    if ($args['post_type'] === 'post') {
        if ( '2' === $args['type']){
            $query_args['meta_key'] = 'post_views_count'; // phpcs:ignore slow query ok.
            $query_args['orderby'] = 'meta_value_num';
            $query_args['order'] = 'DESC';
        } else {
            if ( '4' === $args['type'] ) {
                $query_args['orderby'] = 'rand';
            } else if ( '3' === $args['type'] ) {
                if ( '3' === $args['orderby'] ) {
                    $query_args['orderby'] = 'rand';
                } else if ( '2' === $args['orderby'] ) {
                    $query_args['orderby'] = 'date';
                    $query_args['order'] = 'ASC';
                } else {
                    $query_args['orderby'] = 'date';
                    $query_args['order'] = 'DESC';
                }
            } else {
                $query_args['orderby'] = 'date';
                $query_args['order'] = 'DESC';
            }
        }
    }
    

    // offset 
    if ( '' !== $args['offset_number'] && ! empty( $args['offset_number'] ) ) {
        /**
         * Offset + pagination don't play well. Manual offset calculation required
         * @see: https://codex.wordpress.org/Making_Custom_Queries_using_Offset_and_Pagination
         */
        if ( $paged > 1 ) {
            $query_args['offset'] = ( ( $paged - 1 ) * intval( $args['posts_number'] ) ) + intval( $args['offset_number'] );
        } else {
            $query_args['offset'] = intval( $args['offset_number'] );
        }
    }
    // Get query
    $q = apply_filters('dgbm_blog_query', $query_args);
    // start query
    ob_start();

    query_posts( $q ); //phpcs:ignore WordPress.WP.DiscouragedFunctions

    if ( have_posts() ) {  
            
        if ('full-width' !== $args['layout']) {
            $classes = 'masonry' === $args['layout'] ? 'dg-blog-masonry et_pb_salvattore_content' : 'dg-blog-grid';
            $masonry_attr = 'masonry' === $args['layout'] ? sprintf('data-columns="%1$s"', $args['item_in_desktop']) : '';
            $container = sprintf('<div class="%1$s" %2$s>', esc_attr($classes), esc_attr($masonry_attr));
            echo et_core_esc_previously($container);
        }   
        
        while ( have_posts() ) {
            the_post();
            global $et_fb_processing_shortcode_object;

            $image_size     = !empty($args['image_size']) ? $args['image_size'] : 'mid';
            $width          = $image_size === 'large' ? 1080 : 400;
            $width          = (int) apply_filters( 'et_pb_blog_image_width', $width );
            $height         = $image_size === 'large' ? 675 : 250;
            $height         = (int) apply_filters( 'et_pb_blog_image_height', $height );
            $classtext      = 'et_pb_post_main_image';
            $titletext      = get_the_title();
            $thumbnail      = get_thumbnail( $width, $height, $classtext, $titletext, $titletext, false, 'Blogimage' );
            $thumb          = $thumbnail["thumb"];
            $read_more_text = sprintf(esc_html__( '%1$s', 'dg-blog-module' ), $args['read_more_text']);
            
            // read more button
            $btn_at_bottom = 'on' === $args['button_at_bottom'] ? ' btn-at-bottm' : '';
            $read_more_button = 'on' === $args['show_more'] ? 
                    sprintf('<div class="dg_read_more_wrapper%4$s"><a class="read-more" href="%2$s" %3$s><span>%1$s</span></a></div>', 
                    esc_html($read_more_text),
                    esc_attr(get_the_permalink()),
                    $data_icon,
                    esc_attr($btn_at_bottom)
            ) : '';
            // post title markup
            $post_title = sprintf( '<%3$s class="dg_bm_title"><a href="%2$s">%1$s</a></%3$s>', 
                $titletext, esc_attr(get_the_permalink()), $args['title_tag'] );
            $image_style = 'full-width' === $args['layout'] && 'on' === $args['equal_height_column'] && 'image-top' !== $args['layout_styles'] ?
            sprintf('style="background-image:url(%1$s);"', dgbm_get_thumbnail_url($thumb, $thumbnail["use_timthumb"], $image_size, $width, $height)) : '';
            $image_as_bg = 'on' === $args['image_as_background'] && 'full-width' !== $args['layout'] ?
            sprintf('style="background-image:url(%1$s);"', dgbm_get_thumbnail_url($thumb, $thumbnail["use_timthumb"], $image_size, $width, $height)) : '';
            ?>
            <article id="post-<?php the_ID(); ?>" <?php post_class( 'dgbm_post_item' ) ?> <?php echo et_core_esc_previously($image_as_bg);?>>
                <?php 
                    if ( '' !== $thumb && 'on' === $args['show_thumbnail']) {
                        dgbm_column_open($args, 'column-image');
                        echo '<div class="dg-post-thumb" '.et_core_esc_previously($data_overlay_icon).'>';
                        // render post meta position over-image
                        echo et_core_esc_previously(dgbm_render_post_meta_html($args, 'over-image',get_the_ID()));
                        echo '<a class="featured-image-link" '.et_core_esc_previously($image_style).' href="'.esc_attr(get_the_permalink()).'">';
                            if($image_size !== 'default_image') {
                                print_thumbnail( $thumb, $thumbnail["use_timthumb"], $titletext, $width, $height );
                            } else {
                                dgbm_print_default_image($thumb, $titletext );
                            }
                            
                        echo '</a></div>';
                        dgbm_column_close($args);
                    }
                ?>
                <?php dgbm_column_open($args, 'column-content'); ?>
                    <div class="content-wrapper">
                        <?php 
                            // Background Pattern and Mask style for builder
                            echo isset($args['background_enable_pattern_style']) ? dgbm_render_pattern_or_mask_html($args['background_enable_pattern_style'], 'pattern') : '';
                            echo isset($args['background_enable_mask_style']) ? dgbm_render_pattern_or_mask_html($args['background_enable_mask_style'], 'mask') : '';
                            
                            // render post meta position top
                            echo et_core_esc_previously(dgbm_render_post_meta_html($args, 'top', get_the_ID()));
                        ?>
                        <?php echo et_core_esc_previously($post_title);?>
                        <?php 
                            // render post meta position default
                            echo et_core_esc_previously(dgbm_render_post_meta_html($args, 'default', get_the_ID())); 
                        ?>
                        <?php
                        // render post content
                        if('on' === $args['show_excerpt']) {
                            $content_length = empty($args['show_excerpt_length']) ? 120 : $args['show_excerpt_length'];

                            if ( has_excerpt() && 'on' === $args['use_post_excerpt']) {
                                echo '<div class="post-content">';
                                    the_excerpt();
                                echo '</div>';
                            } else {
                                echo '<div class="post-content">' .et_core_intentionally_unescaped( wpautop( et_delete_post_first_video( strip_shortcodes( truncate_post( $content_length, false, '', true ) ) ) ), 'html' ). '</div>';
                            }
                            // if ( trim(get_the_excerpt()) !== '' ) {
                            //     echo '<div class="post-content">'.et_core_intentionally_unescaped(apply_filters('dgbm_get_post_content', get_the_excerpt(), $content_length), 'html').'</div>';
                            // } else {
                            //     echo '<div class="post-content">' .et_core_intentionally_unescaped( wpautop( et_delete_post_first_video( strip_shortcodes( truncate_post( $content_length, false, '', true ) ) ) ), 'html' ). '</div>';
                            // }
                        }
                        ?>
                        <?php 
                            if ('on' !== $args['button_at_bottom']) {
                                echo et_core_esc_previously($read_more_button); 
                                echo et_core_esc_previously(dgbm_render_post_meta_html( $args, 'bottom', get_the_ID())); 
                            } else {
                                echo et_core_esc_previously(dgbm_render_post_meta_html( $args, 'bottom', get_the_ID())); 
                                echo et_core_esc_previously($read_more_button); 
                            } 
                        ?>
                        
                    </div>
                <?php dgbm_column_close($args); ?>
            </article>
            <?php
            
        } //endwhile
        if ('full-width' !== $args['layout']) {
            echo '</div>';
        } 

        if ( 'on' === $args['show_pagination'] && ! is_search() ) {
            if ( function_exists( 'wp_pagenavi' ) ) {
                wp_pagenavi();
            } else {
                if ( et_is_builder_plugin_active() ) {
                    include( ET_BUILDER_PLUGIN_DIR . 'includes/navigation.php' );
                } else {
                    get_template_part( 'includes/navigation', 'index' );
                }
            }
        }

    }

    wp_reset_query(); //phpcs:ignore WordPress.WP.DiscouragedFunctions
    $posts = ob_get_contents();
    ob_end_clean();
    // return the blog HTML
    wp_send_json_success($posts);
}
/**
 * Make sure the VB getting the data on ajax load
 * @return json response
 */
function dgbm_et_builder_load_actions( $actions ) {
	$actions[] = 'dgbm_requestdata';

	return $actions;
}
add_filter( 'et_builder_load_actions', 'dgbm_et_builder_load_actions' );

/**
 * render pattern or mask markup
 * 
 */
function dgbm_render_pattern_or_mask_html( $props, $type ) {
    $html = array(
        'pattern' => '<span class="et_pb_background_pattern"></span>',
        'mask' => '<span class="et_pb_background_mask"></span>'
    );
    return $html[$type];
}

/**
 * Get the list of registered Post Types options.
 *
 * @since 3.18
 * @since 4.0.7 Added the $require_editor parameter.
 *
 * @param boolean|callable $usort
 * @param boolean $require_editor
 *
 * @return array
 */
function dgbm_get_registered_post_type_options( $usort = false, $require_editor = true ) {
	$require_editor_key = $require_editor ? '1' : '0';
	$key                = "et_get_registered_post_type_options:{$require_editor_key}";

	$blocklist = et_builder_get_blocklisted_post_types();
	$allowlist = et_builder_get_third_party_post_types();

	// Extra and Library layouts shouldn't appear in Theme Options as configurable post types.
	/**
	 * Get array of post types to prevent from appearing as options for builder usage.
	 *
	 * @since 4.0
	 *
	 * @param string[] $blocklist Post types to blocklist.
	 */
	$blocklist      = apply_filters( 'et_builder_post_type_options_blocklist', array_merge( $blocklist, array(
		'et_pb_layout',
        'layout',
        'page',
        'attachment'
	) ) );
	$raw_post_types = get_post_types( array(
		'show_ui' => true,
	), 'objects' );
	$post_types     = array();

	foreach ( $raw_post_types as $post_type ) {
		$is_allowlisted  = in_array( $post_type->name, $allowlist );
		$is_blocklisted  = in_array( $post_type->name, $blocklist );
		$supports_editor = $require_editor ? post_type_supports( $post_type->name, 'editor' ) : true;
		$is_public       = et_builder_is_post_type_public( $post_type->name );

		if ( ! $is_allowlisted && ( $is_blocklisted || ! $supports_editor || ! $is_public ) ) {
			continue;
		}

		$post_types[] = $post_type;
	}

	if ( $usort && is_callable( $usort ) ) {
		usort( $post_types, $usort );
	}

	$post_type_options = array_combine(
		wp_list_pluck( $post_types, 'name' ),
		wp_list_pluck( $post_types, 'label' )
	);

	return $post_type_options;
}




