<?php
/**
 * Course Scheduler Widget
 *
 * This widget will display list of courses/lessons/topics/quizzes with their defined scheduled dates in an accordion.
 */

/**
 * Adds CS_LD_Widget widget.
 */
class CS_LD_Widget extends WP_Widget {

    /**
     * Register widget with WordPress.
     */
    function __construct() {
        parent::__construct(
            'cs_ld_widget', // Base ID
            esc_html__( 'LearnDash Course Planner Pro Schedule Management', 'cs_ld_addon' ), // Name
            array( 'description' => esc_html__( 'Display scheduled courses, lessons, topics and quizzes. Visible only to logged in users.', 'cs_ld_addon' ), ) // Args
        );

        add_action('wp_enqueue_scripts', [$this, 'wn_ld_cs_enqueue_scripts']);
    }

    /**
     * Front-end display of widget.
     *
     * @see WP_Widget::widget()
     *
     * @param array $args     Widget arguments.
     * @param array $instance Saved values from database.
     */
    public function widget( $args, $instance ) {
        $listing_data = $this->getEvents();
        if( empty($listing_data) ) {
            return;
        }

        echo $args['before_widget'];
        if ( ! empty( $instance['title'] ) ) {
            echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];
        }
        $this->output($instance, $listing_data);
        echo $args['after_widget'];
    }

    /**
     * Back-end widget form.
     *
     * @see WP_Widget::form()
     *
     * @param array $instance Previously saved values from database.
     */
    public function form( $instance ) {
        $title = ! empty( $instance['title'] ) ? $instance['title'] : esc_html__( 'Scheduled Courses', 'cs_ld_addon' );
        $status_text = ! empty( $instance['status_text'] ) ? $instance['status_text'] : esc_html__( 'Status', 'cs_ld_addon' );
        $status_available_text = ! empty( $instance['status_available_text'] ) ? $instance['status_available_text'] : esc_html__( 'Available', 'cs_ld_addon' );
        $status_unavailable_text = ! empty( $instance['status_unavailable_text'] ) ? $instance['status_unavailable_text'] : esc_html__( 'Unavailable', 'cs_ld_addon' );
        $message = ! empty( $instance['message'] ) ? $instance['message'] : esc_html__( 'Your enrolled courses/lessons/topics and quizzes are scheduled on following dates.', 'cs_ld_addon' );
        ?>
        <p>
            <label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_attr_e( 'Title:', 'cs_ld_addon' ); ?></label>
            <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
        </p>
        <p>
            <label for="<?php echo esc_attr( $this->get_field_id( 'available_message' ) ); ?>"><?php esc_attr_e( 'Message:', 'cs_ld_addon' ); ?></label>
            <textarea class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'message' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'message' ) ); ?>"><?php echo esc_attr( $message ); ?></textarea>
        </p>
        <!--<p>
            <label for="<?php /*echo esc_attr( $this->get_field_id( 'status_text' ) ); */?>"><?php /*esc_attr_e( 'Status Text:', 'cs_ld_addon' ); */?></label>
            <input class="widefat" id="<?php /*echo esc_attr( $this->get_field_id( 'status_text' ) ); */?>" name="<?php /*echo esc_attr( $this->get_field_name( 'status_text' ) ); */?>" type="text" value="<?php /*echo esc_attr( $status_text ); */?>">
        </p>-->
        <p>
            <label for="<?php echo esc_attr( $this->get_field_id( 'status_available_text' ) ); ?>"><?php esc_attr_e( 'Available Text:', 'cs_ld_addon' ); ?></label>
            <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'status_available_text' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'status_available_text' ) ); ?>" type="text" value="<?php echo esc_attr( $status_available_text ); ?>">
        </p>
        <p>
            <label for="<?php echo esc_attr( $this->get_field_id( 'status_unavailable_text' ) ); ?>"><?php esc_attr_e( 'Unavailable Text:', 'cs_ld_addon' ); ?></label>
            <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'status_unavailable_text' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'status_unavailable_text' ) ); ?>" type="text" value="<?php echo esc_attr( $status_unavailable_text ); ?>">
        </p>
        <?php
    }

    /**
     * Sanitize widget form values as they are saved.
     *
     * @see WP_Widget::update()
     *
     * @param array $new_instance Values just sent to be saved.
     * @param array $old_instance Previously saved values from database.
     *
     * @return array Updated safe values to be saved.
     */
    public function update( $new_instance, $old_instance ) {
        $instance = array();
        $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? sanitize_text_field( $new_instance['title'] ) : '';
        $instance['message'] = ( ! empty( $new_instance['message'] ) ) ? sanitize_text_field( $new_instance['message'] ) : '';
        $instance['status_text'] = ( ! empty( $new_instance['status_text'] ) ) ? sanitize_text_field( $new_instance['status_text'] ) : '';
        $instance['status_available_text'] = ( ! empty( $new_instance['status_available_text'] ) ) ? sanitize_text_field( $new_instance['status_available_text'] ) : '';
        $instance['status_unavailable_text'] = ( ! empty( $new_instance['status_unavailable_text'] ) ) ? sanitize_text_field( $new_instance['status_unavailable_text'] ) : '';


        return $instance;
    }

    /**
     * Rendered added events on calendar
     */
    public function getEvents() {

        $user_id = get_current_user_id();
        $course_ids = ld_get_mycourses($user_id);

        $listing_data = array();

        foreach ($course_ids as $course_id) {

            if($this->is_content_hidden_for_all($course_id)) {
                continue;
            }

            $course_schedules = $this->get_object_schedule($course_id, 'course');
            
            if(!empty($course_schedules)) {
                $listing_data['courses'][$course_id] = array(
                    'course_id' => $course_id,
                    'title' => get_the_title($course_id),
                    'schedules' => $course_schedules
                );
            }

            $lesson_ids = learndash_course_get_steps_by_type($course_id, 'sfwd-lessons');
            foreach ($lesson_ids as $lesson_id) {

                if($this->is_content_hidden_for_all($lesson_id)) {
                    continue;
                }

                $lesson_schedules = $this->get_object_schedule($lesson_id, 'lesson');

                if( !empty($lesson_schedules) ) {
                    $listing_data['lessons'][$lesson_id] = array(
                        'course_id' => $course_id,
                        'title' => get_the_title($lesson_id),
                        'schedules' => $lesson_schedules
                    );
                }
            }


            $topic_ids = learndash_course_get_steps_by_type($course_id, 'sfwd-topic');
            foreach ($topic_ids as $topic_id) {

                if($this->is_content_hidden_for_all($topic_id)) {
                    continue;
                }

                $topic_schedules = $this->get_object_schedule($topic_id, 'topic');

                if( !empty($topic_schedules) ) {
                    $listing_data['topic'][$topic_id] = array(
                        'course_id' => $course_id,
                        'title' => get_the_title($topic_id),
                        'schedules' => $topic_schedules
                    );
                }
            }


            $quiz_ids = learndash_course_get_steps_by_type($course_id, 'sfwd-quiz');
            foreach ($quiz_ids as $quiz_id) {

                if($this->is_content_hidden_for_all($quiz_id)) {
                    continue;
                }

                $quiz_schedules = $this->get_object_schedule($quiz_id, 'quiz');

                if( !empty($quiz_schedules) ) {
                    $listing_data['quiz'][$quiz_id] = array(
                        'course_id' => $course_id,
                        'title' => get_the_title($quiz_id),
                        'schedules' => $quiz_schedules
                    );
                }
            }

        }
//$this->var_dump_error($listing_data, true);


        //$this->var_dump_error($course_scheduled_dates);
        //$course_scheduled_dates = $this->get_schedule_courses($course_ids);



        //learndash_get_groups_administrator_ids(
        //$user_completed_activity_ids = $this->get_user_completed_activities($user_id);
        //$listing_data = array();

        /*foreach ( $course_scheduled_dates as $course_id => $scheduled_dates ) {

            if( in_array($course_id, $user_completed_activity_ids) )
                continue;

            //$scheduled_dates = $this->get_scheduled_dates($course_id);

            if( !empty($scheduled_dates) ) {

                $lesson_ids = learndash_course_get_steps_by_type($course_id, 'sfwd-lessons');
                $topic_ids = learndash_course_get_steps_by_type($course_id, 'sfwd-topic');
                $quiz_ids = learndash_course_get_steps_by_type($course_id, 'sfwd-quiz');

                //$listing_data['scheduled_dates'][$course_id] = $scheduled_dates;

                $listing_data['courses'][$course_id] = array(
                    'course_id' => $course_id,
                    'title' => get_the_title($course_id),
                    'schedules' => $scheduled_dates
                );
                //$listing_data['courses'][$course_id] = ;

                $this->var_dump_error($listing_data);

                //Lessons
                foreach ($lesson_ids as $lesson_id) {
                    if( !in_array($lesson_id, $user_completed_activity_ids) )
                    $listing_data['lessons'][$lesson_id] = array('course_id' => $course_id, 'title' => get_the_title($lesson_id));
                }

                //Topics
                foreach ($topic_ids as $topic_id) {
                    if( !in_array($topic_id, $user_completed_activity_ids) )
                    $listing_data['topics'][$topic_id] = array('course_id' => $course_id, 'title' => get_the_title($topic_id));
                }

                //Quizzes
                foreach ($quiz_ids as $quiz_id) {
                    if( !in_array($quiz_id, $user_completed_activity_ids) )
                    $listing_data['quizzes'][$quiz_id] = array('course_id' => $course_id, 'title' => get_the_title($quiz_id));
                }
            }
        }*/

        return $listing_data;
    }

    function get_schedule_courses($course_ids) {

        $schedule_dates = array();

        if( !empty($course_ids) ) {

            global $wpdb;

            $format = $this->query_in_placeholders($course_ids, '%d');

            $table_name = "{$wpdb->prefix}csld_events";

            $query = "SELECT * FROM `{$table_name}` E 
                        WHERE E.`object_type`='sfwd-courses' 
                          AND E.`object_id` IN ({$format})";

            $query .= " AND E.`start` >= CURDATE()";
            $query .= " AND E.`is_subsdate_as_startdate` != %s";
            $query .= ";";

            $query_data = $course_ids;
            $query_data[] = 'Yes';

            $results = $wpdb->get_results( $wpdb->prepare($query, $query_data) );

            if( !empty($results) ) {

                foreach ($results as $result) {

                    $schedule_dates[$result->object_id][] = $result->start;
                    
                    if( $result->is_end_date != 'one_day_end_date' ) {
                        if ( !empty($result->end) ) {
                            $schedule_dates[$result->object_id][] = $result->end;
                        }
                    }
                }
            }

            /*$this->var_dump_error($wpdb->last_query);
            $this->var_dump_error($schedule_dates);*/
        }

        return $schedule_dates;
    }

    function get_object_schedule($object_id, $object_type = 'course') {

        $ld_post_schedules = array();

        $ld_activity = $this->get_ld_activity($object_id, $object_type);


        if($ld_activity) {
            $activity_status = $ld_activity->activity_status;
            $activity_started = $ld_activity->activity_started;

            //Get course enrollment timestamp
            if($object_type != 'course') {
                $ld_course_activity = $this->get_ld_activity($ld_activity->course_id, 'course');
                if ($ld_course_activity) {
                    $activity_started = $ld_course_activity->activity_started;
                }
            }

        } else {
            $activity_status = false;
            $activity_started = false;
        }

        //If activity is not yet completed
        if( !$activity_status ) {

            $individual_course_results = $this->get_individual_courses($object_id, $object_type);
            $group_course_results = $this->get_group_courses($object_type);

            if($individual_course_results) {

                foreach ($individual_course_results as $individual_course_result) {

                        //SET START

                        $schedule_start_at = strtotime($individual_course_result->start);

                        $enrollment_as_start = (strtolower(sanitize_text_field($individual_course_result->is_subsdate_as_startdate)) == 'yes');

                        if ($enrollment_as_start && $activity_started) {

                            $schedule_start_at =  $activity_started;
                        }

                        //SET END

                        $schedule_end_at = strtotime($individual_course_result->end);

                        //$is_end_date_set = ( strtolower( sanitize_text_field( $individual_course_result->is_end_date ) ) == 'yes' );

                        if($enrollment_as_start && $activity_started) {
                            $duration = $individual_course_result->duration;
                            $duration_type = $individual_course_result->duration_type;

                            if( !empty($duration) && !empty($duration_type) ) {
                                $schedule_end_at = strtotime(date('Y-m-d H:i:s', $schedule_start_at) . " + {$duration} {$duration_type}");
                            }

                        }

                        // $today = time();
                        $today = current_time('timestamp');

                        if( $schedule_start_at >= $today || $schedule_end_at >= $today ) {

                            $is_schedule_passed = $this->is_schedule_passed($object_id, $individual_course_result, $object_type);

                            if($is_schedule_passed) {
                                $ld_post_schedules[] = array('start_at' => $schedule_start_at, 'is_end_date'=>$individual_course_result->is_end_date, 'end_at' => $schedule_end_at);
                            }
                        }

                }
            }

            if($group_course_results) {

                foreach ($group_course_results as $individual_course_result) {


                    //SET START
                    $schedule_start_at = strtotime($individual_course_result->start);
                    $enrollment_as_start = (strtolower(sanitize_text_field($individual_course_result->is_subsdate_as_startdate)) == 'yes');
                    if ($enrollment_as_start && $activity_started) {
                        $schedule_start_at =  $activity_started;
                    }

                    //SET END

                    $schedule_end_at = strtotime($individual_course_result->end);
                    $is_end_date_set = ( strtolower( sanitize_text_field( $individual_course_result->is_end_date ) ) != 'one_day_end_date' );

                    if($enrollment_as_start && $activity_started) {
                        $duration = $individual_course_result->duration;
                        $duration_type = $individual_course_result->duration_type;

                        if( !empty($duration) && !empty($duration_type) ) {
                            $schedule_end_at = strtotime(date('Y-m-d H:i:s', $schedule_start_at) . " + {$duration} {$duration_type}");
                        }

                    } else {

                        if( $is_end_date_set ) {
                            $schedule_end_at = strtotime(date('Y-m-d H:i:s', $schedule_start_at) . ' + 1 Day');
                        }
                    }

                    // $today = time();
                    $today = current_time('timestamp');


                    if( $schedule_start_at >= $today || $schedule_end_at >= $today ) {

                        $is_schedule_passed = $this->is_schedule_passed($object_id, $individual_course_result, $object_type, 'group');
                        if($is_schedule_passed) {
                            $ld_post_schedules[] = array('start_at' => $schedule_start_at, 'is_end_date'=>$individual_course_result->is_end_date, 'end_at' => $schedule_end_at);

                        }
                    }
                }
            }

        }

        return $ld_post_schedules;

    }

    function get_ld_activity($post_id, $activity_type) {

        //if(empty($user_id)) {
        $user_id = get_current_user_id();
        //}

        $course_id = learndash_get_course_id($post_id);

        $ld_activity_args = array(
            'course_id' => $course_id,
            'user_id' => $user_id,
            'post_id' => $post_id,
            'activity_type' => $activity_type,
        );

        if($activity_type == 'quiz') {

            global $wpdb;
            $sql_str = $wpdb->prepare("SELECT * FROM " . LDLMS_DB::get_table_name( 'user_activity' ) . " WHERE user_id=%d AND post_id=%d AND activity_type=%s LIMIT 1", $ld_activity_args['user_id'], $ld_activity_args['post_id'], $ld_activity_args['activity_type'] );
            $activity = $wpdb->get_row( $sql_str );

        } else {

            $activity = learndash_get_user_activity($ld_activity_args);
        }

        return $activity;
    }

    function is_enrollment_date_valid($ld_activity) {

        if( $ld_activity ) {
            $enrollment_timestamp = $ld_activity->activity_started;

            $enrollment_date = date('Ymd', $enrollment_timestamp);

            if( $enrollment_date >= date('Ymd') ) {
                return date('Y-m-d H:i:s', $enrollment_timestamp);
            }
        }

        return false;
    }

    function get_object_category_ids($object_id, $object_type = 'course') {

        $taxonomy = "ld_{$object_type}_category";

        return $this->get_terms($object_id, $taxonomy);

    }

    function get_object_tag_ids($object_id, $object_type = 'course') {

        if($object_type== 'course') {
            $taxonomy = "ld_{$object_type}_tag";
        } else {
            $taxonomy = 'post_tag';
        }

        return $this->get_terms($object_id, $taxonomy);

    }

    function get_terms($post_id, $taxonomy) {

        $terms = wp_get_post_terms( $post_id, $taxonomy);

        $ids = array();
        foreach( $terms as $term ) {
            if(is_object($term)) {
                $ids[] = $term->term_id;
            }
        }

        return $ids;
    }

    function get_group_courses($object_type = 'course') {

        if($object_type=='quiz') {
            return false;
        }

        global $wpdb;

        $table_name = "{$wpdb->prefix}csld_events";
        $query_data = array();

        $query = "SELECT * FROM `{$table_name}` E 
                    WHERE E.`start` >= CURDATE()";

        if( $object_type == 'course' ) {
            $object_global_type = 'schedule_courses';

            $query .= " AND E.`object_type`= %s";
            $query_data[] = $object_global_type;
        } elseif( $object_type == 'lesson' ) {
            $object_global_type = 'schedule_lessons';

            $query .= " AND E.`object_type`= %s";
            $query_data[] = $object_global_type;
        } elseif( $object_type == 'topic' ) {
            $object_global_type = 'schedule_topics';

            $query .= " AND E.`object_type`= %s";
            $query_data[] = $object_global_type;
        }

        /*$query .= " AND E.`is_subsdate_as_startdate` != %s";
        $query_data[] = 'Yes';*/

        $query .= ";";

        $results = $wpdb->get_results($wpdb->prepare($query, $query_data));
        
        if( !empty($results) ) {
            return $results;
        }

        return false;
    }

    function is_user_role_exists($user_roles) {

        $schedule_user_role_exists = true;

        if( !empty($user_roles) ) {

            $user_roles = array_map( function($role) {
                if( !empty(trim($role)) ) {
                    return $role;
                }
            }, explode(',',$user_roles) );

            $current_user_roles = $this->get_current_user_roles();

            $schedule_user_role_exists = !empty(array_intersect($current_user_roles, $user_roles));

        }

        return $schedule_user_role_exists;
    }

    function is_user_id_exists($user_ids) {

        $schedule_user_id_exists = true;

        if( !empty($user_ids) ) {

            $user_ids = array_map( function($user_id) {
                if( !empty(trim($user_id)) ) {
                    return $user_id;
                }
            }, explode(',', $user_ids) );

            $current_user_id = get_current_user_id();

            $schedule_user_id_exists = in_array($current_user_id, $user_ids);
        }

        return $schedule_user_id_exists;
    }

    function get_current_user_roles() {
        if ( is_user_logged_in() ) {
            $user = wp_get_current_user();
            $roles = ( array )$user->roles;
            return $roles;
        } else {
            return array();
        }
    }

    function get_individual_courses($object_id, $object_type = 'course') {
        global $wpdb;

        $table_name = "{$wpdb->prefix}csld_events";
        $query_data = array();

        $query = "SELECT * FROM `{$table_name}` E 
                        WHERE E.`object_id` = %d 
                        ";
        $query_data[] = $object_id;

        if( $object_type == 'course' ) {

            $object_ld_type = 'sfwd-courses';

            $query .= " AND E.`object_type`= %s";
            $query_data[] = $object_ld_type;
        }

        /*$query .= " AND E.`is_subsdate_as_startdate` != %s";
        $query_data[] = 'Yes';*/

        $query .= "  AND E.`end` >= CURDATE()";

        $query .= ";";

        $results = $wpdb->get_results($wpdb->prepare($query, $query_data));

        if( !empty($results) ) {
            return $results;
        }

        return false;
    }

    function is_schedule_passed($object_id, $result, $object_type='course', $check_type = 'single') {

        $category_exists = true;
        $tag_exists = true;
        $group_exists = true;
        $user_has_access = true;

        $response = array(
            'user_has_access' => $user_has_access,
            'category_exists' => $category_exists,
            'tag_exists' => $tag_exists,
            'group_exists' => $group_exists
        );

        //Object related values
        $course_groups = learndash_get_course_groups($object_id);
        $course_categories = $this->get_object_category_ids($object_id, $object_type);
        $course_tags = $this->get_object_tag_ids($object_id, $object_type);

        //Result set values to check
        $user_roles = $result->excluded_role;
        $user_ids = $result->excluded_users;
        $group_id = absint($result->ld_group);
        $category_id = absint($result->category);
        $tag_id = absint($result->tag);

        $response['user_has_access'] = $this->user_has_access($user_roles, $user_ids, $result->user_filter_type);

        if( $response['user_has_access'] ) {

            if( $check_type=='single' && !empty($group_id) && ( !empty($course_groups) && !in_array($group_id, $course_groups) ) ) {
                $course_scheduled_groups[] = $group_id;
                $response['group_exists'] = false;
            }

            if( $check_type == 'group' ) {
                if( !empty($category_id) ) {
                    if( !in_array($category_id, $course_categories)) {
                        $response['category_exists'] = false;
                    }
                }
            }

            if( $check_type == 'group' ) {
                if( !empty($tag_id) ) {
                    if( !in_array($tag_id, $course_tags)) {
                        $response['tag_exists'] = false;
                    }
                }
            }

        }
$this->var_dump_error($response, true);
        if( $response['user_has_access'] && $response['group_exists'] && $response['category_exists'] && $response['tag_exists']) {
            return true;
        }

        return false;
    }

    function user_has_access($user_roles, $user_ids, $access_type = 'include') {

        $access_type = strtolower(sanitize_text_field($access_type));

        if( empty($access_type) ) {
            $access_type = 'include';
        }

        //Set default values according to access type
        if( $access_type == 'include' ) {
            $schedule_user_role_exists = true;
            $schedule_user_id_exists = true;
        } else {
            $schedule_user_role_exists = false;
            $schedule_user_id_exists = false;
        }

        if( !empty($user_roles) ) {
            $schedule_user_role_exists = $this->is_user_role_exists($user_roles);
        }

        if( !empty($user_ids) ) {
            $schedule_user_id_exists = $this->is_user_id_exists($user_ids);
        }

        if($access_type == 'include' && $schedule_user_role_exists && $schedule_user_id_exists) {
            return true;
        }

        if($access_type == 'exclude' && !$schedule_user_role_exists && !$schedule_user_id_exists) {
            return true;
        }

        return false;
    }

    function query_in_placeholders(array $values, $placeholder = '%s') {

        $format = null;

        if( !empty($values) ) {

            if (empty($placeholder)) {
                $placeholder = '%s';
            }

            $count = count($values);
            $placeholders = array_fill(0, $count, $placeholder);
            $format = implode(', ', $placeholders);
        }

        return $format;
    }

    function var_dump_error($var, $print=false) {
        ob_start();
        if($print) {
            print_r($var);
        } else {
            var_dump($var);
        }
        error_log(ob_get_clean());
    }


    /**
     * Prepare widget HTML with listing data
     *
     * @param $instance
     * @param $listing_data
     */
    private function output($instance, $listing_data) {

        $message = ! empty( $instance['message'] ) ? $instance['message'] : esc_html__( 'Your enrolled courses/lessons/topics and quizzes are scheduled on following dates.', 'cs_ld_addon' );

        ?>
        <p><?php _e( $message, 'cs_ld_addon' ); ?></p>
        <div id="ld_cs_listing">
            <?php
            $scheduled_dates = null;
            foreach ($listing_data as $content_type => $contents) {
                echo $this->schedule_block_html($content_type, $contents,$instance);
            }
            ?>
        </div>
        <?php
    }

    private function is_content_hidden_for_all($content_id) {
        $content_hidden_for_all = get_post_meta($content_id, '_csld_hide_all_users', true);

        return ($content_hidden_for_all == 'yes');
    }

    private function is_content_available($content_id) {
        $availability_status = get_option( 'course_scheduler_ld_addon_setting', 'hide' ) == 'show';

        $content_availability_status = get_post_meta($content_id,'_show_hide_action',true);

        if( !empty($content_availability_status) ) {
            $availability_status = $content_availability_status;
        }

        return ($availability_status == 'show');
    }

    /**
     * @param $content_type
     * @param $contents
     * @param $instance
     * @param $scheduled_dates
     * @return string|void
     */
    private function schedule_block_html($content_type, $contents, $instance) {

        $status_text = ! empty( $instance['status_text'] ) ? $instance['status_text'] : esc_html__( 'Status', 'cs_ld_addon' );
        $status_available_text = ! empty( $instance['status_available_text'] ) ? $instance['status_available_text'] : esc_html__( 'Available', 'cs_ld_addon' );
        $status_unavailable_text = ! empty( $instance['status_unavailable_text'] ) ? $instance['status_unavailable_text'] : esc_html__( 'Unavailable', 'cs_ld_addon' );

        $col_name = ucwords($content_type);
        $title_text = esc_html__('Title', 'cs_ld_addon' );
        $date_text = esc_html__('Date', 'cs_ld_addon' );

        $html = "";

        $html .= "<h3>{$col_name}</h3>";
        $html .= "<div class=\"accordion_item\">";
        $html .= "<table><tr><th>{$title_text}</th><th>{$date_text}</th><th>{$status_text}</th></tr>";

        foreach ($contents as $content_id => $content) {

            if($this->is_content_hidden_for_all($content_id)) {
                continue;
            }

            $permalink = get_permalink($content_id);

            //if( $content_type == 'courses' ) { //Courses

              //  $course_id = $content_id;
              //  $title = $content;

            //} else { //Lessons/Topics/Quizzes

                $course_id = $content['course_id'];
                $title = $content['title'];
            //}

/*            $scheduled_dates_strings = [];
            foreach ($scheduled_dates[$course_id] as $scheduled_date) {
                $this->var_dump_error($scheduled_date);

                $scheduled_dates_strings[] = implode('-', $scheduled_date);

            }

            $scheduled_dates_strings = implode(' / ', $scheduled_dates_strings);

            $html .= "<tr>";
            $html .= "<td><a href=\"{$permalink}\">{$title}</a></td>";
            $html .= "<td>{$scheduled_dates_strings}</td>";
            $html .= "</tr>";*/

            foreach ($content['schedules'] as $scheduled_raw_dates) {

                //$html .= "<tr>";

                $i = 0;
                $is_end_date = $scheduled_raw_dates['is_end_date'];

                foreach ($scheduled_raw_dates as $skey => $scheduled_raw_date) {
                    if( $skey == 'is_end_date' ) {
                        continue;
                    }

                    if( $is_end_date == 'no_end_date' && $skey == 'end_at' ) {
                        $html .= "<td>".__( 'No End Date', 'cs_ld_addon' )."</td>";
                        $html .= "<td>{$status_available_text}</td>";
                        $html .= "</tr>";
                        continue;
                    }
                    /**
                     * ld_cms_widget_date_format
                     *
                     * Filter to change widget output date format
                     */
                    $date_format = apply_filters('ld_cms_widget_date_format', 'd-M-y H:i');
                    
                    $scheduled_raw_date = date($date_format, $scheduled_raw_date);

                    $is_content_available = $this->is_content_available($content_id);

                    $html .= "<tr>";
                    if ($i == 0) {
                        $html .= "<td rowspan=\"2\" style=\"vertical-align : middle;text-align:center;\"><a href=\"{$permalink}\">{$title}</a></td>";
                    }

                    $html .= "<td>{$scheduled_raw_date}</td>";
                    if($is_content_available) {
                        $html .= "<td>{$status_available_text}</td>";
                    } else {
                        $html .= "<td class=\"ld-cs-sttus\"><span>{$status_unavailable_text}</span></td>";
                    }
                    $html .= "</tr>";
                    $i++;
                }
            }
        }

        $html .= "</table>";
        $html .= "</div>";

        return $html;
    }

    private function get_scheduled_dates($course_id) {

        $scheduled_dates = get_post_meta($course_id, 'course_schedule', true);

        if( !empty($scheduled_dates) ) {

            //Return today or future dates only
            $scheduled_dates = array_filter( array_map( function($date) {
                if( $date >= date('Y-m-d') ) {
                    return date('d M, Y', strtotime($date) );
                }
            }, $scheduled_dates) );

            //Sort dates
            usort($scheduled_dates, function ($date1, $date2) {
                return strtotime($date1) - strtotime($date2);
            });
        }

        //TODO: If dates are set in continuity, return that date range

        return $scheduled_dates;
    }

    private function get_user_completed_activities($user_id) {
        global $wpdb;

        $query = "SELECT DISTINCT LUA.`post_id` FROM wp_learndash_user_activity AS LUA WHERE LUA.`user_id`= %d AND LUA.`activity_status` = %d ORDER BY LUA.`course_id` ASC";
        $user_ld_activities = $wpdb->get_col($wpdb->prepare($query, $user_id, 1));

        return $user_ld_activities;
    }

    /**
     * Enqueue JQuery UI and accordion scripts
     */
    function wn_ld_cs_enqueue_scripts() {
        wp_enqueue_script('jquery-ui-accordion');
        wp_enqueue_style( 'jquery-ui', CS_LD_PLUGIN_URL . "/assets/css/jquery-ui.css", array() );
    }

} // class CS_LD_Widget

// register CS_LD_Widget widget
function register_cs_ld_widget() {
    if( is_user_logged_in() ) {
        register_widget('CS_LD_Widget');
    }
}
add_action( 'widgets_init', 'register_cs_ld_widget' );