<?php
/**
 * Abort if this file is accessed directly.
 */
if ( ! defined( 'ABSPATH' ) ) { 
    exit;
}

class CS_LD_TREE_HELPER { 

    /**
     *  Constructor
     */
    public function __construct() { 
        add_action ( 'wp_ajax_cs_ld_load_courses', array( $this, 'cs_ld_load_all_courses_function' ) );
        add_action ( 'wp_ajax_cs_ld_excluded_users', array( $this, 'cs_ld_load_excluded_users' ) );

        add_action ( 'wp_ajax_ld_cms_update_events', array( $this, 'updateEvents' ) );
        add_action ( 'wp_ajax_ld_cms_update_event', array( $this, 'updateEvent' ) );//By Me
        add_action ( 'wp_ajax_ld_cms_delete_event', array( $this, 'deleteEvent' ) );//By Me
        add_action ( 'wp_ajax_add_course_schedule', array( $this, 'addCourseSchedule' ) );
        add_action ( 'wp_ajax_move_course_schedule', array( $this, 'move_course_schedule_to_new_date' ) );
        add_action ( 'wp_ajax_increase_course_schedule_time', array( $this, 'increase_course_schedule_time' ) );
        
        add_action ( 'wp_ajax_remove_course_schedule', array( $this, 'removeCourseSchedule' ) );
        add_action ( 'wp_ajax_getEvents', array( $this, 'getEvents' ) );
        add_action ( 'wp_ajax_getUserEvents', array( $this, 'getUserEvents' ) );

        add_action ( 'wp_ajax_cs_ld_load_groups', array( $this, 'cs_ld_load_groups_ddl' ) );
        add_action ( 'wp_ajax_cs_ld_load_taxonomy', array( $this, 'cs_ld_load_taxonomy_ddl' ) );
        add_action ( 'wp_ajax_cs_ld_get_record', array( $this, 'cs_ld_get_record_by_id' ) );
        add_action ( 'wp_ajax_cs_ld_get_dropdown_vals', array( $this, 'cs_ld_get_dropdown_vals' ) );
        add_action ( 'wp_ajax_cs_ld_search_courses', array( $this, 'search_courses_cb' ) );
    }
    
    public function cs_ld_get_dropdown_vals() {
        if( !wp_doing_ajax() ) {
            return;
        }
        $current_user_id = get_current_user_id();

        $object_id = intval( sanitize_text_field( $_POST['object_id'] ) );
        $object_type = sanitize_text_field( $_POST['object_type'] );
        $arrays = [ 'object_id' =>$object_id, 'object_type' =>$object_type ];
        
        $group_ddls = '<option value="" data-id="">'.__( 'Select a Group', 'cs_ld_addon' ).'</option>';
        if( $object_type == 'sfwd-courses') { 
            $groups = learndash_get_course_groups( $object_id, true );
            $arrays['groups'] = $groups;
            foreach ( $groups as $group_id ) {
                $group_l_ids = learndash_get_groups_administrator_ids($group_id);
                if(( current_user_can( 'administrator' ) ) || in_array($current_user_id , $group_l_ids)){
                    $user_ids = learndash_get_groups_user_ids( $group_id );
                    $user_string = implode(',', $user_ids);
                    if( !empty( $user_string ) ) {
                        $user_string = ",".$user_string.",";
                    }
                    $group_ddls .= '<option value="'.$group_id.'" data-id="'.$user_string.'">'.get_the_title($group_id).'</option>';
                }
            }
            $arrays['courses'] = 1;
        } elseif( $object_type == 'sfwd-lessons' || $object_type == 'sfwd-topic' || $object_type == 'sfwd-quiz' ) {
            $course_id = learndash_get_course_id($object_id);
            $groups = learndash_get_course_groups( $course_id, true );
            $arrays['groups'] = $groups;
            foreach ( $groups as $group_id ) {
                $group_l_ids = learndash_get_groups_administrator_ids($group_id);
                if(( current_user_can( 'administrator' ) ) || in_array($current_user_id , $group_l_ids)){
                    $user_ids = learndash_get_groups_user_ids( $group_id );
                    $user_string = implode(',',$user_ids);
                    if( !empty( $user_string ) ) {
                        $user_string = ",".$user_string.",";
                    }
                    $group_ddls .= '<option value="'.$group_id.'" data-id="'.$user_string.'">'.get_the_title($group_id).'</option>';
                }
                
            }
            $arrays['course_id'] = $course_id;
        } 
        else {
            $groups = get_posts( array(
                'post_type'      =>	'groups',
                'posts_per_page' =>	-1,
            ) );
            foreach ( $groups as $group ) {
                $group_l_ids = learndash_get_groups_administrator_ids($group->ID);
                if(( current_user_can( 'administrator' ) ) || in_array($current_user_id , $group_l_ids)){
                    $user_ids = learndash_get_groups_user_ids( $group->ID );
                    $user_string = implode( ',', $user_ids );
                    if( !empty( $user_string ) ) {
                        $user_string = ",".$user_string.",";
                    }
                    $group_ddls .= '<option value="'.$group->ID.'" data-id="'.$user_string.'">'.$group->post_title.'</option>';
                }
            }
            $arrays['courses'] = 0;
        }
        $arrays['group_ddl'] = $group_ddls;
        wp_send_json( $arrays );
    }
    public function search_courses_cb() {

        if( !wp_doing_ajax() ) {
            return;
        }

        if( !check_ajax_referer('ld-cms-nonce', 'security')) {
            return;
        }

        if(isset($_POST['ld_cms_course_list_page_num'])) {
            $ld_cms_page = absint($_POST['ld_cms_course_list_page_num']);
        }

        $per_page_count = 5;

        if(empty($ld_cms_page)) {
            $ld_cms_page = 1;
        }

        $args = array(
            'posts_per_page' => $per_page_count,
            'post_type' => learndash_get_post_type_slug('course'),
            'post_status' => 'publish',
            'paged' => $ld_cms_page
        );

        if(isset($_POST['search_text'])) {
            $args['s'] = sanitize_text_field($_POST['search_text']);
        }

        //added by Waqardrigh
        $user_id=get_current_user_id();
        /*if ( !empty( $group_ids )  && learndash_is_group_leader_user($user_id)  && !learndash_is_admin_user($user_id) ) {
           
            $group_ids_query=array();
            $group_ids_query['relation'] = 'OR';
            foreach ($group_ids as $group_id) {

                if ( get_post_status ($group_id) != 'publish' ){
                    continue;
                }
                $group_ids_query[]= array(
                    'key'     => 'learndash_group_enrolled_' . $group_id,
                    'compare' => 'EXISTS',
                );
            }
            $args['meta_query']=array($group_ids_query);
        }*/


        $course_query = new WP_Query( $args ); //Used inside template below
        $max_num_pages = $course_query->max_num_pages;

        ob_start();
        include_once dirname(__FILE__) . '/views/calendar_view_ajax.php';
        $content = ob_get_clean();
        $response = array('content' => $content);


        if($ld_cms_page < $max_num_pages) {
            $response['next_page'] = $ld_cms_page + 1;
        } else {
            $response['next_page'] = 0;
        }

        wp_send_json( $response );
    }
    
    /**
     * Get record by id
     */
    public function cs_ld_get_record_by_id() {
        
        global $wpdb, $wp_roles;
        $all_roles = $wp_roles->roles;

        $rec_id = intval( sanitize_text_field( $_POST['rec_id'] ) );
        $object_id = intval( sanitize_text_field( $_POST['object_id'] ) );

        $results = $wpdb->get_results( 
            $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}csld_events WHERE id=%d and object_id=%d", $rec_id, $object_id), ARRAY_A
        );
        
        $record = array();
        if( count($results) > 0 ) {
            $record = $results[0];
            $start_dt = $record['start'];
            if( !empty( $start_dt ) ) {
                $record['start'] = date('Y-m-d', strtotime($start_dt));
                $record['start_time'] = date('h:i A', strtotime($start_dt));
                if( $record['start_time'] == '00:00:00' || $record['start_time'] == '00:00 am' || $record['start_time'] == '00:00 AM' )
                    $record['start_time'] = '';
            }
            $end_dt = $record['end'];
            if( !empty( $end_dt ) ) {
                $record['end'] = date('Y-m-d', strtotime($end_dt));
                $record['end_time'] = date('h:i A', strtotime($end_dt));
                if( $record['end_time'] == '00:00:00' || $record['end_time'] == '00:00 am' || $record['end_time'] == '00:00 AM' )
                    $record['end_time'] = '';
            }
            $excluded_users = $record['excluded_users'];
            if( ! empty( $excluded_users ) )
                $excluded_users = explode( ',', $excluded_users );

            if( is_array( $excluded_users ) && count( $excluded_users ) > 0 ) {
                $new_recs = array(  );
                foreach( $excluded_users as $user_id ) {
                    if( !empty( $user_id ) ) {
                        $user = get_user_by( 'ID', $user_id );
                        if( $user ) {
                            $new_recs[] = array( 'id' => $user_id, 'text' => $user->user_login );
                        }
                    }
                }
                $record['excluded_users'] = $new_recs;
            } else {
                $record['excluded_users'] = array();
            }

            $excluded_role = $record['excluded_role'];
            if( ! empty( $excluded_role ) )
                $excluded_role = explode( ',', $excluded_role );
            
            if( is_array( $excluded_role ) && count( $excluded_role ) > 0 ) {
                $new_recs = array(  );
                foreach( $excluded_role as $role ) {
                    $role_data = $all_roles[trim($role)];  
                    $new_recs[] = array( 'id' => trim($role), 'text' => $role_data['name'] );
                }
                
                $record['excluded_role'] = $new_recs;
            } else {
                $record['excluded_role'] = array();
            }
    
            
            $title = '';
            switch( $record['object_type'] ) {
                case 'sfwd-courses':
                    $title = LearnDash_Custom_Label::get_label( 'course' ) . ': '.get_the_title( $object_id );
                    break;
                case 'sfwd-quiz':
                    $title = LearnDash_Custom_Label::get_label( 'quiz' ) . ': '.get_the_title( $object_id );
                    break;
                case 'sfwd-lessons':
                    $title = LearnDash_Custom_Label::get_label( 'lesson' ) . ': '.get_the_title( $object_id );
                    break;
                case 'sfwd-topic':
                    $title = LearnDash_Custom_Label::get_label( 'topic' ) . ': '.get_the_title( $object_id );
                    break;
                default:
                    if( intval( $record['ld_group'] ) > 0 ) { 
                        switch( $record['object_type'] ) {
                            case "schedule_courses":
                                $title = __( 'Schedule Courses by Learndash Groups:', 'cs_ld_addon' ).' '.get_the_title( $record['ld_group'] );
                                break;
                            case "schedule_lessons":
                                $title = __( 'Schedule Lessons by Learndash Groups:', 'cs_ld_addon' ).' '.get_the_title( $record['ld_group'] );
                                break;
                            case "schedule_topics":
                                $title = __( 'Schedule Topics by Learndash Groups:', 'cs_ld_addon' ).' '.get_the_title( $record['ld_group'] );
                                break;
                            default:
                                $title = __( 'Schedule Learndash Groups:', 'cs_ld_addon' ).' '.get_the_title( $record['ld_group'] );
                                break;
                        }
                    } else {
                        $type = '';
                        if( intval( $record['category'] ) > 0 ) {
                            $type = self::get_post_type_term( $record['category'] );
                        } else if( intval( $record['tag'] ) > 0 ) {
                            $type = self::get_post_type_term( $record['tag'] );
                        }
                        switch( $type ) {
                            case 'sfwd-courses':
                                $title = LearnDash_Custom_Label::get_label( 'course' ) . __( ' by Category/Tag', 'cs_ld_addon' );
                                break;
                            case 'sfwd-lessons':
                                $title = LearnDash_Custom_Label::get_label( 'lesson' ) . __( ' by Category/Tag', 'cs_ld_addon' );
                                break;
                            case 'sfwd-topic':
                                $title = LearnDash_Custom_Label::get_label( 'topic' ) . __( ' by Category/Tag', 'cs_ld_addon' );
                                break;
                        }
                    } 
                    break;

            }
            $record['title'] = $title; 
        }
        echo wp_send_json( $record );  
    }
    
    function get_post_type_term( $id = 0 ) {
        
        $term = get_term( $id );
        if( $term  ) {
            $taxonomy = get_taxonomy( $term->taxonomy );
            if( $taxonomy ) {
                return $taxonomy->object_type[0];
            }
        }
        
        return '';
    }

    /**
     * Returns the course subscription date by course/lession/topic/quiz ID.
     *
     * @param $post_id
     *
     * @return subscription date
     */
    function get_course_subscription_date( $post_id = 0 ) {

        global $wpdb, $post;

        if( $post_id <= 0 )
            $post_id = $post->ID;

        $post_type = get_post_type( $post_id );
        $course_id = 0;
        if( $post_type == 'sfwd-courses' ) {

            $course_id = $post_id;
        } else {

            $course_id = learndash_get_course_id( $post_id );
        }

        if( $course_id > 0 ) {

            $sql_str = "SELECT activity_started FROM " . LDLMS_DB::get_table_name( 'user_activity' ) . " WHERE user_id='".get_current_user_id()."' and post_id='". intval( $course_id )."' and ( ( course_id='".intval( $course_id )."' and activity_type='course' ) or ( course_id='0' and activity_type='access' ) )";
            $activity_started = $wpdb->get_var( $sql_str );
            if( ! empty( $activity_started ) ) {
                return $activity_started;
            } else {
                $meta = get_post_meta( $course_id, '_sfwd-courses', true );
                if ( @$meta['sfwd-courses_course_price_type'] == 'open' ) {
                    if( is_user_logged_in() ) {

                        $udata = get_userdata( get_current_user_id() );
                        $registered = $udata->user_registered;

                        if( ! empty( $registered ) )
                            return strtotime( $registered );

                    }
                }
            }
        }

        return 0;
    }

    /**
     * Rendered added events on calendar
     */
    public function getEvents() {
        ini_set('display_errors', 'On');
        error_reporting(E_ALL);
        global $wpdb;
        $start = date('Y-m-d H:i:s', strtotime(sanitize_text_field($_REQUEST['start_at'])));
        $end = date('Y-m-d H:i:s', strtotime(sanitize_text_field($_REQUEST['end_at'])));
        $user_id =  absint($_REQUEST['user_id']);
        $type =  $_REQUEST['type'];

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

        $user_ids = get_users( array( 'role__in' => array( 'administrator'), 'fields' => 'ID' ) );

        $query = "SELECT * FROM {$table} WHERE ";
        //$query .= "( (`start` >= %s AND (`end` <= %s OR `end` IS NULL) ) or ) ";
        // nab** Changes
        $query .= "`start` <= %s AND ( ((`end` >= %s OR `end` IS NULL) and is_end_date='end_date') or is_end_date in ('one_day_end_date','no_end_date','end_date_yearly') )";

        if(learndash_is_group_leader_user($user_id)) {
            $user_ids[] = $user_id;
            if( count( $user_ids ) > 0 )
                $query .= "AND `posted_by` IN (" . implode(',', $user_ids) . ")";
        }

        $ld_help_cls_obj= new CS_LD_HELPER();        
        $results = $wpdb->get_results($wpdb->prepare($query, $end, $start));
        $events = array();
        $show_option = get_option( 'course_scheduler_ld_addon_setting' );
        foreach( $results as $rec )  {
            $object_id = $rec->object_id;
            $user_has_access = ld_course_check_user_access( $rec->object_id, $user_id );
            if ( !LD_CMS_HELPER::is_course_admin($rec->object_id) && !$user_has_access && !is_admin()) {
                continue;
            }
            if( intval( $rec->ld_group ) > 0 ){
                $group_students = learndash_get_groups_user_ids(intval( $rec->ld_group ));
                if(!in_array($user_id,$group_students) && !learndash_is_admin_user($user_id) && !learndash_is_group_leader_user($user_id)){
                    continue;
                }

            }
            $is_users_n_roles = $ld_help_cls_obj->is_exist_allowed_users_n_roles( $rec->user_filter_type, $rec->excluded_role, $rec->excluded_users, $user_id );
            if( $type == 'student' && !$is_users_n_roles ) {
                continue;
            } elseif (!$is_users_n_roles && !LD_CMS_HELPER::is_course_admin($rec->object_id)) {
                continue;
            }
            
            $post_type = get_post_type( $object_id );
            $course_id = 0;
            if( $post_type == 'sfwd-courses' ) {

                $course_id = $object_id;
            } else {

                $course_id = learndash_get_course_id( $object_id );
            }

            if( $type == 'student' && !ld_course_check_user_access( $course_id, $user_id ) ) {
                continue;
            }

            if(!$user_has_access && !is_admin()) {
                continue;
            }
            
            if( $rec->object_id != 0 ) {
                if( !learndash_is_admin_user($user_id) && !in_array( $rec->object_type, learndash_get_post_types() ) ) {
                    continue;
                }
            }
           
            
            $title = get_the_title( $object_id );

            $start = strtotime($rec->start);
            $end = strtotime($rec->end);
            if( $rec->is_end_date == 'no_end_date' ) {
                $end = strtotime('+2 Month', strtotime($_REQUEST['end_at']));
            }
			
            // nab** Changes
            if ($rec->is_end_date == 'end_date_yearly') {
                $duration_end_Interval =  absint($rec->duration_end_date);
                $duration_end_day = $rec->duration_type_end_date;

                // error_log('duration_end_Interval:' . var_export($duration_end_Interval, true));
                // error_log('duration_end_day:' . var_export($duration_end_day, true));
                $end = strtotime('+' . $duration_end_Interval . $duration_end_day, strtotime($_REQUEST['start_at']));
                // $endss = date('Y-m-d\TH:i:s', $endss);
            }
			
            $can_edit_event             = CS_LD_TREE_HELPER::check_event_edit($rec->object_id, $rec->object_parent_course, $user_id);
            $event = array();
            $event[ 'event_edit' ]      = $can_edit_event;
            $event[ 'id' ]              = $rec->id;
            $event[ 'rec_id' ]          = $rec->id;
            $event[ 'object_id' ]       = $object_id;
            $event[ 'object_link' ]     = get_permalink( $object_id );
            $event[ 'object_link_text' ]= '';
            switch ($rec->object_type) {
                case 'sfwd-courses':
                    $event[ 'object_link_text' ]= __( 'View Course', 'cs_ld_addon' );
                    break;
                case 'sfwd-lessons':
                    $event[ 'object_link_text' ]= __( 'View Lesson', 'cs_ld_addon' );
                    break;
                case 'sfwd-topic':
                    $event[ 'object_link_text' ]= __( 'View topic', 'cs_ld_addon' );
                    break;
                case 'sfwd-quiz':
                    $event[ 'object_link_text' ]= __( 'View Quiz', 'cs_ld_addon' );
                    break;
            }
            
            $event[ 'object_type' ]     = $rec->object_type;
            $event[ 'cid' ]             = $rec->object_parent_course;
            $event[ 'lid' ]             = $rec->object_parent_lesson;
            $event[ 'start' ]           = date('Y-m-d\TH:i:s', $start);
            $event[ 'end' ]             = date('Y-m-d\TH:i:s', $end);
            $event[ 'start_at' ]        = date('Y-m-d H:i:s', $start);
            $event[ 'end_at' ]          = date('Y-m-d H:i:s', $end);;
            $event[ 'is_subsdate_as_startdate' ] = $rec->is_subsdate_as_startdate;
            $event[ 'duration' ]        = absint($rec->duration);
            $event[ 'duration_type' ]   = $rec->duration_type;
			// nab** changes
            $event['duration_end_date']        = absint($rec->duration_end_date);
            $event['duration_type_end_date']   = $rec->duration_type_end_date;
            // nab** changes end
            $event[ 'editable' ]        = $can_edit_event;
            $event[ 'can_edit' ]          = $can_edit_event === true ? 1 : 0;
            //$event['allDay']          = true;
            $event['type']              = $type;
            $event['group_alert_text']  = __( 'This is group a event.', 'cs_ld_addon' );
            $current_visiblity          = get_post_meta( $object_id, '_show_hide_action', true );
            if( ( ! $current_visiblity || empty( $current_visiblity ) ) && intval( $object_id ) > 0  ) {
                $current_visiblity = $show_option;
            }
            if($current_visiblity =='show') {
                $event[ 'color' ] = '#00A300';
                $event[ 'isEventShow' ] = true;
            }
            else if($current_visiblity =='hide'){
                $event[ 'color' ] = '#FF0000';
                $event[ 'isEventShow' ] = false;
            }
            else{
                $event[ 'color' ] = '#808080';
            }

            $event[ 'textColor' ] = '#ffffff';
            $event[ 'title' ] = '';
            switch( $rec->object_type ) {
                case 'sfwd-courses':
                    if( intval( $rec->ld_group ) > 0 ) {
                        $event[ 'title' ] = LearnDash_Custom_Label::get_label( 'course' ).' "'.get_the_title( $object_id ).'" '.__( 'for group', 'cs_ld_addon' ).' "'.get_the_title( $rec->ld_group ).'"';
                    } else {
                        $event[ 'title' ] = LearnDash_Custom_Label::get_label( 'course' ) . ': '.get_the_title( $object_id );
                    }
                    break;
                case 'sfwd-quiz':
                    if( intval( $rec->ld_group ) > 0 ) {
                        $event[ 'title' ] = LearnDash_Custom_Label::get_label( 'quiz' ).' "'.get_the_title( $object_id ).'" '.__( 'for group', 'cs_ld_addon' ).' "'.get_the_title( $rec->ld_group ).'"';
                    } else {
                        $event[ 'title' ] = LearnDash_Custom_Label::get_label( 'quiz' ) . ': '.get_the_title( $object_id );
                    }
                    break;
                case 'sfwd-lessons':
                    if( intval( $rec->ld_group ) > 0 ) {
                        $event[ 'title' ] = LearnDash_Custom_Label::get_label( 'lesson' ) . ' "'.get_the_title( $object_id ).'" '.__( 'for group', 'cs_ld_addon' ).' "'.get_the_title( $rec->ld_group ).'"';
                    } else {
                        $event[ 'title' ] = LearnDash_Custom_Label::get_label( 'lesson' ) . ': '.get_the_title( $object_id );
                    }
                    break;
                case 'sfwd-topic':
                    if( intval( $rec->ld_group ) > 0 ) {
                        $event[ 'title' ] = LearnDash_Custom_Label::get_label( 'topic' ).' "'.get_the_title( $object_id ).'" '.__( 'for group', 'cs_ld_addon' ).' "'.get_the_title( $rec->ld_group ).'"';
                    } else {
                        $event[ 'title' ] = LearnDash_Custom_Label::get_label( 'topic' ) . ': '.get_the_title( $object_id );
                    }
                    break;

                case 'schedule_courses':
                    if( intval( $rec->ld_group ) > 0 ) {
                        $event[ 'title' ] = sprintf('%s %s %s', LearnDash_Custom_Label::get_label( 'courses' ), __(' of ', "cs_ld_addon"), get_the_title( $rec->ld_group ));
                    } else {
                        $event[ 'title' ] = LearnDash_Custom_Label::get_label( 'course' ) . __( ' by Category/Tag', 'cs_ld_addon' );
                    }
                    break;
                case 'schedule_lessons':
                    if( intval( $rec->ld_group ) > 0 ) {
                        $event[ 'title' ] = sprintf('%s %s %s', LearnDash_Custom_Label::get_label( 'lessons' ), __(' of ', "cs_ld_addon"), get_the_title( $rec->ld_group ));
                    } else {
                        $event[ 'title' ] = LearnDash_Custom_Label::get_label( 'lesson' ) . __( ' by Category/Tag', 'cs_ld_addon' );
                    }
                    break;
                case 'schedule_topics':
                    if( intval( $rec->ld_group ) > 0 ) {
                        $event[ 'title' ] = sprintf('%s %s %s', LearnDash_Custom_Label::get_label( 'topics' ), __(' of ', "cs_ld_addon"), get_the_title( $rec->ld_group ));
                    } else {
                        $event[ 'title' ] = LearnDash_Custom_Label::get_label( 'topic' ) . __( ' by Category/Tag', 'cs_ld_addon' );
                    }
                    break;
                default:
                    if( intval( $rec->ld_group ) > 0 ) {
                        $event[ 'title' ] = __( 'Group:', 'cs_ld_addon' ).' '.get_the_title( $rec->ld_group );
                    } else {
                        $type = '';
                        if( intval( $rec->category ) > 0 ) {
                            $type = self::get_post_type_term( $rec->category );
                        } else if( intval( $rec->tag ) > 0 ) {
                            $type = self::get_post_type_term( $rec->tag );
                        }
                        switch( $type ) {
                            case 'sfwd-courses':
                                $event[ 'title' ] = LearnDash_Custom_Label::get_label( 'course' ) . __( ' by Category/Tag', 'cs_ld_addon' );
                                break;
                            case 'sfwd-lessons':
                                $event[ 'title' ] = LearnDash_Custom_Label::get_label( 'lesson' ) . __( ' by Category/Tag', 'cs_ld_addon' );
                                break;
                            case 'sfwd-topic':
                                $event[ 'title' ] = LearnDash_Custom_Label::get_label( 'topic' ) . __( ' by Category/Tag', 'cs_ld_addon' );
                                break;
                        }
                    } 
                    break;
            }

            foreach( $events as $evt ) {
                if( in_array( $event[ 'object_id' ], $evt) ){
                    $repeated_courses[ $event[ 'object_id' ] ] = isset($repeated_courses[ $event[ 'object_id' ] ]) ? $repeated_courses[ $event[ 'object_id' ] ] + 1 : 1;

                    $event[ 'title' ] .= apply_filters('ldcms_pro_calender_event_id',"#".$repeated_courses[ $event[ 'object_id' ] ]);

                    break;
                }
            }

            if(isset($event[ 'title' ])){
                $event[ 'name' ] = $event[ 'title' ];
            }

            $events[] = $event;
        }
        wp_send_json( $events );
    }

    public static function check_event_edit($object_id, $parent_course, $user_id)
    {
        $parent_course_id = $parent_course;
        if( intval( $parent_course_id ) == 0 ) {
            $parent_course_id = $object_id;
        }
       
        if( is_super_admin( $user_id ) ) {
            return true; 
        }

        $user = wp_get_current_user();
        $roles = $user->roles;
        $in_role = false;
        $ld_cms_group_roles_schedule = get_option( 'ld_cms_group_roles_schedule', []);
        if( isset( $ld_cms_group_roles_schedule ) && is_array( $ld_cms_group_roles_schedule ) && count( $ld_cms_group_roles_schedule ) > 0 ) {
            foreach( $ld_cms_group_roles_schedule as $role )  {
                if( in_array($role, (array) $user->roles) ) {
                    $in_role = true;
                }
            }
        }
        
        if( $in_role ) {
            $ld_cms_group_selected_roles_manage_their_courses = get_option( 'ld_cms_group_selected_roles_manage_their_courses', 'no') == 'yes';
            if($ld_cms_group_selected_roles_manage_their_courses) {
                
                if (ld_course_check_user_access($parent_course_id,intval( $user_id ))) {
                    return true;
                } else{
                    return false;
                }
            } else {
                return true; 
            }
        }

        return false;


        // $can_edit_event = absint($rec->posted_by) === $user_id;

        // if($can_edit_event) {
        //     $referer_post_url = wp_get_referer();
        //     $referer_post_id  = url_to_postid( $referer_post_url );
        //     $can_edit_event   = has_shortcode(get_post_field('post_content', $referer_post_id), 'ld_cms_user_calendar') === false;
        // }

        // if($can_edit_event) {
        //     $can_edit_event = LD_CMS_HELPER::is_course_admin($rec->object_id, $user_id);
        // }

        // if(learndash_is_admin_user()){
        //     $can_edit_event = true;
        // }

        // if ( LD_CMS_HELPER::is_course_admin($rec->object_id) ) {
        //     $can_edit_event = true;
        // }

    }

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

        global $wpdb;

        $start = date('Y-m-d H:i:s', strtotime(sanitize_text_field($_POST['start'])));
        $end = date('Y-m-d H:i:s', strtotime(sanitize_text_field($_POST['end'])));
        $user_id =  absint($_POST['user_id']);

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

        $user_ids = get_users( array( 'role__in' => array( 'administrator'), 'fields' => 'ID' ) );

        $query = "SELECT * FROM {$table} WHERE 1=1 ";
        $query .= "AND `start` >= %s AND (`end` <= %s OR `end` IS NULL) ";

        if(learndash_is_group_leader_user($user_id)) {
            $user_ids[] = $user_id;
            $query .= "AND `posted_by` IN (" . implode($user_ids, ',') . ")";
        }

        $results = $wpdb->get_results($wpdb->prepare($query, $start, $end));
        
        $events = array();
        $show_option = get_option( 'course_scheduler_ld_addon_setting' );
        foreach( $results as $rec )  {
            if (!ld_course_check_user_access($rec->object_id,$user_id)) {
                continue; 
            }
            $object_id = $rec->object_id;
            $title = get_the_title( $object_id );
            $event = array();
            $event[ 'id' ]      = $rec->id;
            $event[ 'rec_id' ]      = $rec->id;
            $event[ 'object_id' ]   = $object_id;
            $event[ 'object_type' ] = $rec->object_type;
            $event[ 'cid' ]         = $rec->object_parent_course;
            $event[ 'lid' ]         = $rec->object_parent_lesson;
            $event[ 'start' ]       = $rec->start;
            $event[ 'end' ]         = $rec->end;
            $event[ 'posted_by' ]   = $rec->posted_by;
            $current_visiblity      = get_post_meta( $object_id, '_show_hide_action', true );
            if( ( ! $current_visiblity || empty( $current_visiblity ) ) && intval( $object_id ) > 0  ) {
                $current_visiblity = $show_option;
            }
            if($current_visiblity =='show')
                $event[ 'color' ] = '#00A300';
            else if($current_visiblity =='hide')
                $event[ 'color' ] = '#FF0000';
            else
                $event[ 'color' ] = '#808080';
            $event[ 'textColor' ] = '#ffffff';
            switch( $rec->object_type ) {
                case 'sfwd-courses':
                    $event[ 'title' ] = LearnDash_Custom_Label::get_label( 'course' ) . ': '.get_the_title( $object_id );
                    break;
                case 'sfwd-quiz':
                    $event[ 'title' ] = LearnDash_Custom_Label::get_label( 'quiz' ) . ': '.get_the_title( $object_id );
                    break;
                case 'sfwd-lessons':
                    $event[ 'title' ] = LearnDash_Custom_Label::get_label( 'lesson' ) . ': '.get_the_title( $object_id );
                    break;
                case 'sfwd-topic':
                    $event[ 'title' ] = LearnDash_Custom_Label::get_label( 'topic' ) . ': '.get_the_title( $object_id );
                    break;
                case 'schedule_courses':
                    $event[ 'title' ] = sprintf('%s %s %s', LearnDash_Custom_Label::get_label( 'courses' ), __('Group', "cs_ld_addon"), __('Schedule', "cs_ld_addon"));
                    break;
                case 'schedule_lessons':
                    $event[ 'title' ] = sprintf('%s %s %s', LearnDash_Custom_Label::get_label( 'lessons' ), __('Group', "cs_ld_addon"), __('Schedule', "cs_ld_addon"));
                    break;
                case 'schedule_topics':
                    $event[ 'title' ] = sprintf('%s %s %s', LearnDash_Custom_Label::get_label( 'topics' ), __('Group', "cs_ld_addon"), __('Schedule', "cs_ld_addon"));
                    break;
                default:
                    if( intval( $rec->ld_group ) > 0 ) {
                        $event[ 'title' ] = __( 'Group:', 'cs_ld_addon' ).' '.get_the_title( $rec->ld_group );
                    } else {
                        $type = '';
                        if( intval( $rec->category ) > 0 ) {
                            $type = self::get_post_type_term( $rec->category );
                        } else if( intval( $rec->tag ) > 0 ) {
                            $type = self::get_post_type_term( $rec->tag );
                        }
                        switch( $type ) {
                            case 'sfwd-courses':
                                $event[ 'title' ] = LearnDash_Custom_Label::get_label( 'course' ) . __( ' by Category/Tag', 'cs_ld_addon' );
                                break;
                            case 'sfwd-lessons':
                                $event[ 'title' ] = LearnDash_Custom_Label::get_label( 'lesson' ) . __( ' by Category/Tag', 'cs_ld_addon' );
                                break;
                            case 'sfwd-topic':
                                $event[ 'title' ] = LearnDash_Custom_Label::get_label( 'topic' ) . __( ' by Category/Tag', 'cs_ld_addon' );
                                break;
                        }
                    } 
                    break;
            }
            $events[] = $event; 
        }
        wp_send_json( $events );
    }

    /**
     * Schedule the courses
     */
    public function move_course_schedule_to_new_date() {
        
        global $wpdb;
        
        $rec_id         = sanitize_text_field( $_POST['rec_id'] );
        $start          = sanitize_text_field( $_POST['start'] );
        $remove_date    = sanitize_text_field( $_POST['remove_date'] );
        $prev_date      = sanitize_text_field( $_POST['prev_date'] );
       
        $date_v = explode( '-', $_POST['start'] );
        $object_id = intval( $_POST['object_id'] );
        $object_type = get_post_type( $object_id );

        $is_subsdate_as_startdate = 'No';
        $recs = $wpdb->get_results( "select * from ".$wpdb->prefix."csld_events where id='".$rec_id."'" );
        if( count( $recs ) > 0 ) {
            if( $recs[0]->is_subsdate_as_startdate == 'Yes' ) {
                $is_subsdate_as_startdate = 'Yes';
            }
        }

        if( $is_subsdate_as_startdate != 'Yes' ) {
            $date_validated = wp_checkdate( $date_v[1], $date_v[2], $date_v[0], 'Y-m-d' );
            if ( !$date_validated ) {
                wp_send_json( array('object_id'=>$object_id, 'object_type' => $object_type, 'status' => __( 'Invalid date format.', 'cs_ld_addon' ) ) );
                exit();
            }

            if( strtotime( date( 'Y-m-d' ) ) > strtotime( $start ) ) {
                wp_send_json( array( 'object_id' => $object_id, 'object_type' => $object_type, 'status'=>__( 'You can not add event behind the current date.', 'cs_ld_addon' )) );
                exit();
            }
        }
        $results = $wpdb->get_results( 
            $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}csld_events WHERE id=%d and object_id = %d", $rec_id, $object_id)
        );
        if( count($results) > 0 ) {
            $record = $results[0];
            $date1 = $record->start;
            $date2 = $record->end;
            $diff = abs( strtotime( $date2 ) - strtotime( $date1 ) );
            $end = strtotime( $start ) + $diff;
            $end = date( 'Y-m-d H:i:s', $end );
        } else {
            $end = $start;
        }

        $wpdb->update( 
            $wpdb->prefix.'csld_events', 
            array( 
                'start' => $start,
                'end' => $end
            ), 
            array( 'id' => $rec_id ), 
            array( '%s', '%s' ), 
            array( '%d' ) 
        );
        
        wp_send_json( array( 'object_id' => $object_id, 'rec_id' => $rec_id, 'object_type' => $object_type,'status' => 'success' ) );
    }

    public function update_event_date() {
        global $wpdb;

        $object_id  = sanitize_text_field( $_POST['object_id'] );
        $rec_id     = sanitize_text_field( $_POST['rec_id'] );
        $new_start_date      = sanitize_text_field( $_POST['start'] );
        $new_end_date        = sanitize_text_field( $_POST['end'] );
        $table = "{$wpdb->prefix}csld_events";
        $event = $wpdb->get_row( $wpdb->prepare("SELECT * FROM {$table} WHERE id=%d", $rec_id ), ARRAY_A);

        if($event) {
            list($saved_start_date, $saved_start_time) = explode(' ', $event['start']);
            list($saved_end_date, $saved_end_time) = explode(' ', $event['end']);

            $new_start = "{$new_start_date} {$saved_start_time}";
            $new_end = "{$new_end_date} {$saved_end_time}";

            $wpdb->update($table, ['start' => $new_start, 'end' => $new_end, 'is_end_date' => 'end_date'], ['id' => $rec_id], ['%s', '%s', '%s'], ['%d'] );
        }

        wp_send_json(['status' => 'success']);
    }

    public function increase_course_schedule_time() {
        $this->update_event_date();
        global $wpdb;
        
        $rec_id         = sanitize_text_field( $_POST['rec_id'] );
        $start          = sanitize_text_field( $_POST['start'] );
        $end            = sanitize_text_field( $_POST['end'] );
        $remove_date    = sanitize_text_field( $_POST['remove_date'] );
        $prev_date      = sanitize_text_field( $_POST['prev_date'] );
        $isDateEnd      = sanitize_text_field( $_POST['isDateEnd'] );

        $date_v = explode( '-', $_POST['start'] );
        $object_id = intval( $_POST['object_id'] );
        $object_type = get_post_type( $object_id );

        $is_subsdate_as_startdate = 'No';
        $recs = $wpdb->get_results( "select * from ".$wpdb->prefix."csld_events where id='".$rec_id."' " );
        if( count( $recs ) > 0 ) {
            if( $recs[0]->is_subsdate_as_startdate == 'Yes' ) {
                $is_subsdate_as_startdate = 'Yes';
            }
        }

        if( $is_subsdate_as_startdate != 'Yes' ) {
            $date_validated = wp_checkdate( $date_v[1], $date_v[2], $date_v[0], 'Y-m-d' );
            if ( !$date_validated ) {
                wp_send_json( array('object_id'=>$object_id, 'object_type' => $object_type, 'status' => __( 'Invalid date format.', 'cs_ld_addon' ) ) );
                exit();
            }

            if( strtotime( date( 'Y-m-d' ) ) > strtotime( $start ) ) {
                wp_send_json( array( 'object_id' => $object_id, 'object_type' => $object_type, 'status'=>__( 'You can not add event behind the current date.', 'cs_ld_addon' )) );
                exit();
            }
        }
        $results = $wpdb->get_results( 
            $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}csld_events WHERE id=%d and object_id = %d' ", $rec_id, $object_id)
        );
        if( count($results) > 0 ) {
            $record = $results[0];
            $date1 = $record->start;
            $date2 = $end;
            $diff = abs( strtotime( $date2 ) - strtotime( $date1 ) );
            $end = strtotime( $start ) + $diff;
            $end = date( 'Y-m-d H:i:s', $end );
        } else {
            $end = $end;
        }

        $wpdb->update( 
            $wpdb->prefix.'csld_events', 
            array( 
                'start' => $start,
                'end' => $end,
                'is_end_date' => 'end_date'
            ), 
            array( 'id' => $rec_id ), 
            array( '%s', '%s' ), 
            array( '%d' ), 
            array( '%s' ) 
        );
        
        wp_send_json( array( 'object_id' => $object_id, 'rec_id' => $rec_id, 'object_type' => $object_type,'status' => 'success' ) );
    }

    private function sanitizeEventData($event_data) {
        $default_data = array(
            'object_id' => 0,
            'object_parent_course' => 0,
            'object_parent_lesson' => 0,
            'object_type' => null,
            'is_subsdate_as_startdate' => 'No',
            'duration' => 0,
            'duration_type' => 'Day',
            'start' => null,
            'is_end_date' => 'end_date',
            'end' => null,
            'category' => null,
            'tag' => null,
            'user_filter_type' => 'Include',
            'excluded_role' => null,
            'excluded_users' => null,
            'ld_group' => null,
            'posted_by' => get_current_user_id(),
        );

        foreach($default_data as $key => $value) {
            if(isset($data[$key])) {
                if(is_null($value) && empty($data[$key])) {
                    $data[$key] = null;
                } elseif(is_numeric($value)) {
                    $data[$key] = absint($value);
                } else {
                    $data[$key] = sanitize_text_field($value);
                }
            }
        }

        return wp_parse_args($event_data, $default_data);
    }

    private function validateEventData($event_data) {
        $response = ['status' => 'success'];

        if( !isset($event_data['start_date']) || empty($event_data['start_date']) ) {
            //$response['message'] = __('Invalid start date/time provided');
            $response = [
                'status' => 'error',
                'message' => __('Invalid start date/time provided', "cs_ld_addon")
            ];
        } elseif( !isset($event_data['object_type']) || empty($event_data['object_type']) ) {
            $response = [
                'status' => 'error',
                'message' => __('Invalid object type provided', "cs_ld_addon")
            ];
        }

        return $response;

        $start_date = date('Y-m-d H:i:s', strtotime($event_data['start_date']));

        if( !isset($event_data['end_date']) && !empty($event_data['start_date'])) {
            $end_date = $event_data['start_date'];
        }

        if(!empty($end_date)) {
            $end_date = date('Y-m-d H:i:s', strtotime($event_data['end_date']));
            $event_data['end'] = $end_date;
        }

        if( !isset($event_data['object_type']) && !empty($event_data['object_id']) ) {
            $event_data['object_type'] = get_post_type($event_data['object_id']);
        }
    }

    public function deleteEvent() {
        global $wpdb;
        $table_name = "{$wpdb->prefix}csld_events";
        $data = $_POST['ld_cms_event'];
        $event_id = absint($data['event_id']);


        $deleted = $wpdb->delete($table_name, ['id' => $event_id], ['%d']);

        if($deleted) {
            wp_send_json(['status' => 'success', 'data' => ['id' => $event_id]]);
        }

        wp_send_json(['status' => 'error', 'data' => ['id' => $event_id]], 400);
    }

    public function updateEvent() {
        global $wpdb;
        $table_name = "{$wpdb->prefix}csld_events";
        $id=0;

        $data = $_POST['ld_cms_event'];
        
        //Form Data
        $rec_id                     = 0;
        if( isset($data['rec_id']) ) {
            $rec_id                     = absint( $data['rec_id'] );
        }
        $user_filter_type           = isset($data['filter_type'])? sanitize_text_field( $data['filter_type'] ): '';
        $is_subsdate_as_startdate   = ( isset( $data[ 'is_subsdate_as_startdate' ] ) && ($data[ 'is_subsdate_as_startdate' ] =='on' || $data[ 'is_subsdate_as_startdate' ] =='Yes') )? 'Yes' : 'No';
        $duration                   = isset($data['duration'])? sanitize_text_field( $data['duration'] ): '';
        $duration_type              = isset($data['duration_type'])? sanitize_text_field( $data['duration_type'] ): '';
        $start_date                 = isset($data['start_date'])? sanitize_text_field( $data['start_date'] ): date('Y-m-d');
        $start_time                 = isset($data['start_time'])? sanitize_text_field( $data['start_time'] ): '';
        $end_date                   = isset($data['end_date'])? sanitize_text_field( $data['end_date'] ): '';
        $end_time                   = isset($data['end_time'])? sanitize_text_field( $data['end_time'] ): '';
        $is_end_date                = isset( $data[ 'is_end_date' ] )? $data[ 'is_end_date' ] : 'one_day_end_date';
		// nab** changes
        $duration_end_date          = isset($data['duration_end_date']) ? $data['duration_end_date'] : '';
        $duration_type_end_date     = isset($data['duration_type_end_date']) ? $data['duration_type_end_date'] : '';
        // nab** changes end
        $start                      = date('Y-m-d H:i:s', strtotime("$start_date $start_time") );
        $end                        = date('Y-m-d H:i:s', strtotime("$end_date $end_time") );
        $object_id                  = absint( $data['object_id'] );
        
        if( !empty($object_id) ) {
            $object_type    = get_post_type( $object_id );
        } else {
            $object_type    = sanitize_text_field( $data['object_type'] );
        }

        if( !LD_CMS_HELPER::is_course_admin($object_id) ) {
            wp_send_json(['status' => 'error', 'message' => 'You\'re not authorized']);
        }

        if( empty( $user_filter_type ) ) {
            $user_filter_type = 'Include';
        }

        if( empty( $end_time ) ) {
            $end_time = '23:59';
        }

        if( empty( $start_time ) ) {
            $start_time = '00:00:00';
        }

        if( $is_end_date == 'one_day_end_date' ){
            $end = date( 'Y-m-d H:i:s', strtotime( "$start_date 23:59" ) );
        }
        
        if( $is_end_date == 'no_end_date' ){
            $end = date( 'Y-m-d H:i:s', strtotime( "+10 Year", strtotime( "$start_date 23:59" ) ) );
        }
        
        if( $is_end_date == 'end_date' ) {
            if( strtotime( $start ) > strtotime( $end ) ) {
                wp_send_json( array( 'object_id' => $object_id, 'object_type' => $object_type, 'status' => __( 'The start date cannot be after the end date.', 'cs_ld_addon' ) ) );
                exit();
            }
        }
		
		// nab*** changes
        if ($is_end_date == 'end_date_yearly' && $duration_end_date != '' &&  $duration_type_end_date != '') {
            $end_date = '';
            $end_time = '';
        } else {
            $duration_end_date = '';
            $$duration_type_end_date  = '';
        }

        $category       = isset($data['categories'])?sanitize_text_field( $data['categories'] ):'';
        $tag            = isset($data['tags'])?sanitize_text_field( $data['tags'] ):'';
        $course_id      = isset($data['parent_course_id'])?sanitize_text_field( $data['parent_course_id'] ):''; //Fix #8714
        $lesson_id      = isset($data['parent_lesson_id'])?sanitize_text_field( $data['parent_lesson_id'] ):''; //Fix #8714

        $excluded_role  = isset($data['user_roles'])?$data['user_roles']:'';
        if( is_array( $excluded_role ) && count( $excluded_role ) > 0 ) {
            $excluded_role = implode(',', $excluded_role );
        } else {
            $excluded_role = intval( $excluded_role );
        }

        $excluded_users = '';

        if( isset($data['users']) ) {

            if(is_array($data['users'])) {
                $excluded_users = array_filter(array_map('esc_attr', $data['users']));
                $excluded_users = implode(',', $excluded_users);
            }
        }

        $ld_group       = isset( $data['group'] ) ? sanitize_text_field( $data['group'] ):'';

        $event_data = [
            'id' => $rec_id,
            'object_id' => $object_id,
            'object_parent_course' => $course_id,
            'object_parent_lesson' => $lesson_id,
            'object_type' => $object_type,
            'is_subsdate_as_startdate' => $is_subsdate_as_startdate,
            'duration' => $duration,
            'duration_type' => $duration_type,
            'start' => $start,
            'is_end_date' => $is_end_date,
            'end' => $end,
			// nab** changes
            'duration_end_date' => $duration_end_date,
            'duration_type_end_date' => $duration_type_end_date,
            // nab** changes end
            'user_filter_type' => $user_filter_type,
            'excluded_role' => $excluded_role,
            'excluded_users' => $excluded_users,
            'ld_group' => $ld_group
        ];
       
        if( !in_array($object_type, learndash_get_post_types()) ) {
            $event_data['category'] = $category;
            $event_data['tag'] = $tag;
        }

        $event_data = $this->sanitizeEventData($event_data);

        if(empty($event_data['id'])) {
            $event_id = $this->record_exists_new($event_data);
        } else {
            $event_id = $event_data['id'];
        }

        if(!$event_id) {
            $wpdb->insert( $table_name, $event_data);
            $id = $wpdb->insert_id;
        } else {
            $id = $event_id;
            $wpdb->update( $table_name, $event_data,['id' => $id], null, ['%d']);
        }
        wp_send_json(['status' => 'success', 'data' => ['id' => $id]]);
        exit;

        // //Form Data
        // $data = $this->sanitizeEventData($event_data);
        // print_r($data); exit;
        // $event_id = absint($event_data['event_id']);
        // $object_id = absint($event_data['object_id']);

        // $data = $this->sanitizeEventData($data);

        // $event_id = $this->record_exists_new($data);
        // //$record_exists_id = $this->record_exists($table_name, $data);

        // if( $event_id ) {
        //     //Update
        //     $id = $event_id;
        // } else {
        //     //Insert
        //     $wpdb->insert( $table_name, $data);

        //     $id = $wpdb->insert_id;
        // }

        // if( !empty($object_id) ) {
        //     $event_data = array(
        //         'object_id' => $object_id,
        //         'object_type' => get_post_type($object_id),
        //         'start' => $start_date,
        //         'is_end_date' => !empty($end_date) ? 'Yes' : 'No',
        //         'end' => !empty($end_date) ? $end_date : NULL,
        //     );
        // }
        // wp_send_json(['status' => 'success', 'data' => ['id' => $id]]);
    }


    public function updateEvents() {
        global $wpdb;
        $events = "{$wpdb->prefix}csld_events";
        
        $data               = $_POST['ld_cms_event'];
        //var_dump($data);
        $object_type        = sanitize_text_field( $data['object_type'] );
        $category           = sanitize_text_field( $data['categories'] );
        $tag                = sanitize_text_field( $data['tags'] );

        $date_startdate     = sanitize_text_field( $data['is_subsdate_as_startdate'] );
        $duration           = sanitize_text_field( $data['duration'] );
        $duration_type      = sanitize_text_field( $data['duration_type'] );

        $is_end_date        = isset($data['is_end_date'])?$data['is_end_date']:'one_day_end_date';
        
        $start_date         = sanitize_text_field( $data['start_date'] );
        $end_date           = $is_end_date != 'one_day_end_date' ? sanitize_text_field( $data['end_date'] ) : $start_date; 

        $start_time         = !empty($data['start_time']) ? sanitize_text_field( $data['start_time'] ) : '00:00:00';
        $end_time           = !empty($data['end_time']) ? sanitize_text_field( $data['end_time'] ) : '23:59:00';

        $start              = date('Y-m-d H:i:s', strtotime("$start_date $start_time") );
        $end                = date('Y-m-d H:i:s', strtotime("$end_date $end_time") );
        
        if( $is_end_date != 'one_day_end_date' && strtotime($start) > strtotime($end) ) {
            wp_send_json( array( 'object_id' => $object_id, 'object_type' => $object_type, 'status' => __( 'The start date cannot be after the end date.', 'cs_ld_addon' ) ) );
            exit();
        }
        
        $user_filter_type   = !empty($data['filter_type']) ? sanitize_text_field( $data['filter_type'] ) : 'Include';

        $excluded_role      = is_array($data['user_roles']) && count($data['user_roles']) > 0 ? 
                              implode(',', $data['user_roles'] ) : intval($data['user_roles']);

        $excluded_users = "";
        if( isset($data['users']) && is_array($data['users'])) {
            $excluded_users = array_filter(array_map('esc_attr', $data['users']));
            $excluded_users = implode(',', $excluded_users);
        }
        
        if ( in_array($object_type, ['schedule_courses','schedule_lessons','schedule_topics'])) {
            switch ($object_type) {
                case 'schedule_courses': $object_type = 'sfwd-courses'; break;
                case 'schedule_lessons': $object_type = 'sfwd-lessons'; break;
                case 'schedule_topics': $object_type = 'sfwd-topic'; break;
            }
        }
        
        $taxonomies_id = !empty($category) ? $category : "";

        if( !empty($tag) ){
            $taxonomies_id = !empty($taxonomies_id) ? ",".$tag : $tag;            
        }

        // Terms - Category and Tag
        $inner_join_taxonomies = $where_taxonomies = "";
        if( !empty($taxonomies_id) ){
            $inner_join_taxonomies = "INNER JOIN {$wpdb->prefix}term_relationships AS tr ON e.object_id = tr.object_id";
            $where_taxonomies = "AND term_taxonomy_id IN ($taxonomies_id)";
        }

        $query = "SELECT e.id AS event_id, e.object_id AS object_id FROM $events AS e 
            INNER JOIN $wpdb->posts AS p ON  e.object_id = p.ID
            $inner_join_taxonomies
            WHERE 1 AND object_type = '$object_type' 
            $where_taxonomies";

        
        $result = $wpdb->get_results( $query );

        foreach ($result as $event) {
            //var_dump($event->event_id);
            $object_id = $event->object_id;

            if( !LD_CMS_HELPER::is_course_admin($object_id) ) { continue; }

            $event_data = [
                'is_subsdate_as_startdate' => $date_startdate,
                'duration' => $duration,
                'duration_type' => $duration_type,
                'is_end_date' => $is_end_date,
                'start' => $start,
                'end' => $end,
                'user_filter_type' => $user_filter_type,
                'excluded_role' => $excluded_role,
                'excluded_users' => $excluded_users,
            ];
            $wpdb->update( $events, $event_data,['id' => $event->event_id], null, ['%d']);
        }
        wp_send_json(['status' => 'success']);
        die();
    }

    /**
     * Schedule the courses
     */
    public function addCourseSchedule() {
        global $wpdb;
        $data = $_POST;
        //var_dump($data); exit;
        $rec_id                     = absint( $data['rec_id'] );
        $user_filter_type           = sanitize_text_field( $data['filter_type'] );

        $is_subsdate_as_startdate   = sanitize_text_field( $data['is_subsdate_as_startdate'] );
        $duration                   = sanitize_text_field( $data['duration'] );
        $duration_type              = sanitize_text_field( $data['duration_type'] );
         
        $start_date                 = sanitize_text_field( $data['start_date'] );
        $start_time                 = sanitize_text_field( $data['start_time'] );

        $end_date                   = sanitize_text_field( $data['end_date'] );
        $end_time                   = sanitize_text_field( $data['end_time'] );

        $is_end_date                = isset( $data[ 'is_end_date' ] )? $data[ 'is_end_date' ] : 'one_day_end_date';;


        $start = date('Y-m-d H:i:s', strtotime("$start_date $start_time") );
        $end = date('Y-m-d H:i:s', strtotime("$end_date $end_time") );



        $object_id = intval( $data['object_id'] );
        if( intval( $object_id ) > 0 ) {
            $object_type = get_post_type( $object_id );
        } else {
            $object_type = sanitize_text_field( $data['object_type'] );
        }



        if( empty( $user_filter_type ) ) {
            $user_filter_type = 'Include';
        }

        if( empty( $end_time ) ) {
            $end_time = '23:59';
        }
        if( empty( $start_time ) ) {
            $start_time = '00:00:00';
        }
        
        if( $data[ 'is_end_date' ] == 'one_day_end_date' ){
            $end = date( 'Y-m-d H:i:s', strtotime( "$start_date 23:59" ) );
        }
        
        if( $data[ 'is_end_date' ] == 'no_end_date' ){
            $end = date( 'Y-m-d H:i:s', strtotime( "+10 Year", strtotime( "$start_date 23:59" ) ) );
        }
        
        if( $data[ 'is_end_date' ] == 'end_date' ) {
            if( strtotime( $start ) > strtotime( $end ) ) {
                wp_send_json( array( 'object_id' => $object_id, 'object_type' => $object_type, 'status' => __( 'The start date cannot be after the end date.', 'cs_ld_addon' ) ) );
                exit();
            }
        }
        $category       = sanitize_text_field( $data['categories'] );
        $tag            = sanitize_text_field( $data['tags'] );
        $excluded_role  = $data['user_roles'];
        $cid            = sanitize_text_field( $data['course_id'] );
        $lid            = sanitize_text_field( $data['lesson_id'] );
        
        $excluded_role  = $data['user_roles'];
        if( is_array( $excluded_role ) && count( $excluded_role ) > 0 ) {
            $excluded_role = implode(',', $excluded_role );
        } else {
            $excluded_role = intval( $excluded_role );
        }

        $excluded_users = '';

        if( isset($data['users']) ) {

            if(is_array($data['users'])) {
                $excluded_users = array_filter(array_map('esc_attr', $data['users']));
                $excluded_users = implode(',', $excluded_users);
            }
        }
        
        $ld_group       = sanitize_text_field( $data['group'] );
        
        $date_v = explode( '-', $data['start_date'] );


        if( $is_subsdate_as_startdate != 'Yes' ) {

            list($year, $month, $day) = explode('-', $start_date);
            if ( checkdate($month, $day, $year) ) {
                wp_send_json( array( 'object_id' => $object_id, 'object_type' => $object_type, 'status' => __( 'Invalid date format.', 'cs_ld_addon' ) ) );
                exit();
            }
            
            if( strtotime( date( 'Y-m-d' ) ) > strtotime( $start ) ) {
                wp_send_json( array('object_id'=>$object_id, 'object_type'=>$object_type,'status'=>__( 'You can add event for future dates only.', 'cs_ld_addon' )) );
                exit();
            }
        } else {

            if( empty($duration) || empty($duration_type) ) {
                wp_send_json( array('object_id'=>$object_id, 'object_type'=>$object_type,'status'=>__( 'Interval fields are required.', 'cs_ld_addon' )) );
                exit();
            }
        }
        
        switch( $object_type ) {
            case 'schedule_courses':
            case 'schedule_lessons':
            case 'schedule_topics':
                $ld_group = 0;
                break;
            default:
                $category = 0;
                $category = 0;
                break;
        }

        $table_name = $wpdb->prefix . 'csld_events';

        $fields = array (
            'object_id' => $object_id,
            'object_parent_course' => absint($cid),
            'object_parent_lesson' => absint($lid),
            'object_type' => $object_type,
            'is_subsdate_as_startdate' => $is_subsdate_as_startdate,
            'duration' => $duration,
            'duration_type' => $duration_type,
            'start' => $start,
            'is_end_date' => $is_end_date,
            'end' => $end,
            'category' => absint($category),
            'tag' => absint($tag),
            'user_filter_type' => $user_filter_type,
            'excluded_role' => $excluded_role,
            'excluded_users' => $excluded_users,
            'ld_group' => $ld_group,
        );

        if( empty($rec_id) ) {
            $rec_id = false;
        }

        $record_exists_id = $this->record_exists($table_name, $fields, $rec_id);

        if( $record_exists_id ) {

            wp_send_json( array(
                'object_id' => $object_id,
                'object_type'=> $object_type,
                'status' => __( 'Schedule already exists', 'cs_ld_addon' )
            ));

            exit;
        }

        if( $rec_id ) {
            $this->cs_ld_update_event( $rec_id, $cid, $lid, $object_id, $object_type, $start, $end, $is_subsdate_as_startdate, $duration, $duration_type, $user_filter_type,$category, $tag, $excluded_role, $excluded_users, $ld_group, $is_end_date );
        } else {
            $rec_id = $this->cs_ld_add_event(  $cid, $lid, $start, $end,$is_subsdate_as_startdate, $duration, $duration_type, $user_filter_type, $object_id,$category, $tag,$object_type, $excluded_role, $excluded_users, $ld_group, $is_end_date );
        }

        wp_send_json( array( 'object_id' => $object_id, 'rec_id' => $rec_id, 'object_type' => $object_type,'status' => 'success' ) );
    }

    /**
     * Remove courses from schedule
     */
    public function removeCourseSchedule() {
        $rec_id         = sanitize_text_field( $_POST['rec_id'] );
        $object_id      = sanitize_text_field( $_POST['object_id'] );
        $result = $this->cs_ld_delete_event( $rec_id, $object_id );
        if ( $result > 0 ) {
            wp_send_json( array( 'object_id' => $object_id, 'rec_id' => $rec_id, 'status' => 'success' ) );
        }
        exit;
    }


    /**
     * Add new event in db.
     *
     * @since  1.0.0
     * @param  integer $object_id 
     * @param  string $object_type
     * @param  string $start
     * @param  integer $end
     */
    function cs_ld_add_event( $object_parent_course, $object_parent_lesson, $start, $end,  $is_subsdate_as_startdate, $duration, $duration_type, $user_filter_type ,$object_id=0, $category=0, $tag=0,$object_type='', $excluded_role='', $excluded_users='', $ld_group=0, $is_end_date = 'one_day_end_date' ) {

        global $wpdb;

        if( ! empty( $start ) ) {

            if( absint( $object_id ) == 0 || empty( $object_id ))
                $object_id = 0;

            $filter_type = $user_filter_type;
            if( empty( $filter_type ) ) {
                $filter_type = 'Include';
            }

            if( empty($is_subsdate_as_startdate) ) {
                $duration = 1;
                $duration_type = 'Day';
            }

            $insert_array = array (
                'object_id' => $object_id,
                'object_parent_course' => absint($object_parent_course),
                'object_parent_lesson' => absint($object_parent_lesson),
                'object_type' => $object_type,
                'is_subsdate_as_startdate' => $is_subsdate_as_startdate,
                'duration' => $duration,
                'duration_type' => $duration_type,
                'start' => $start,
                'is_end_date' => $is_end_date,
                'end' => $end,
                'category' => absint($category),
                'tag' => absint($tag),
                'user_filter_type' => $filter_type,
                'excluded_role' => $excluded_role,
                'excluded_users' => $excluded_users,
                'ld_group' => $ld_group,
            );

            $table_name = $wpdb->prefix . 'csld_events';

            $posted_by_col_exists = $wpdb->get_results("SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE column_name='posted_by' and TABLE_NAME='".$table_name."'");

            if( !empty( $posted_by_col_exists ) ) {
                $insert_array[ 'posted_by' ] = get_current_user_id();

            }

            $record_exists_id = $this->record_exists($table_name, $insert_array);

            if( $record_exists_id ) {
                return $record_exists_id;
            }

            $wpdb->insert( $table_name, $insert_array );

            if( $object_type != 'sfwd-topic' || $object_type != 'sfwd-quiz' ) {


                //commented by waqardrigh

                // $this->insert_child_posts($_POST['cid'], $object_id, $is_subsdate_as_startdate, $duration, $duration_type, $start, $is_end_date, $end, $category, $tag, $filter_type, $excluded_role, $excluded_users, $ld_group);


            }

            return $wpdb->insert_id;
        }
        return 0;
    }

    function record_exists_new($data) {
        if( isset($data['id']) && empty(absint($data['id'])) ) {
            unset($data['id']);
        }


        global $wpdb;
        $table_name = $wpdb->prefix . 'csld_events';
        $query = " SELECT `id` FROM {$table_name} WHERE 1 = 1";
        $placeholders = [];
        foreach ($data as $key => $value) {
            if(is_null($value)) {
                $query .= " AND `$key` IS NULL";
            } elseif(is_numeric($value)) {
                $query .= " AND `{$key}`=%d";
                $placeholders[] = $value;
            } else {
                $query .= " AND `{$key}`=%s";
                $placeholders[] = $value;
            }
        }

        $event_id = $wpdb->get_var($wpdb->prepare($query, $placeholders));

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

        return false;
    }

    function record_exists($table_name, $insert_array, $id=false, $check_date_conflict=false) {

        global $wpdb;

        $temp_data = array();

        if($check_date_conflict) {

            $remove_fields = array(
                'start',
                'end',
                'is_subsdate_as_startdate',
                'duration',
                'duration_type',
                'is_end_date'
            );

            foreach ($remove_fields as $remove_field) {
                $temp_data[$remove_field] = $insert_array[$remove_field];
                unset($insert_array[$remove_field]);
            }
        }

        $record_exists_query = "SELECT `id` FROM `{$table_name}` WHERE ";

        $record_exists_query_conditions = array();
        $record_exists_placeholders = array();


        foreach ($insert_array as $key => $value) {

            $record_exists_query_conditions[] = "`{$key}` = %s";

            $record_exists_placeholders[] = $value;
        }

        if( !empty($id) ) {
            $record_exists_query_conditions[] = "`id` != %d";

            $record_exists_placeholders[] = $id;
        }


        //Check if there is any date conflicts
        if( $check_date_conflict ) {

            $record_exists_query_conditions[] = "( 
                (%s BETWEEN `start` AND `end`) OR (%s BETWEEN `start` AND `end`) 
            )";

            $record_exists_placeholders[] = $temp_data['start'];
            $record_exists_placeholders[] = $temp_data['end'];
        }

        $record_exists_query_conditions = implode(' AND ', $record_exists_query_conditions);

        $record_exists_query .= $record_exists_query_conditions;



        $record_exists_id = $wpdb->get_var( $wpdb->prepare($record_exists_query, $record_exists_placeholders) );

        $this->var_dump_error($wpdb->last_query);

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

        return false;
    }

    // public function insert_child_posts( $course_id = 0, $object_id = 0, $is_subsdate_as_startdate, $duration, $duration_type, $start, $is_end_date = 'No', $end, $category = 0, $tag = 0, $filter_type, $excluded_role = '', $excluded_users = '', $ld_group = 0 ) {

    //     $post_type = get_post_type($object_id);

    //     $course_id = absint($course_id);

    //     $object_id = absint($object_id);

    //     if( $post_type == "sfwd-courses" ) {
    //         $children = learndash_get_lesson_list($object_id);
    //         if (!empty($children)) {
    //             foreach ($children as $child) {
    //                 $this->cs_ld_add_event( $object_id, 0, $start, $end, $is_subsdate_as_startdate, $duration, $duration_type, $filter_type ,$child->ID, absint($category), absint($tag),$child->post_type, $excluded_role, $excluded_users, $ld_group, $is_end_date );
    //                 $topics = learndash_get_topic_list($child->ID);
    //                 foreach ($topics as $topic) {
    //                     $topic_course_id = $this->get_topic_course_id($topic->ID);
    //                     if ( (int)$topic_course_id == (int)$object_id ) {
    //                         $this->cs_ld_add_event( $object_id, $child->ID,  $start, $end, $is_subsdate_as_startdate, $duration, $duration_type, $filter_type,$topic->ID, absint($category), absint($tag),$topic->post_type, $excluded_role, $excluded_users, $ld_group, $is_end_date);
    //                     }
    //                 }
    //             }
    //         }
    //     }

    //     if( $post_type == "sfwd-lessons" ) {
    //         $topics = learndash_get_topic_list($object_id);
    //         if (!empty($topics)) {
    //             foreach ($topics as $topic) {
    //                 $topic_course_id = $this->get_topic_course_id($topic->ID);
    //                 if ( (int)$topic_course_id == (int)$course_id ) {
    //                     $this->cs_ld_add_event( $course_id, $object_id, $start, $end, $is_subsdate_as_startdate, $duration, $duration_type, $filter_type,$topic->ID, absint($category), absint($tag),$topic->post_type, $excluded_role, $excluded_users, $ld_group, $is_end_date);
    //                 }
    //             }
    //         }
    //     }
    // }

    /**
     * update an event.
     *
     * @param  integer $object_id 
     * @param  string $object_type
     * @param  string $start
     * @param  integer $end
     */

    function cs_ld_update_event( $id, $cid, $lid, $object_id, $object_type, $start, $end,  $is_subsdate_as_startdate, $duration, $duration_type, $user_filter_type,$category=0, $tag=0, $excluded_role='', $excluded_users='', $ld_group=0, $is_end_date = 'one_day_end_date' ) {

        global $wpdb;

        if( ! empty( $start ) ) {

            if( absint( $object_id ) == 0 || empty( $object_id )) {
                $object_id = 0;
            }

            if( empty($is_subsdate_as_startdate) ) {
                $duration = 1;
                $duration_type = 'Day';
            }

            if( empty($is_end_date) ) {
                $is_end_date = 'one_day_end_date';
            }

            $fields = array(
                'object_id' => $object_id,
                'object_parent_course' => absint($cid),
                'object_parent_lesson' => absint($lid),
                'object_type' => $object_type,
                'is_subsdate_as_startdate' => $is_subsdate_as_startdate,
                'duration' => $duration,
                'duration_type' => $duration_type,
                'start' => $start,
                'is_end_date' => $is_end_date,
                'end' => $end,
                'category' => $category,
                'tag' => $tag,
                'user_filter_type' => $user_filter_type,
                'excluded_role' => $excluded_role,
                'excluded_users' => $excluded_users,
                'ld_group' => $ld_group,
            );

            $table_name = $wpdb->prefix . 'csld_events';

            $record_exists_id = $this->record_exists($table_name, $fields, $id);

            if( $record_exists_id ) {
                return $record_exists_id;
            }

            $wpdb->update(
                $table_name,
                $fields,
                array('id' => $id),
                // nab** changes
                array('%d', '%d', '%d', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%d', '%d', '%s', '%s', '%s', '%d', '%d', '%s')
            );

            return $id;
        }
        return 0;
    }

    
    /**
     * delete an event from db.
     *
     * @param  integer $id
     *  
     * @return  none
     */
    function cs_ld_delete_event( $id, $object_id ) {
        global $wpdb;
        if( intval( $id ) > 0 ) {
           return $wpdb->delete( $wpdb->prefix.'csld_events', array( 'id' => $id, 'object_id' => $object_id ), array( '%d', '%d' ) );
        }
        return false;
    }

    public function cs_ld_load_groups_ddl() {
        $rec_id   = $_REQUEST['rec_id'];
        $object_id    = $_REQUEST[ 'object_id' ]; 
        
        $groups = learndash_get_course_groups( $object_id, true );
        echo '<option value="">'.__( 'Select Group', 'cs_ld_addon' ).'</option>';
        if( is_array( $groups ) && count( $groups ) ) {
            foreach( $groups as $group_id ) {
                echo '<option value="'.$group_id.'">'.get_the_title( $group_id ).'</option>';
            }
        }
        exit;
    }

    public function cs_ld_load_taxonomy_ddl() {
        $taxonomy   = $_REQUEST['object_type'];
        $section    = $_REQUEST[ 'section' ]; 
        if( $section == 'category' ) {
            echo '<option value="">'.__( 'Select Category', 'cs_ld_addon' ).'</option>';
            switch( $taxonomy ) {
                case "ld_course_category":
                    if ( LearnDash_Settings_Section::get_section_setting('LearnDash_Settings_Courses_Taxonomies', 'ld_course_category' ) == 'yes' )
                        $this->generate_terms_ddl_options( 'ld_course_category' );
                    
                    if ( LearnDash_Settings_Section::get_section_setting('LearnDash_Settings_Courses_Taxonomies', 'wp_post_category' ) == 'yes')
                        $this->generate_terms_ddl_options( 'category' );
                    break;
                case "ld_lesson_category":
                    if ( LearnDash_Settings_Section::get_section_setting('LearnDash_Settings_Lessons_Taxonomies', 'ld_lesson_category' ) == 'yes')
                        $this->generate_terms_ddl_options( 'ld_lesson_category' );
                    if ( LearnDash_Settings_Section::get_section_setting('LearnDash_Settings_Lessons_Taxonomies', 'wp_post_category' ) == 'yes')
                        $this->generate_terms_ddl_options( 'category' );
                    break;
                case "ld_topic_category":
                    if ( LearnDash_Settings_Section::get_section_setting('LearnDash_Settings_Topics_Taxonomies', 'ld_topic_category' ) == 'yes')
                        $this->generate_terms_ddl_options( 'ld_topic_category' );
                    if ( LearnDash_Settings_Section::get_section_setting('LearnDash_Settings_Topics_Taxonomies', 'wp_post_category' ) == 'yes')
                        $this->generate_terms_ddl_options( 'category' );
                    break;
            }

        } else if( $section == 'tag' ) {
            echo '<option value="">'.__( 'Select Tag', 'cs_ld_addon' ).'</option>';
            switch( $taxonomy ) {
                case "ld_course_tag":
                    if ( LearnDash_Settings_Section::get_section_setting('LearnDash_Settings_Courses_Taxonomies', 'ld_course_tag' ) == 'yes')    
                        $this->generate_terms_ddl_options( 'ld_course_tag' );
                    if ( LearnDash_Settings_Section::get_section_setting('LearnDash_Settings_Courses_Taxonomies', 'wp_post_tag' ) == 'yes') 
                        $this->generate_terms_ddl_options( 'post_tag' );
                    break;
                case "ld_lesson_tag":
                    if ( LearnDash_Settings_Section::get_section_setting('LearnDash_Settings_Lessons_Taxonomies', 'ld_lesson_tag' ) == 'yes')
                        $this->generate_terms_ddl_options( 'ld_lesson_tag' );
                    if ( LearnDash_Settings_Section::get_section_setting('LearnDash_Settings_Lessons_Taxonomies', 'wp_post_tag' ) == 'yes')
                        $this->generate_terms_ddl_options( 'post_tag' );
                    break;
                case "ld_topic_tag":
                    if ( LearnDash_Settings_Section::get_section_setting('LearnDash_Settings_Topics_Taxonomies', 'ld_topic_tag' ) == 'yes' )
                        $this->generate_terms_ddl_options( 'ld_topic_tag' );
                    if ( LearnDash_Settings_Section::get_section_setting('LearnDash_Settings_Topics_Taxonomies', 'wp_post_tag' ) == 'yes')
                        $this->generate_terms_ddl_options( 'post_tag' );
                    break;
            }
        }
    }
    
    public function generate_terms_ddl_options( $taxonomy = '' ) {
        if( ! empty( $taxonomy ) ) {
            
            $terms = get_terms([
                'taxonomy' => $taxonomy,
                'hide_empty' => false,
            ]);

            foreach( $terms as $term ) {
                echo '<option value="'.$term->term_id.'">'.$term->name.'</option>';
            } 
        }
    }

    public function cs_ld_load_excluded_users() {
        
        // /**
        //  * If no query was sent, die here
        //  */ 
        // if ( ! isset( $_REQUEST['excluded_user_ids'] ) ) {
        //     wp_send_json_success( [] );
        // }

        global $wpdb;

       
        
       
        $excluded_users_results = array();
      //  $excluded_user_ids = esc_sql($_REQUEST['excluded_user_ids']);
	   if(isset($_REQUEST['excluded_user_ids']))
		{
			$excluded_user_ids = esc_sql($_REQUEST['excluded_user_ids']);
		}
		
		  if(isset($_REQUEST['selected_roles']))
		{
			$selected_roles = esc_sql($_REQUEST['selected_roles']);
		}
		
	       
        if (empty($selected_roles)) 
		{
           $selected_roles = array();
        }
		

        $roles_data = $this->wp_roles_array($selected_roles);

        if( is_multisite() ) {
            $blog_id = get_current_blog_id();
            $sql = "SELECT u.ID as id, u.user_login as text FROM {$wpdb->users} as u inner join {$wpdb->usermeta} as m on (u.ID = m.user_id)";
            $sql .= " WHERE m.meta_key = 'primary_blog' and m.meta_value='{$blog_id}'";

            $excluded_users_sql = $sql;

            if ( !empty( $excluded_user_ids ) ) {
                
                $excluded_user_ids = wp_list_pluck($excluded_user_ids,'id');

                $sql .= " and u.ID IN (".implode(',', $excluded_user_ids).")";
                $excluded_users_sql.= " and u.ID NOT IN (".implode(',', $excluded_user_ids).")";
            }
        } else {
            $sql = "SELECT ID as id, user_login as text FROM {$wpdb->users} ";

            $excluded_users_sql = $sql;


            /**
             * Build our query
             */
            if ( !empty( $excluded_user_ids ) ) {

                $excluded_user_ids = wp_list_pluck($excluded_user_ids,'id');

                $sql .= " WHERE ID NOT IN  (".implode(',', $excluded_user_ids).")";
                $excluded_users_sql.= " WHERE ID IN (".implode(',', $excluded_user_ids).")";
            }

        }

        /**
         * Fetch our results (store as associative array)
         */
        $results = $wpdb->get_results( $sql, 'ARRAY_A' );
        $user_lists = array();
        if (current_user_can( 'administrator' )){
            $user_lists = $results;
        }else{
            if(learndash_is_group_leader_user(get_current_user_id())){
                $group_users = learndash_get_groups_administrators_users(get_current_user_id(  ));
                foreach($results as $user){
                    if(in_array($user['id'] , $group_users)){
                        $user_lists[]= $user;
                    }
                }
            }
        }
        if (!empty($excluded_user_ids)) {
            $excluded_users_results = $wpdb->get_results( $excluded_users_sql, 'ARRAY_A' );
        }

        /**
         * Return our results
         */
        wp_send_json_success( array('roles'=>$roles_data['roles'], 'selected_roles'=>$roles_data['selected_roles'] , 'selected_users_list'=>$excluded_users_results,'users_list'=>$user_lists ) );
        
    }


    function wp_roles_array($selected_role_ids = array()) {
       
        $editable_roles = get_editable_roles();
        $roles =array();
        $select_roles = array();
        $selected_role_ids = wp_list_pluck($selected_role_ids,'id');
        foreach ($editable_roles as $role => $details) {
		
            if (in_array($role, $selected_role_ids)) {
				
                $selected_roles[] = array('role'=> esc_attr($role),'name'=>translate_user_role($details['name'])) ;
                continue;
            }
            $sub['role'] = esc_attr($role);
            $sub['name'] = translate_user_role($details['name']);
            $roles[] = $sub;
        }
        if(!empty($selected_roles)) 
		{
		   return array('roles'=>$roles,'selected_roles'=>$selected_roles);	
		}
		return array('roles'=>$roles);	
    }

    public function cs_ld_load_all_courses_function() {
        $node = $_REQUEST['course_id'];
        $cid = $_REQUEST['cid'];
        $lid = $_REQUEST['lid'];
        if( empty( $node ) ) {
            $courses_args = array( 'posts_per_page' => -1, 'post_type' => 'sfwd-courses', 'post_status'   => 'publish' );
            $courses = get_posts( $courses_args );
            $course_json = "";
            foreach( $courses as $course ) {
                $course_json .= empty( $course_json ) ? '':',';
                $course_json .= '{"name": "'.$course->post_title.'","id": '.$course->ID.',"post_type": "'.$course->post_type.'","cid":"0","lid":"0","load_on_demand": true}';
            }
            echo $course_json = '['.$course_json.']';
        } else {
            $post_type = get_post_type( $node );
            $lesson_json = '';
            switch( $post_type ) {
                case 'sfwd-courses':
                    $lessons = learndash_get_lesson_list( $node );
                    foreach( $lessons as $lesson ) {
                        
                        $has_sub_nodes = 'false';
                        $topics = learndash_get_topic_list( $lesson->ID, $cid );
                        if ( count( $topics ) > 0 ) {
                            $has_sub_nodes = 'true';
                        }
                        
                        $quizes = learndash_get_lesson_quiz_list( $lesson->ID, null );
                        if ( count( $quizes ) > 0 ) {
                            $has_sub_nodes = 'true';
                        }

                        $lesson_json .= empty( $lesson_json ) ? '':',';
                        $lesson_json .= '{"name": "'.$lesson->post_title.'","id": '.$lesson->ID.',"post_type": "'.get_post_type( $lesson->ID ).'","cid":"'.$node.'","lid":"0","load_on_demand": '.$has_sub_nodes.'}';

                    }

                    $quizzes = learndash_get_course_quiz_list( $node, null );
                    if ( count( $quizzes ) > 0 ) {
                        foreach ( $quizzes as $quiz ) {
                            $quiz_rec = $quiz['post'];
                            $lesson_json .= empty( $lesson_json ) ? '':',';
                            $lesson_json .= '{"name": "'.$quiz_rec->post_title.'","id": '.$quiz_rec->ID.',"post_type": "'.get_post_type( $quiz_rec->ID ).'","cid":"'.$node.'","lid":"0","load_on_demand": false}';
                        }
                    } 
                    
                    if( empty( $lesson_json ) ) {
                        echo '[]';
                    } else {
                        $lesson_json = '['.$lesson_json.']';
                        echo $lesson_json;
                    }
                    break;
                case 'sfwd-lessons':
                    
                    $topics = learndash_get_topic_list( intval( $node ), $cid );
                    $lesson_json = '';
                    foreach ( $topics as $topic ) {
                        $has_sub_nodes = 'false';
                        $quizes = learndash_get_lesson_quiz_list($topic->ID);
                        if ( count( $quizes ) > 0 ) {
                            $has_sub_nodes = 'true';
                        }
                        $lesson_json .= empty( $lesson_json ) ? '':',';
                        $lesson_json .= '{"name": "'.$topic->post_title.'","id": '.$topic->ID.',"post_type": "'.get_post_type($topic->ID).'","cid":"'.$cid.'","lid":"'.$node.'","load_on_demand": true}';
                    }

                    $quizes = learndash_get_lesson_quiz_list( $node, null, $cid );
                    foreach ( $quizes as $quiz_rec ) {
                        $quiz           = $quiz_rec['post'];
                        $lesson_json    .= empty( $lesson_json ) ? '':',';
                        $lesson_json    .= '{"name": "'.$quiz->post_title.'","id": '.$quiz->ID.',"post_type": "'.get_post_type( $quiz->ID ).'","cid": "'.$cid.'","lid":"'.$node.'","load_on_demand": false}';
                    } 
                    
                    if( ! empty( $lesson_json ) ) {
                        echo $lesson_json = '['.$lesson_json.']';
                    } else {
                        echo '[]';
                    }
                    break;

                case 'sfwd-topic':
                    
                    $topic_json = ''; 
                    $quizes = learndash_get_lesson_quiz_list( $node, null, $cid );
                    foreach ( $quizes as $quiz_rec ) {
                        $quiz           = $quiz_rec['post'];
                        $topic_json    .= empty( $topic_json ) ? '':',';
                        $topic_json    .= '{"name": "'.$quiz->post_title.'","id": '.$quiz->ID.',"post_type": "'.get_post_type( $quiz->ID ).'","cid": "'.$cid.'","lid":"'.$node.'","load_on_demand": false}';
                    } 
                    
                    if( ! empty( $topic_json ) ) {
                        echo $topic_json = '['.$topic_json.']';
                    } else {
                        echo '[]';
                    }
                    break;
                default:
                    echo '[]';
                    break;
            }
        }
        exit;
    }

    public function get_topic_course_id($topic_id) {
        if(!empty($topic_id)) {
            $course_id = get_post_meta($topic_id,'course_id',true);
            return $course_id;
        }
    }

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