<?php
$settings = $this->get_settings();
$cat_multi_slug = widgetkit_pro_array_get($settings, 'cat_dynamic_multiple_id');
$course_thumbnail_size = widgetkit_pro_array_get($settings, 'image_size');
$post_num_to_show = widgetkit_pro_array_get($settings, 'post_num_to_show');


$ld_course_price = $settings['ld_course_price'];
$ld_course_desc = widgetkit_pro_array_get($settings, 'ld_course_desc');
$ld_excerpt_word_count = widgetkit_pro_array_get($settings, 'post_desc_length');
$ld_course_btn = widgetkit_pro_array_get($settings, 'ld_course_btn');

$nav_visibility = widgetkit_pro_array_get($settings, 'nav_visibility'); 
$posts_column = $settings['posts_column'];
$layout = widgetkit_pro_array_get($settings, 'courses_layout_style');
$active_carousel = $layout == 'active_carousel' ? 'yes' : '';
//$tax_term = get_term_meta($cat_id);
$a = '';


?>
<?php if (class_exists('SFWD_LMS')) : // Check LearnDash LMS plugin active?>

<div id="dynamic-category-content-<?php echo $this->get_id(); ?>" class="dynamic-category-content-<?php echo $this->get_id(); ?> dynamic-category-body">
    <div id="dynamic-layout" class="dynamic-layout dynamic-layout-<?php echo $this->get_id(); ?>">
        <div id="dynamic-category">
         

	               <div class="learndash-dynamic-category-wrapper">
                    <?php if ($cat_multi_slug): ?>
                        <div id="<?php echo $this->get_id(); ?>" class="multiple-cat">
                            
                            <?php
                                /**
                                 * get custom post type
                                 * data from slug
                                 */
                                foreach ($cat_multi_slug as $cat):
                                    $tax_data = get_term_by('slug', $cat, 'ld_course_category');
                                    if($tax_data):
                                    $cat_id =  $tax_data->term_id ;

                                    if ($a == 0) {
                                        $first_cat_ID = $cat_id;
                                    }
                                    /**
                                     * pn = post number to show
                                     * rts= regular thumb size
                                     */
                            ?>
                            <a href="<?php echo admin_url('admin-ajax.php?action=learndashDynamicCat&term_id=' . $tax_data->term_id . '&pn=' . $post_num_to_show . '&rts=' . $course_thumbnail_size) ?>"
                               class="cat-item <?php echo $a == 0 ? ' active' : ''; ?>"
                            >
                                <span class="tab-text"> <?php echo esc_html( $tax_data->name ); ?> </span>
                            </a>

                            <?php
                                endif;
                                $a++;
                            endforeach;

                            ?>
                        </div>
                    <?php else: ?>
                        <div id="<?php echo $this->get_id(); ?>" class="multiple-cat">
                            <a href="#" class="cat-item <?php echo $a == 0 ? ' active' : ''; ?>" >
                                <span class="tab-text"> <?php esc_html_e('Most Recent', "widgetkit-pro"); ?> </span>
                            </a>
                        </div>
                    <?php endif ?>
                    </div>

            
        </div>
        <!-- category content -->
        <div
                data-coursePrice="<?php echo $ld_course_price; ?>"
                data-courseDesc="<?php echo $ld_course_desc; ?>"
                data-courseButton="<?php echo $ld_course_btn; ?>"
                data-postsColumn="<?php echo $posts_column; ?>"
                data-activeCarousel="<?php echo $active_carousel; ?>"
                class="dynamic-category-content cat-post-list dynamic-cat-post-list animated fadeIn">

            <div id="lp-dynamic-course-carousel" class="wkp-ld-course-tab-element <?php echo ($active_carousel=='yes') ? 'lp-dynamic-course-active owl-carousel' : ''; ?>">
      <?php
        /**
         * Query for the post
         * custom post type
         * post type : lp_course
         * category taxonomy : course_category
         */
        $count = 0;
        /**
        * if select any category for drop down
        * then assign that value to the $first_cat_id
        * if not then set it to null
        */
        if (isset($first_cat_ID)) {
            $first_cat_ID = $first_cat_ID;
        } else {
            $first_cat_ID = '';
        }
        if ($cat_multi_slug) :
            $args = array(
                'post_type' => 'sfwd-courses',
                'posts_per_page' => $post_num_to_show,
                'tax_query' => array(
                    array(
                        'taxonomy' => 'ld_course_category',
                        'field'    => 'slug',
                        'terms' => $cat_multi_slug[0],
                    ),
                ),
            );

        else :
            $args = array(
                'post_type' => 'sfwd-courses',
                'posts_per_page' => $post_num_to_show
            );  
        endif;
        
        $query = new WP_Query($args);
        if ($query->have_posts()):
            while ($query->have_posts()):
                $query->the_post();

                global $post;
                $post_id = $post->ID;
                $course_id = $post_id;
                $user_id = get_current_user_id();
                $current_id = $post->ID;

                $enable_video = get_post_meta($post->ID, '_learndash_course_grid_enable_video_preview', true);
                $embed_code = get_post_meta($post->ID, '_learndash_course_grid_video_embed_code', true);
                $button_text = get_post_meta($post->ID, '_learndash_course_grid_custom_button_text', true);
                $post_meta = get_post_meta($post->ID);
                $short_description = @$post_meta['_wkfe_ld_template_course_short_desc']; // meta box id comes from wk pro
                $grid_short_desc = get_post_meta($post->ID, '_learndash_course_grid_short_description', true);

                // Retrive oembed HTML if URL provided
                if (preg_match('/^http/', $embed_code)) {
                    $embed_code = wp_oembed_get($embed_code, array('height' => 600, 'width' => 400));
                }

                $button_text = isset($button_text) && !empty($button_text) ? $button_text : __('See more...', 'widgetkit-pro');

                $button_text = apply_filters('learndash_course_grid_custom_button_text', $button_text, $post_id);

                $options = get_option('sfwd_cpt_options');
                $currency = null;

                if (!is_null($options)) {
                    if (isset($options['modules']) && isset($options['modules']['sfwd-courses_options']) && isset($options['modules']['sfwd-courses_options']['sfwd-courses_paypal_currency'])) {
                        $currency = $options['modules']['sfwd-courses_options']['sfwd-courses_paypal_currency'];
                    }
                }

                if (is_null($currency)) {
                    $currency = 'USD';
                }

                $course_options = get_post_meta($post_id, "_sfwd-courses", true);
                $price = $course_options && isset($course_options['sfwd-courses_course_price']) ? $course_options['sfwd-courses_course_price'] : __('Free', 'widgetkit-pro');
                // $short_description = @$course_options['sfwd-courses_course_short_description'];
                

                $has_access = sfwd_lms_has_access($course_id, $user_id);
                $is_completed = learndash_course_completed($user_id, $course_id);

                if ($price == '') {
                    $price .= __('Free', 'widgetkit-pro');
                }

                if (is_numeric($price)) {
                    if ($currency == "USD") {
                        $price = '$' . $price;
                    } else {
                        $price .= ' ' . $currency;
                    }
                }

                $class = '';
                $ribbon_text = '';

                if ($has_access && !$is_completed) {
                    $class = 'ld_course_grid_price ribbon-enrolled';
                    $ribbon_text = __('Enrolled', 'widgetkit-pro');
                } elseif ($has_access && $is_completed) {
                    $class = 'ld_course_grid_price';
                    $ribbon_text = __('Completed', 'widgetkit-pro');
                } else {
                    $class = !empty($course_options['sfwd-courses_course_price']) ? 'ld_course_grid_price price_' . $currency : 'ld_course_grid_price free';
                    $ribbon_text = $price;
                }

            ?>

	                  <div class="wkp-ld-single-course <?php echo $active_carousel ? 'col-md-12' : ''; ?> col-sm-<?php echo $posts_column; ?>">
	                      <article id="post-<?php the_ID();?>" <?php post_class('course');?>>
                            
	                        <?php if ($post->post_type == 'sfwd-courses' && $ld_course_price == true && has_post_thumbnail() ): ?>
                                <div class="<?php echo esc_attr($class); ?>">
                                    <?php echo esc_attr($ribbon_text); ?>
                                </div>
	                        <?php endif;?>

                        <?php if (1 == $enable_video && !empty($embed_code)): ?>
                            <div class="ld_course_grid_video_embed">
                                <?php echo $embed_code; ?>
                            </div>
                        <?php elseif (has_post_thumbnail()): ?>
                            <a href="<?php the_permalink();?>">
                                <?php the_post_thumbnail($course_thumbnail_size);?>
                            </a>
                        <?php endif;?>

                        <div class="ld-caption">
                            <h3 class="wk-entry-title">
                                <a class="course-title-link" href="<?php the_permalink();?>">
                                    <?php the_title();?>
                                </a>
                            </h3>
                          <?php if (!empty($short_description) && $ld_course_desc) :?>
                            <p class="ld-entry-content">
                                <?php if($ld_excerpt_word_count): ?>
                                    <?php echo wp_trim_words($short_description[0], $ld_excerpt_word_count, ''); ?>
                                <?php else: ?>
                                    <?php echo $short_description[0]; ?>
                                <?php endif; ?>
                            </p>
                          <?php else:?>
                            <p class="ld-entry-content"><?php echo htmlspecialchars_decode($grid_short_desc); ?></p>
                          <?php endif;?>

                        <?php if ($ld_course_btn) {?>
                            <p class="ld_course_grid_button"><a class="btn btn-primary" role="button" href="<?php the_permalink()?>" rel="bookmark"><?php esc_html_e($button_text, 'widgetkit-pro');?></a></p>
                        <?php }?>

                        </div>
                      </article><!-- #post-## -->
                  </div>
            <?php $count++;
                endwhile;
               wp_reset_postdata(); wp_reset_query(); 
            endif;
        ?>
        </div>
        </div>
    </div><!-- div -->


  <script type='text/javascript'>
            <?php
                if ($active_carousel == 'yes'):
                $column = 12 / $posts_column;
                $rootId = '#dynamic-category-content-' . $this->get_id();
            ?>
	        jQuery(document).ready(function($) {
	          console.log();
	          $('<?php echo $rootId; ?> ').find('.lp-dynamic-course-active').owlCarousel({
	              loop:false,
	              nav:true,
	              dots:false,
	              items: <?php echo $column ?>,
	              navClass: ['owl-carousel-left','owl-carousel-right'],
	              navText: ['<i class="fa fa-chevron-left" aria-hidden="true"></i>', '<i class="fa fa-chevron-right" aria-hidden="true"></i>'],
	              responsive:{
	                  0:{
	                      items:1
	                  },
	                  600:{
	                      items:2
	                  },
	                  1000:{
	                      items:<?php echo $column ?>
	                  }
	              }
	          });
	      });
	    <?php endif;?>


  </script>

  <!-- Start css style -->
    <style>
    <?php if ($settings['nav_visibility'] == 'always_visible'): ?>
        .widgetkit-lp-course-1 .owl-nav .owl-carousel-left, .widgetkit-lp-course-1 .owl-nav .owl-carousel-right, .widgetkit-course-1 .owl-nav .owl-carousel-left, .widgetkit-course-1 .owl-nav .owl-carousel-right, .dynamic-category-body .owl-nav .owl-carousel-left, .dynamic-category-body .owl-nav .owl-carousel-right {
            opacity: 1;
        }
    <?php endif;?>
  </style>

</div>
<?php else:  ?>
    <div class="plugin-active-massage">
        <h3><?php esc_html_e('Please activate LearnDash LMS plugin first', 'widgetkit-pro');?></h3>

    </div>
<?php endif;  ?>
