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

/**
 * Include the license class
 */
if ( file_exists( CSLDP_DIR . 'license/LCMS_License.php' ) ) {
    require_once CSLDP_DIR . 'license/LCMS_License.php';
}

class CS_LD_HELPER {
    
    var $file_loaded = false;
    var $settings = [];
	
    private $license_class;

    public $page_tab;

    public $front_page_tab;
    /**
     *  Constructor
     */
    public function __construct() {

        $this->page_tab = isset( $_GET['tab'] ) ? $_GET['tab'] : 'general';
        $this->front_page_tab = isset( $_GET['tab'] ) ? $_GET['tab'] : 'calendar';
        require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
        if ( class_exists( 'SFWD_LMS' ) ) {

            /**
             * Adding settings tab
             */
            add_filter( 'plugin_action_links', array( $this, 'plugin_action_links' ), 10, 4 );
            add_filter( 'plugin_row_meta', array( $this, 'plugin_row_meta_links' ), 10, 4 );

            add_action ( 'admin_menu', array( $this, 'ldccAdminMenu' ), 1001 );
            add_action ( 'pre_get_posts', array( $this, 'alter_query' ) );
            add_action ( 'current_screen', array( __CLASS__, 'add_help_tab' ) );
            //add_action ( 'admin_notices', array( __CLASS__, 'add_help_notification' ) );
            add_action ( 'current_screen', array( __CLASS__, 'save_csld_settings' ) );
            if ( ! is_admin() ) {
                add_action( 'init', array( __CLASS__, 'save_csld_settings' ) );
            }
            add_filter ( 'admin_footer_text', array( __CLASS__, 'remove_my_footer_admin' ) );
            add_shortcode ( 'csld_schedule', array( $this, 'csld_schedule_shortcode' ) );
            add_shortcode ( 'ld_cms_calendar', array( $this, 'ld_cms_calendar_cb' ) );

            add_shortcode ( 'ld_cms_user_calendar', array( $this, 'ld_cms_user_calendar_cb' ) );
            add_shortcode ( 'ld_cms_monthly_user_calendar', array( $this, 'ld_cms_monthly_user_calendar_cb' ) );

            /**
             * The Elementor following hook callback will manage the LD course show/hide feature
             * when the elementor templates will be implemented for single course, lesson, topic etc.
             */
            add_action( 'elementor/frontend/the_content', array($this,'restrict_content_check') );

            add_filter ( 'learndash_shortcodes_content_args', array( $this, 'csld_shortcodes_content_args' ) );
            add_filter ( 'learndash_ld_course_list_query_args', array( $this, 'learndash_ld_course_list_query_args_cb' ), 10, 2 );
            add_action( 'admin_post_save_ld_cms_settings', array( $this, 'save_course_availability_email_tab' ) );
	        add_action( 'admin_notices', [ $this, 'settings_saved_notice' ], 100 );
            add_action( 'wp_ajax_ld_cms_events_list', [ $this, 'ld_cms_events_list_callback' ] );
	        $this->license_class = new LCMS_License();
        }
    }

    public function plugin_action_links( $actions, $plugin_file, $plugin_data, $context ) {
        if ( plugin_basename( LD_CPP_FILE ) == $plugin_file ) {
            $settings_link = sprintf( '<a href="%s">%s</a>', esc_url( admin_url( 'admin.php?page=calendar_course_settings' ) ), __( 'Settings', 'cs_ld_addon' ) );
            array_unshift( $actions, $settings_link );
        }

        return $actions;
    }

    public function plugin_row_meta_links( $plugin_meta, $plugin_file, $plugin_data, $status ) {
        if ( CSLDP_BASE_DIR == $plugin_file ) {
            $plugin_meta[] = sprintf( '<a href="https://www.arwebcrafts.com/docs/learndash-addons/learndash-course-planner-pro/" target="_blank">%s</a>', __( 'Documentation', 'cs_ld_addon' ) );
            $plugin_meta[] = sprintf( '<a href="https://www.arwebcrafts.com/open-support-ticket/" target="_blank">%s</a>', __( 'Support', 'cs_ld_addon' ) );
        }
        return $plugin_meta;
    }
            
    function csvtoarray($filename='', $delimiter=''){ 

        if(!file_exists($filename) || !is_readable($filename)) 
            return FALSE;
        $header = NULL;
        $data = array();
    
        if (($handle = fopen($filename, 'r')) !== FALSE ) {
            while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
            {   
                if(!$header){
                    $header = $row;
                }else{
                    $data[] = array_combine($header, $row);
                }
            }
            fclose($handle);
        }
        if(file_exists($filename)) @unlink($filename);
    
        return $data;
    }
    
    

    private function upload_excel_file( $files, $file_formats = [ 'csv' ] ) {
        $file = isset( $files['ldcms_import_file'] ) ? $files['ldcms_import_file'] : null;
        if ( ! empty( $file ) ) {
            $ext = strtolower( pathinfo( sanitize_text_field( $file['name'] ), PATHINFO_EXTENSION ) );

            if ( in_array( $ext, $file_formats ) ) {
                global $current_user;
                $upload_dir   = wp_upload_dir();
                $user_dirname = $upload_dir['basedir'] . '/ld_aq_uploads/' . $current_user->ID;
                if ( ! file_exists( $user_dirname ) ) {
                    wp_mkdir_p( $user_dirname );
                }

                $file_path = trailingslashit( $user_dirname ) . $file['name'];
                move_uploaded_file( $file["tmp_name"], $file_path );

                $this->file_loaded = true;

                return $file_path; //File upload successful
            }

            return 1; //Invalid file format
        }

        return 0; //Invalid file
    }

    /**
     * Modify ld_course_list shortcode filters based on calendar events
     *
     * @param $filter
     * @param $atts
     *
     * @return mixed|void
     */
    public function ld_cms_events_list_callback() {
        global $wpdb;
        // ini_set( 'display_errors', 'On' );
        // error_reporting(E_ALL);
        if ( ! wp_doing_ajax() ) {
            return;
        }

        if( !check_ajax_referer('ld-qie-ajax-nonce', 'ld_qie_ajax_nonce')) {
            return;
        }
        
        $response = array(
            'status'  => 'error',
            'message' => __( 'An unknown error occurred while importing file.', 'cs_ld_addon' )
        );
        
        //TODO implement wp_nonce check
        $entered = 0;
        $exists = 0;
        $ids  = [];
        if ( wp_doing_ajax() && !empty( $_POST ) && !empty( $_FILES ) && is_user_logged_in()) {
            $file_path = $this->upload_excel_file( $_FILES, [ 'csv' ] );
            if ( $file_path != 1 || $file_path != 0 ) {
                $table_events = "{$wpdb->prefix}csld_events";
                $events = $this->csvtoarray($file_path, ',');
                if( is_array( $events ) && count( $events ) > 0 ) {
                    foreach( $events as $event  ) {
                        
                        $where                  = '';
                        $object_title           = isset($event['object_title'])?$event['object_title']:'';
                        $object_id              = '';
                        if( !empty($object_title) ) {
                            $object_id              = $this->get_post_id_by_title($object_title);
                            $where                  .= !empty($where)?' and ':'';
                            $where                  .= " object_id='".$object_id."'";
                        }

                        $parent_course   = isset($event['parent_course'])?$event['parent_course']:'';
                        $object_parent_course              = '';
                        if( !empty($parent_course) ) {
                            $object_parent_course   = $this->get_post_id_by_title($parent_course);
                            $where                  .= !empty($where)?' and ':'';
                            $where                  .= " object_parent_course='".$object_parent_course."'";
                        }

                        $parent_lesson   = isset($event['parent_lesson'])?$event['parent_lesson']:'';
                        $object_parent_lesson              = '';
                        if( !empty($parent_lesson) ) {
                            $object_parent_lesson   = $this->get_post_id_by_title($parent_lesson);
                            $where                  .= !empty($where)?' and ':'';
                            $where                  .= " object_parent_lesson='".$object_parent_lesson."'";
                        }
                         
                        $object_type            = isset($event['object_type'])?$event['object_type']:'';
                        if( !empty($object_type) ) {
                            $where                  .= !empty($where)?' and ':'';
                            $where                  .= " object_type='".$object_type."'";
                        }

                        $is_subsdate_as_startdate    = isset($event['is_subsdate_as_startdate'])?$event['is_subsdate_as_startdate']:'';
                        if( !empty($is_subsdate_as_startdate) ) {
                            $where                  .= !empty($where)?' and ':'';
                            $where                  .= " is_subsdate_as_startdate='".$is_subsdate_as_startdate."'";
                        }

                        $duration            = isset($event['duration'])?$event['duration']:'';
                        if( !empty($duration) ) {
                            $where                  .= !empty($where)?' and ':'';
                            $where                  .= " duration='".$duration."'";
                        }

                        $duration_type          = isset($event['duration_type'])?$event['duration_type']:'';
                        if( !empty($duration_type) ) {
                            $where                  .= !empty($where)?' and ':'';
                            $where                  .= " duration_type='".$duration_type."'";
                        }

                        $start                  = isset($event['start'])?$event['start']:'';
                        if( !empty($start) ) {
                            $start                  = date('Y-m-d H:i', strtotime($start));
                            $where                  .= !empty($where)?' and ':'';
                            $where                  .= " start='".date('Y-m-d H:i', strtotime($start))."'";
                        }

                        $is_end_date            = isset($event['is_end_date'])?$event['is_end_date']:'';
                        if( !empty($is_end_date) ){
                            $where                  .= !empty($where)?' and ':'';
                            $where                  .= " is_end_date='".$is_end_date."'";
                        }

                        $end                    = isset($event['end'])?$event['end']:'';
                        if( !empty($end) ) {
                            $end                    = date('Y-m-d H:i', strtotime($end));
                            $where                  .= !empty($where)?' and ':'';
                            $where                  .= " end='".date('Y-m-d H:i', strtotime($end))."'";
                        }

                        $category_name              = isset($event['category'])?$event['category']:'';
                        $category              = '';
                        if( !empty($category_name) ) {
                            $category   = $this->get_term_id_by_title($category_name);
                            $where                  .= !empty($where)?' and ':'';
                            $where                  .= " category='".$category."'";
                        }

                        $tag_name              = isset($event['tag'])?$event['tag']:'';
                        $tag              = '';
                        if( !empty($tag_name) ) {
                            $tag   = $this->get_term_id_by_title($tag_name);
                            $where                  .= !empty($where)?' and ':'';
                            $where                  .= " tag='".$tag."'";
                        }
                        
                        $user_filter_type       = isset($event['user_filter_type'])?$event['user_filter_type']:'';
                        if( !empty($user_filter_type) ) {
                            $where                  .= !empty($where)?' and ':'';
                            $where                  .= " user_filter_type='".$user_filter_type."'";
                        }

                        $excluded_role          = isset($event['filtered_role'])?$event['filtered_role']:'';
                        if( !empty($excluded_role) ){
                            $where                  .= !empty($where)?' and ':'';
                            $where                  .= " excluded_role='".$excluded_role."'";
                        }

                        $filtered_users          = isset($event['filtered_users'])?$event['filtered_users']:'';
                        if( !empty($filtered_users) ){
                            $users = explode( ',', $filtered_users );
                            $users_where = '';
                            foreach( $users as $user ) {
                                $user_obj = get_user_by('login', trim( $user ));
                                if( $user_obj ) {
                                    $users_where .= !empty($users_where)?',':'';
                                    $users_where .= $user_obj->ID;
                                }
                                
                            }

                            if( !empty( $users_where ) ) {
                                $where                  .= !empty($where)?' and ':'';
                                $where                  .= " excluded_users='".$users_where."'";
                                $filtered_users          = $users_where;
                            }
                        }

                        $group   = isset($event['ld_group'])?$event['ld_group']:'';
                        $ld_group              = '';
                        if( !empty($group) ) {
                            $ld_group   = $this->get_post_id_by_title($group);
                            $where                  .= !empty($where)?' and ':'';
                            $where                  .= " ld_group='".$ld_group."'";
                        }
                        if( !empty( $category ) ||  !empty( $tag ) ||  !empty( $object_id ) || !empty( $object_parent_course ) || !empty( $object_parent_lesson ) || !empty( $object_type ) 
                        || !empty( $is_subsdate_as_startdate ) || !empty( $duration ) || !empty( $duration_type ) || !empty( $start )
                        || !empty( $is_end_date ) || !empty( $end ) || !empty( $user_filter_type ) || !empty( $excluded_role ) || !empty( $excluded_users ) || !empty( $ld_group )
                        ) {
                            $query_str = "SELECT * FROM $table_events WHERE ".$where;
                            
                            $results = $wpdb->get_results($query_str);
                            if( count( $results ) == 0 ) {
                                $event_data = [
                                    'object_id' => $object_id,
                                    'object_parent_course' => $object_parent_course,
                                    'object_parent_lesson' => $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,
                                    'user_filter_type' => $user_filter_type,
                                    'excluded_role' => $excluded_role,
                                    'excluded_users' => $filtered_users,
                                    'ld_group' => $ld_group,
                                    'category' => $category,
                                    'tag' => $tag
                                ];
                                
                                $wpdb->insert( $table_events, $event_data);
                                $ids[]  = $wpdb->insert_id;
                                $entered += 1;
                            } else {
                                $exists += 1;
                            }

                            $response = array(
                                'status'  => 'Success',
                                'message' => __( 'Imported the files.', 'cs_ld_addon' )
                            );
                        }
                    }
                }
            
                $response['entered'] = $entered;
                $response['exists'] = $exists;
                $log = '<div class="ld-cms-log-content">';
                $log .= '<div style="font-size: 1.2rem;font-weight:bold">'.__( 'File Uploaded Successfully: ', 'cs_ld_addon' ).'</div><br/>';
                $log .= '<div>'.__( 'Saved Records: ', 'cs_ld_addon' ).$entered.'</div>';
                $log .= '<div>'.__( 'Records Already Exists: ', 'cs_ld_addon' ).$exists.'</div>';
                $log .= '</div>';
            } else {
                    
                $response['entered'] = $entered;
                $response['exists'] = $exists;
                $log = '<div class="ld-cms-log-content">';
                $log .= '<div style="font-size: 1.2rem;font-weight:bold">'.__( 'Error wrong file format upload CSV only ', 'cs_ld_addon' ).'</div><br/>';
                //    $log .= '<div>'.__( 'Saved Records: ', 'cs_ld_addon' ).$entered.'<div>';
                //    $log .= '<div>'.__( 'Records Already Exists: ', 'cs_ld_addon' ).$exists.'<div>';
                $log .= '</div>';
            }  
        }
				      
		if($_FILES['ldcms_import_file']["error"] == 4 ) {
			$response['entered'] = $entered;
            $response['exists'] = $exists;
            $log = '<div class="ld-cms-log-content" style="background: #011B39;color: white !important;font-size: 0.95rem;padding: 10px 0px;margin-top: 10px;">';
            $log .= '<div style="font-size: 1.2rem;font-weight:bold">'.__( 'No file selected', 'cs_ld_addon' ).'</div>';
            $log .= '</div>';
		}
		
        $response['log'] = $log;
        $response['ids'] = $ids;
        wp_send_json( $response );
    }

    function get_post_id_by_title( $page_title ) {
        global $wpdb;
        $post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s", $page_title ));
        if ( $post )
            return $post;
    
        return '';
    }

    function get_term_id_by_title($term_title) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'terms';
        $term = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $table_name WHERE name = %s", $term_title ));
        if ( $term ) {
            return $term;
        }
    
        return '';
    }

    public 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' => 'one_day_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);
    }
    /**
     * Modify ld_course_list shortcode filters based on calendar events
     *
     * @param $filter
     * @param $atts
     *
     * @return mixed|void
     */
    public function learndash_ld_course_list_query_args_cb($filter, $atts) {

        if( get_option( 'ld_cms_hide_unavailable_courses', 'no') == 'no' ) {
            return $filter;
        }

        if( is_single() ) {
            return $filter;
        }

        $post_not_in = self::get_post_ids_to_hide();
        $filter['post__not_in'] = $post_not_in;

        return apply_filters('ld_cms_course_list_query_args', $filter, $atts);
    }

    /**
     * Get hidden courses ids
     *
     * @return array
     */
    public function get_post_ids_to_hide() {
        global $wpdb;

        $user_id = get_current_user_id();
        $user_groups = self::cs_ld_get_user_grups( $user_id );

        $table_events = "{$wpdb->prefix}csld_events";
        $today = current_time('Y-m-d');
        $post_not_in = [];

        $query_str = "SELECT * FROM $table_events E WHERE E.start >= DATE('" . $today . "') ";

        if( count( $user_groups ) > 0 ) {
            $query_str .= " and ( E.ld_group in ( ".implode(', ', $user_groups )." ) or E.ld_group = '' or E.ld_group = '0')";
        }

        $results = $wpdb->get_results($query_str);

        foreach ($results as $result) {


            $is_visible = self::check_node_availability($result->object_id);
            $start_date = date('Y-m-d', strtotime($result->start));
            $has_end_date = strtolower($result->start) === 'no';
            if( $has_end_date ) {
                $end_date = date('Y-m-d', strtotime($result->end));
            } else {
                $end_date = $start_date;
            }

            $in_excluded_users = ! $this->is_exist_allowed_users_n_roles( $result->user_filter_type, $result->excluded_role, $result->excluded_users );
            $in_between = $today >= $start_date && $today <= $end_date;
            if( $is_visible  ) {

                if ( !$in_between ) {
                    $post_not_in[] = $result->object_id;
                } else if ( $in_between && $in_excluded_users ) {
                    $post_not_in[] = $result->object_id;
                }

            } else {

                if( $in_between ) {
                    if ( !$in_excluded_users ) {
                        $post_not_in[] = $result->object_id;
                    }
                }
            }
        }

        return $post_not_in;
    }

    public function get_license_class() {
        return $this->license_class;
    }

    
    function restrict_content_check( $content ) {

        global $wpdb;
        global $post;
        $post_id = $post->ID;
        $post_type = get_post_type( $post_id );
        $course_id = 0;
        $user_id = 0;
        $user_roles = array();
        $user_groups = array();
        $output = '';
        $course_title ='';
        $ld_cms_schedule_excluded_user_roles = get_option( 'ld_cms_schedule_excluded_user_roles', []);
        if( empty( $ld_cms_schedule_excluded_user_roles ) ) {
            $ld_cms_schedule_excluded_user_roles = [];
        }

        if( isset( $post_id ) && ! empty( $post_id ) ) {
            // $object_id = $atts[ 'object_id' ];
            if( isset( $post_type ) && ( learndash_get_post_type_slug('course') ) ){
                $course_id = $post_id;
            }else if($post_id && ( $post_type == learndash_get_post_type_slug('lesson') || $post_type == learndash_get_post_type_slug('topic') || $post_type == learndash_get_post_type_slug('quiz') ) ){
                $course_id = learndash_get_course_id($post_id);
            }
            if( is_user_logged_in() ) {
                $user = wp_get_current_user();
                $user_id = $user->ID;
                $user_roles = ( array ) $user->roles;
                $user_groups = self::cs_ld_get_user_grups( $user_id );
            }



            if ( isset( $post_type ) && ( learndash_get_post_type_slug('course') == $post_type || learndash_get_post_type_slug('lesson') == $post_type || learndash_get_post_type_slug('topic') == $post_type || learndash_get_post_type_slug('quiz') == $post_type ) ) {
                $query = "SELECT * FROM {$wpdb->prefix}csld_events WHERE ";
                if( learndash_get_post_type_slug('course') == $post_type ) {
                    $query .= "( object_id='".$post_id."' and object_parent_course='0' )";
                } else {
                    $query .= "( object_id='".$post_id."' and object_parent_course='".$course_id."' )";
                }
                if( count( $user_groups ) > 0 ) {
                    $query .= " and ( ld_group in ( ".implode(', ', $user_groups )." )  or ld_group = '' or ld_group = '0' )";
                } else {
                    $query .= " and ( ld_group = '' or ld_group = '0' )";
                }
                $events = $wpdb->get_results($query);

                if( count( $events ) > 0 ) {
                    foreach( $events as $event ) {
                        $course_id = $event->object_parent_course;
                        $lesson_id = $event->object_parent_lesson;
                        $parent_check = self::check_show_hide_status( $event->object_parent_lesson, 0, $event->object_parent_course );
                        if( is_array( $parent_check ) && count( $parent_check ) > 0 ) {
                            $parent_msg = self::show_parent_hidden_message(  $event->object_id, $parent_check,$event->id );
                            if( $parent_check['status'] == true && ! empty( $parent_msg ) ) {
                                $output = '<div class = "csld-object-record">';
                                $course_title = '<div class="csld-object-title">'.get_the_title( $post_id ).'</div>';
                                $output .= self::show_parent_hidden_message(  $post_id, $parent_check ,$event->id);
                                $output .= '</div>';
                                continue;
                            } else {
                                $status = $parent_check['display'];
                            }
                        }
                        $parent_hidden_for_all_user_check = self::check_parent_hidden_for_all_user_meta_setting( $event->object_parent_lesson, 0, $event->object_parent_course );
                        if( is_array( $parent_hidden_for_all_user_check ) && count( $parent_hidden_for_all_user_check ) > 0 ) {
                            if( $parent_hidden_for_all_user_check['hidden'] == 'yes' ) {
                                $output = '<div class = "csld-object-record">';
                                $course_title= '<div class="csld-object-title">'.get_the_title( $post_id ).'</div>';
                                $short_code_message = '';
                                $message_option = html_entity_decode( get_user_meta( $user_id, 'cs_ld_addon_hide_for_all_'.strtolower( learndash_get_post_type_key($post_type) ) .'_message', true ) );
                                if( ! empty( $message_option ) ) {
                                    $short_code_message = $message_option;
                                } else {
                                    $short_code_message = html_entity_decode( get_option( 'cs_ld_addon_hide_for_all_'.strtolower( learndash_get_post_type_key($post_type) ) .'_message' ) );
                                }
                                $output .= $short_code_message;
                                $output .= '</div>';
                                continue;
                            } else {
                                $status = $parent_check['display'];
                            }
                        }
                        $list = '';
                        switch ($post_type) {
                            case learndash_get_post_type_slug('course'):
                                $list = $this->ldccShowHide( $post_id, 'ld_course_category', 'ld_course_tag', array($event), strtolower( learndash_get_post_type_key($post_type) ), true, $status, $course_id, $lesson_id );
                                break;
                            case learndash_get_post_type_slug('lesson'):
                                $list = $this->ldccShowHide( $post_id, 'ld_lesson_category', 'ld_lesson_tag', array($event), strtolower( learndash_get_post_type_key($post_type) ), true, $status, $course_id, $lesson_id );
                                break;
                            case learndash_get_post_type_slug('topic'):
                                $list = $this->ldccShowHide( $post_id, 'ld_topic_category', 'ld_topic_tag', array($event), strtolower( learndash_get_post_type_key($post_type) ), true, $status, $course_id, $lesson_id );
                                break;
                            case learndash_get_post_type_slug('quiz'):
                                $list = $this->ldccShowHide($post_id, 'category', 'post_tag', array($event), strtolower( learndash_get_post_type_key($post_type) ), true, $status, $course_id, $lesson_id);
                                break;
                            default:
                                $list = "";
                        }
                        if( ! empty( trim( $list ) ) ) {
                            $output .= '<div class = "csld-object-record">';
                            $course_title = '<div class="csld-object-title">'.get_the_title( $post_id ).'</div>';
                            $output .= $list;
                            $output .= '</div>';
                        }
                    }
                } else {
                    $csld_hide_all_users = get_post_meta( $post_id, '_csld_hide_all_users', true );
                    if( empty( $csld_hide_all_users ) ) {
                        $csld_hide_all_users = get_option( 'course_scheduler_ld_addon_hide_all_users' );
                    }
                    if( strtolower( $csld_hide_all_users ) == 'yes' ) {
                        $short_code_message = '';
                        $message_option = html_entity_decode( get_user_meta( $user_id, 'cs_ld_addon_hide_for_all_'.strtolower( learndash_get_post_type_key($post_type) ) .'_message', true ) );
                        if( ! empty( $message_option ) ) {
                            $short_code_message = $message_option;
                        } else {
                            $short_code_message = html_entity_decode( get_option( 'cs_ld_addon_hide_for_all_'.strtolower( learndash_get_post_type_key($post_type) ) .'_message' ) );
                        }
                        $course_title= '<div class="csld-object-title">'.get_the_title( $post_id ).'</div>';
                        $output .= '<div class = "csld-object-record">';
                        // $output .= '<div class="csld-object-title">'.get_the_title( $object_id ).'</div>';
                        $output .= $short_code_message;
                        $output .= '</div>';
                    }
                }
            }
        }

        $whit_listed_user_roles = array_intersect( $ld_cms_schedule_excluded_user_roles, $user_roles );

        if( count($whit_listed_user_roles) == 0 &&  ! empty($output) && ( strpos($content, '<div data-elementor-type="'.learndash_get_post_type_slug('course').'"') !== false  || strpos($content, '<div data-elementor-type="'.learndash_get_post_type_slug('lesson').'"') !== false  || strpos($content, '<div data-elementor-type="'.learndash_get_post_type_slug('topic').'"') !== false || strpos($content, '<div data-elementor-type="'.learndash_get_post_type_slug('quiz').'"') !== false ))
        {
            $css = '<style>.csld-object-record{
            text-align: center;
            font-size: 16px;
            line-height: 1.8;
            }.csld-object-title {
            text-align: center;
            padding: 2px 0px;
            // font-size: 18px;
            }.cs_ld_date_list{
                font-size: 16px;
                margin:0
                }#main{
                padding:28px;
            }</style>';
            return $css.$course_title.$output;
        }

        return $content;
    }


    /**
     * Returns the current user roles
     *
     * @return mixed
     */
    public function csld_shortcodes_content_args( $shortcode_sections ) {

        require_once( LEARNDASH_LMS_PLUGIN_DIR .'/includes/settings/class-ld-shortcodes-sections.php' );
        include( 'CSLD_Schedular_Pro_ShortCode.php' );
        $shortcode_sections['csld_Schedular_Pro'] = new CSLD_Schedular_Pro_ShortCode(  );

        return $shortcode_sections;
    }
    /**
     * Returns the current user roles
     *
     * @return mixed
     */
    function get_current_user_role() {
        if( is_user_logged_in() ) {
          $user = wp_get_current_user();
          $role = ( array ) $user->roles;
          return $role;
        } else {
          return array();
        }
    }
    /**
     * Returns the terms ids of a post
     *
     * @param $post_id
     * @param $taxonomy
     *
     * @return mixed
     */
    function get_terms_ids_by_id_n_taxonomy( $post_id, $taxonomy='' ) {

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

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

        return $ids;
    }

    /**
     * Alter global query to show courses
     *
     * @param $query
     * @return mixed
     */
    public function alter_query( $query ) {
        if(is_preview()){
            return;
        }
        global $wpdb;
        $user_id = get_current_user_id();
        
        $wpdb->query( "delete from ".$wpdb->prefix."csld_events where start < '".current_time('Y-m-d')."' and end < '".current_time('Y-m-d')."' and is_subsdate_as_startdate!='Yes'");

        if( !is_admin() && $query->is_main_query() ) {
            $post_type = '';
            if( array_key_exists('post_type', $query->query_vars ) ) {
                $post_type = @$query->query_vars['post_type'];
            }

            if( in_array( $post_type, learndash_get_post_types('course') ) ) {

                $user_groups = self::cs_ld_get_user_grups( $user_id );

                if( !is_single() && get_option( 'ld_cms_hide_unavailable_courses', 'no') == 'yes' ) {

                    $post_not_in = self::get_post_ids_to_hide();

                    $query->set( 'post__not_in', $post_not_in );

                } else {
                    $slug = $query->query[$post_type];
                    $post_obj = get_page_by_path( $slug , OBJECT, $post_type );
                    $post_id = $post_obj->ID;
                    
                    $current_course_id = learndash_get_course_id( $post_id );
                    if( empty( $current_course_id ) ){
                        $current_course_id = 0;
                    }    
                    $current_lesson_id = learndash_get_lesson_id( $post_id );
                    if( empty( $current_lesson_id ) ){
                        $current_lesson_id = 0;
                    }
                    $parent_check = false;
                    $parent_check_hidden_for_all_user_meta = false;
                    $course_id = 0;
                    $lesson_id = 0;

                    if( $post_type == 'sfwd-lessons' ) {
                        $course_id = learndash_get_course_id( $post_id );
                        $parent_check = self::check_show_hide_status( $course_id );
                        $parent_check_hidden_for_all_user_meta = self::check_parent_hidden_for_all_user_meta_setting( $course_id );
                    } else if( $post_type == 'sfwd-topic' ) {
                        $lesson_id = learndash_get_lesson_id( $post_id );
                        $parent_check = self::check_show_hide_status( $lesson_id );
                        $parent_check_hidden_for_all_user_meta = self::check_parent_hidden_for_all_user_meta_setting( $lesson_id );
                        $course_id = learndash_get_course_id( $post_id );
                    } else if( $post_type == 'sfwd-quiz' ) {
                        $lesson_id = learndash_get_lesson_id( $post_id );
                        if( intval( $lesson_id ) > 0  ) {
                            $parent_check = self::check_show_hide_status( $lesson_id );
                            $parent_check_hidden_for_all_user_meta = self::check_parent_hidden_for_all_user_meta_setting( $lesson_id );
                            $course_id = learndash_get_course_id( $post_id );
                        } else {
                            $course_id = learndash_get_course_id( $post_id );
                            $parent_check = self::check_show_hide_status( $course_id );
                            $parent_check_hidden_for_all_user_meta = self::check_parent_hidden_for_all_user_meta_setting( $course_id );
                        }
                    }

                    $parent_hidden = false;
                    $status = '';

                    if( is_array( $parent_check ) && count( $parent_check ) > 0 ) {
                        if( $parent_check[ 'status' ] == true ) {
                            $parent_hide_content = '<div class = "csld-object-parent-not-found">';
                            $parent_hide_content .= self::show_parent_hidden_message(  $post_id, $parent_check ,$parent_check['rec_id']);
                            $parent_hide_content .= '</div>';
                            
                            $GLOBALS['parent_hide_content'] = $parent_hide_content;
                            add_filter('learndash_content', function(  ) {
                                return '<div class="cs_ld_mng_frnt_msg">'.$GLOBALS['parent_hide_content'].'</div>';
                            });

                            $parent_hidden = true;
                        } else {
                            $status = $parent_check['display'];
                        }
                    }

                    if( $parent_hidden == false ) {

                        if( 'sfwd-courses' == $post_type ) {
                            $cat_taxonomy = 'ld_course_category';
                            $tag_taxonomy = 'ld_course_tag';
                        } elseif( 'sfwd-lessons' == $post_type ) {
                            $cat_taxonomy = 'ld_lesson_category';
                            $tag_taxonomy = 'ld_lesson_tag';
                        } elseif( 'sfwd-quiz' == $post_type ) {
                            $cat_taxonomy = 'category';
                            $tag_taxonomy = 'post_tag';
                        } elseif( 'sfwd-topic' == $post_type ) {
                            $cat_taxonomy = 'ld_topic_category';
                            $tag_taxonomy = 'ld_topic_tag';
                        }

                        $cat_string = '';
                        if( ! empty( $cat_taxonomy ) ) {
                            $cats = self::get_terms_ids_by_id_n_taxonomy( $post_id, $cat_taxonomy );
                            if( count( $cats ) > 0 ) {
                                $cat_string = implode(',', $cats);
                            }
                        }
                        $tag_string = '';
                        if( ! empty( $tag_taxonomy ) ) {
                            $tags = self::get_terms_ids_by_id_n_taxonomy( $post_id, $tag_taxonomy );
                            if( count( $tags ) > 0 ) {
                                $tag_string = implode(',', $tags);
                            }
                        }
                        $where = " object_id='0'";
                        if( 'sfwd-courses' == $post_type ) {
                            $where = "( object_id='".$post_id."' AND object_parent_lesson='0' and object_parent_course='0' ) OR object_id='0'";
                        } elseif( 'sfwd-lessons' == $post_type ) {

                            // $where = "( object_id='".$post_id."' and object_parent_lesson='0' and object_parent_course='".$current_course_id."' ) or object_id='0' or object_id='".$current_course_id."'  ";

                             $where = "( object_id='".$post_id."' AND object_parent_lesson='0' AND object_parent_course='0' ) 
                             OR
                             ( object_id='".$post_id."' AND object_parent_lesson='0' AND object_parent_course='".$current_course_id."' )
                             OR 
                             object_id='0' OR object_id='".$current_course_id."'  ";


                        } elseif( 'sfwd-quiz' == $post_type ||  'sfwd-topic' == $post_type ) {

                            $where = " 
                            ( object_id='".$post_id."' and object_parent_lesson='0' and object_parent_course='0' ) 
                            OR 
                            ( object_id='".$post_id."' and object_parent_lesson='".$current_lesson_id."' and object_parent_course='0' ) 
                            OR
                            ( object_id='".$post_id."' and object_parent_lesson='0' AND object_parent_course='".$current_course_id."' )
                            OR
                            ( object_id='".$post_id."' and object_parent_lesson='".$current_lesson_id."' and object_parent_course='".$current_course_id."' ) 
                            OR 
                            object_id='0' OR object_id='".$current_lesson_id."'  OR object_id='".$current_course_id."' ";
                        }

                        if( ! empty( $cat_string ) ) {
                            $where .= " or category in (".$cat_string.")";
                        }
                        if( ! empty( $tag_string ) ) {
                            $where .= " or tag in (".$tag_string.")";
                        }

                        if( ! isset( $post_obj->ID ) ) {
                            return $query;
                        }
                        
                        if( isset( $parent_check_hidden_for_all_user_meta ) && is_array( $parent_check_hidden_for_all_user_meta ) && array_key_exists( 'hidden', $parent_check_hidden_for_all_user_meta ) && $parent_check_hidden_for_all_user_meta['hidden'] == 'yes' ) {
                            
                            $parent_object_id = $parent_check_hidden_for_all_user_meta['object_id'];
                            $parent_object_type =  get_post_type( $parent_object_id );

                            $csld_hide_all_users = get_post_meta( $parent_object_id, '_csld_hide_all_users', true );
                            if( empty( $csld_hide_all_users ) ) {
                                $csld_hide_all_users = get_option( 'course_scheduler_ld_addon_hide_all_users' );
                            }

                            if( strtolower( $csld_hide_all_users ) == 'yes' ) {
                                $rec_type = '';
                                if( 'sfwd-courses' == $parent_object_type ) {
                                    $rec_type = 'Course';
                                } elseif( 'sfwd-lessons' == $parent_object_type ) {
                                    $rec_type = 'Lesson';
                                } elseif( 'sfwd-quiz' == $parent_object_type ) {
                                    $rec_type = 'Quiz';
                                } elseif( 'sfwd-topic' == $parent_object_type ) {
                                    $rec_type = 'Topic';
                                }

                                $short_code_message = '';
                                $message_option = html_entity_decode( get_user_meta( $parent_object_id, 'cs_ld_addon_hide_for_all_'.strtolower( $rec_type ) .'_message', true ) );
                                if( ! empty( $message_option ) ) {
                                    $short_code_message = $message_option;
                                } else {
                                    $short_code_message = html_entity_decode( get_option( 'cs_ld_addon_hide_for_all_'.strtolower( $rec_type ) .'_message' ) );
                                }
                                
                                $GLOBALS[ 'short_code_message' ] = $short_code_message;
                                add_filter('learndash_content', function() {
                                    return '<div class="cs_ld_mng_frnt_msg">'.$GLOBALS[ 'short_code_message' ].'</div';
                                });
                            }
                        } else {
                            $query_str2 = "SELECT * FROM {$wpdb->prefix}csld_events WHERE (".$where.")";
                            if( count( $user_groups ) > 0 ) {
                                $query_str2 .= " and ( ld_group in ( ".implode(', ', $user_groups )." ) or ld_group = '' or ld_group = '0')";
                            } else {
                                $query_str2 .= " and ( ld_group = '' or ld_group = '0' )";
                            }
                            
                            $results = $wpdb->get_results( $query_str2 );
                           
                            if( count( $results ) > 0 ) {
                                if( 'sfwd-courses' == $post_type ) {
                                    $this->ldccShowHide( $post_id, 'ld_course_category', 'ld_course_tag', $results, 'Course', false, $status, $course_id, $lesson_id );
                                } elseif( 'sfwd-lessons' == $post_type ) {

                                    $this->ldccShowHide( $post_id, 'ld_lesson_category', 'ld_lesson_tag', $results, 'Lesson', false, $status, $course_id, $lesson_id );
                                } elseif( 'sfwd-quiz' == $post_type ) {
                                    $this->ldccShowHide( $post_id, 'category', 'post_tag', $results, 'Quiz', false, $status, $course_id, $lesson_id );
                                } elseif( 'sfwd-topic' == $post_type ) {
                                    $this->ldccShowHide( $post_id, 'ld_topic_category', 'ld_topic_tag', $results, 'Topic', false, $status, $course_id, $lesson_id );
                                }
                            } else {
                                $csld_hide_all_users = get_post_meta( $post_id, '_csld_hide_all_users', true );
                                if( empty( $csld_hide_all_users ) ) {
                                    $csld_hide_all_users = get_option( 'course_scheduler_ld_addon_hide_all_users' );
                                }
                                
                                if( strtolower( $csld_hide_all_users ) == 'yes' ) {
                                    $rec_type = '';
                                    if( 'sfwd-courses' == $post_type ) {
                                        $rec_type = 'Course';
                                    } elseif( 'sfwd-lessons' == $post_type ) {
                                        $rec_type = 'Lesson';
                                    } elseif( 'sfwd-quiz' == $post_type ) {
                                        $rec_type = 'Quiz';
                                    } elseif( 'sfwd-topic' == $post_type ) {
                                        $rec_type = 'Topic';
                                    }

                                    $short_code_message = '';
                                    $message_option = html_entity_decode( get_user_meta( $post_id, 'cs_ld_addon_hide_for_all_'.strtolower( $rec_type ) .'_message', true ) );
                                    if( ! empty( $message_option ) ) {
                                        $short_code_message = $message_option;
                                    } else {
                                        $short_code_message = html_entity_decode( get_option( 'cs_ld_addon_hide_for_all_'.strtolower( $rec_type ) .'_message' ) );
                                    }
                                    
                                    $GLOBALS[ 'short_code_message' ] = $short_code_message;
                                    add_filter('learndash_content', function() {
                                        return '<div class="cs_ld_mng_frnt_msg">'.$GLOBALS[ 'short_code_message' ].'</div>';
                                    });
                                }
                            }
                        }
                    }

                }


                return $query;
            }
        }

        return $query;
    }

    /**
     * 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='0' and activity_type='course' ) or ( course_id='".intval( $course_id )."' and activity_type='course' ) or ( course_id='".intval( $course_id )."' and activity_type='access' ) 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;
    }

    /**
     * Returns the terms ids of a post
     *
     * @param $post_id
     * @param $taxonomy
     *
     * @return mixed
     */
    function is_exist_in_groups( $post_id, $group_id = 0 ) {

        $parent_course_id = self::get_parent_course_of_object( $post_id );

        $is_conditions_met = false;
        if( ! empty( $group_id ) && intval( $group_id ) > 0 )  {
            if( learndash_group_has_course( $group_id, $parent_course_id ) ) {
                $is_conditions_met = true;
            } else {
                $is_conditions_met = false;
            }
        } else {
            $is_conditions_met = true;
        }

        return $is_conditions_met;
    }

    /**
     * Returns the terms ids of a post
     *
     * @param $post_id
     * @param $taxonomy
     *
     * @return mixed
     */
    function is_exist_in_terms( $cat_id, $post_id, $taxonomy, $type ) {

        $is_conditions_met = false;
        if( ! empty( $cat_id ) && intval( $cat_id ) > 0 )  {
            if( has_term( $cat_id, $taxonomy, $post_id ) ) {
                $is_conditions_met = true;
            } else {
                $post_type = get_post_type( $post_id );
                if( $post_type == 'sfwd-lessons' ) {
                    $course_id = learndash_get_course_id( $post_id );

                    $taxotype = '';
                    if( $type=='category' )
                        $taxotype = 'ld_course_category';
                    else
                        $taxotype = 'ld_course_tag';
                    if( has_term( $cat_id, $taxotype, $course_id ) ) {
                        $is_conditions_met = true;
                    } else {
                        $is_conditions_met = false;
                    }
                } else if( $post_type == 'sfwd-topic' ) {
                    $taxotype = '';
                    if( $type=='category' )
                        $taxotype = 'ld_lesson_category';
                    else
                        $taxotype = 'ld_lesson_tag';
                    $lesson_id = learndash_get_lesson_id( $post_id );

                    if( has_term( $cat_id, $taxotype, $lesson_id ) ) {
                        $is_conditions_met = true;
                    } else {
                        $course_id = learndash_get_course_id( $post_id );

                        if( $type=='category' )
                            $taxotype = 'ld_course_category';
                        else
                            $taxotype = 'ld_course_tag';
                        if( has_term( $cat_id, $taxotype, $course_id ) ) {
                            $is_conditions_met = true;
                        } else {
                            $is_conditions_met = false;
                        }
                    }
                } else {
                    return false;
                }
            }
        }  else {
            $is_conditions_met = true;
        }

        return $is_conditions_met;
    }

    /**
     * Returns user group ids
     *
     * @param $user_id
     *
     * @return $user_groups
     */
    function cs_ld_get_user_grups( $user_id = 0 ) {
        global $wpdb;
        $user_groups = learndash_get_users_group_ids( $user_id );
        $sql_str = "SELECT usermeta.meta_value as group_ids FROM ". $wpdb->usermeta ." as usermeta INNER JOIN ". $wpdb->posts ." as posts ON posts.ID=usermeta.meta_value WHERE user_id ='".$user_id."'  AND meta_key LIKE 'learndash_group_leaders_%' AND posts.post_status = 'publish'";
        $group_ids = $wpdb->get_col( $sql_str );
        $return = array_merge( $user_groups, $group_ids );
        return $return;
    }

    /**
     * Returns true if user is allowed to view course/lesson/topic/qui
     *
     * @param $user_filter_type
     * @param $excluded_role
     * @param $excluded_users
     *
     * @return true/false
     */
    function is_exist_allowed_users_n_roles( $user_filter_type, $excluded_role, $excluded_users, $select_user_id=0 ) {
        $roles = array();
        $user_id = 0;
        if( $select_user_id == 0 ) {
            if( is_user_logged_in() ) {
                $user = wp_get_current_user();
                $user_id = $user->ID;
                $roles = ( array ) $user->roles;
            }
        } else{
            $user_id = $select_user_id;
            $userdata = get_userdata($user_id);
            $roles = ( array ) $userdata->roles;
        }
        if( ( empty( $excluded_users ) || $excluded_users=="0" ) && ( empty( $excluded_role ) || $excluded_role=='0') ) {
            return true;
        }
        
        if( $user_filter_type == 'Include' ) {

            $is_user_include_role_allowed = false;
            if( !empty( $excluded_role ) ) {
                $current_roles = explode( ',', $excluded_role );
                foreach( $current_roles as $crole ) {
                    foreach( $roles as $role ) {
                        if( !empty( $crole ) && $crole!='0' && $role==$crole ) {
                            $is_user_include_role_allowed = true;
                        }
                    }
                }
            } else {
                $is_user_include_role_allowed = true;
            }
            
            $is_include_user_allowed = false;
            if( !empty( $excluded_users ) ) {
                $current_users = explode( ',', $excluded_users );
                foreach( $current_users as $user ) {
                    if( ! empty( $user ) && $user != '0' && $user == $user_id ) {
                        $is_include_user_allowed = true;
                    }
                }
            } else {
                $is_include_user_allowed = true;
            }
           
            if( $is_user_include_role_allowed && $is_include_user_allowed )
            {
                return true;
            }
        } else if( $user_filter_type == 'Exclude' ) {

            $is_user_role_excluded = false;
            if( ! empty( $excluded_role ) ) {
                $current_roles = explode( ',', $excluded_role );
                foreach( $roles as $role ) {
                    if( in_array( $role, $current_roles ) ) {
                        $is_user_role_excluded = true;
                    }
                }
            }

            $is_user_excluded = false;
            if( ! empty( $excluded_users ) ) {
                $current_users = explode( ',', $excluded_users );
                if( in_array( $user_id, $current_users )  ) {
                    $is_user_excluded = true;
                }
            }
            
            if( $is_user_excluded == false && $is_user_role_excluded == false ) {
                return true;
            }
        }

        return false;
    }

    /**
     * Show/Hide posts
     *
     * @param $object_id
     * @param $show_courses
     * @param $post_in
     * @param $post_type
     */
    public function ldccShowHide( $object_id, $cat_taxonomy, $tag_taxonomy, $results, $post_type, $is_allowed_to_show = false, $status = '', $course_id = 0, $lesson_id = 0 ) {
        
        $user_id = 0;
        $user_roles = array();
        $ld_cms_schedule_excluded_user_roles = get_option( 'ld_cms_schedule_excluded_user_roles', []);
        if( empty( $ld_cms_schedule_excluded_user_roles ) ) {
            $ld_cms_schedule_excluded_user_roles = [];
        }
        if( is_user_logged_in() ) {
            $user = wp_get_current_user();
            $user_id = $user->ID;
            $user_roles = ( array ) $user->roles;
        }

        $whit_listed_user_roles = array_intersect( $ld_cms_schedule_excluded_user_roles, $user_roles );

        if( count($whit_listed_user_roles) > 0 ){
            return;
        }

        $type = $post_type;
        $current_post_type = get_post_type($object_id);
        $allowed_types = [];
        switch( $current_post_type ) {
            case "sfwd-courses":
                $allowed_types = ['schedule_courses', 'sfwd-courses'];
                break;
            case "sfwd-lessons":
                $allowed_types = ['schedule_lessons', 'sfwd-lessons'];
                break;
            case "sfwd-topic":
                $allowed_types = ['schedule_topics', 'sfwd-topic'];
                break;
            case "sfwd-quiz":
                $allowed_types = ['sfwd-quiz'];
                break;
        }
 
        $posted_by_id = 0;
        // $pre_zone =  date_default_timezone_get();
        // echo $pre_zone;

     //   $t_zone = $this->csld_timezone_string();
     //   date_default_timezone_set( $t_zone );

      //  $date_today = time();
        $date_today  = current_time('timestamp');
     //   $date_today  = $date_today->getTimestamp();

        $categories = $this->get_terms_ids_by_id_n_taxonomy( $object_id, $cat_taxonomy);
        $tags = $this->get_terms_ids_by_id_n_taxonomy( $object_id, $tag_taxonomy );

        $display_dates = array();
        $display_dates_start_only = array();
        $display_dates_end_only = array();
        $is_in_hide_range = false;
        $format = get_option( 'date_format' );
        $time_format = get_option( 'time_format' );
        
        $show_hide_action = get_post_meta( $object_id, '_show_hide_action', true );
        if( empty( $show_hide_action ) ) {
            if( ! empty( $status ) ) {
                $show_hide_action = $status;
            } else {
                $show_hide_action = get_option( 'course_scheduler_ld_addon_setting' );
            }
        }
        $show_hide_action_general = get_option( 'course_scheduler_ld_addon_setting' );
        $is_one = false;
        $is_group_schedule = false;
        
        foreach( $results as $rec ) {
            if( in_array( $rec->object_type, $allowed_types)) {
                $rec_end_date = $rec->end;
                if( $rec->is_end_date == 'no_end_date' ) {
                    $rec_end_date = date( 'Y-m-d H:i:s', strtotime( "+10 Year", strtotime( date('Y-m-d') ) ) );
					// nab** changes
                    $rec_end_date = strtotime('+' . $rec->duration_end_date . $rec->duration_type_end_date, strtotime($rec->start));
                }
                
                //
                if( ! $is_group_schedule ) {
                    switch( $rec->object_type ){
                        case "schedule_courses":
                            $is_group_schedule = true;
                            break;
                        case "schedule_lessons":
                            $is_group_schedule = true;
                            break;
                        case "schedule_topics":
                            $is_group_schedule = true;
                            break;
                    }
                }
                
                if( $rec->object_id == $object_id || $rec->object_id == $course_id || $rec->object_id == $lesson_id || $rec->object_id == '0'  ) {
                    $is_users_n_roles = $this->is_exist_allowed_users_n_roles( $rec->user_filter_type, $rec->excluded_role, $rec->excluded_users );
                    $is_group = $this->is_exist_in_groups( $object_id, $rec->ld_group );
                    $is_cat = $this->is_exist_in_terms( $rec->category, $object_id, $cat_taxonomy, 'category' );
                    $is_tag = $this->is_exist_in_terms( $rec->tag, $object_id, $tag_taxonomy, 'tag' );
                    if( $is_cat && $is_tag && $is_group && $is_users_n_roles ) {
    
                        $subsdate = $this->get_course_subscription_date( $object_id );
                        $start = strtotime( $rec->start );
                        $end = strtotime( $rec_end_date );
                        if( $rec->is_subsdate_as_startdate == 'Yes' && intval( $subsdate ) > 0 ) {
                            $start = $subsdate;
                            $end = strtotime( '+'.$rec->duration.' '.$rec->duration_type, $subsdate );
                        } else if( $rec->is_subsdate_as_startdate == 'Yes' &&  intval( $subsdate ) <= 0 ) {
                            $start = 0;
                            $end = 0;
                        }
                        
                        if( $start > 0 && $end > 0 ) {
                            if( $show_hide_action == 'hide' ) {
                                if( $date_today >= $start && $date_today <= $end ) {
                                    $is_in_hide_range = true;
                                    if( intval( $rec->posted_by ) > 0 ) {
                                        $hide_lesson_message_option = html_entity_decode( get_user_meta( $rec->posted_by, 'cs_ld_addon_'.$show_hide_action.'_'. strtolower( $type ) .'_message', true ) );
                                        if( ! empty( $hide_lesson_message_option ) ) {
                                            $posted_by_id = $rec->posted_by;
                                            echo 'sdfsdfsdf';
                                        }
                                    }
                                }
                              
                                $endonly = date_i18n( $format.' '.$time_format, $end );
                                if( $rec->is_end_date == 'no_end_date' ) {
                                    $endonly = __( 'Undefined Time', 'cs_ld_addon' );
                                }
                                $display_dates[] = '<span class="ldcms-start-date-label">'.__( 'From', 'cs_ld_addon' ).'</span> '.date_i18n( $format.' '.$time_format, $start ).' <span class="ldcms-end-date-label">'.__( 'to', 'cs_ld_addon' ).'</span> '.$endonly;
                                $display_dates_start_only[] = '<span class="ldcms-start-date-label">'.__( 'From', 'cs_ld_addon' ).'</span> '.date_i18n( $format.' '.$time_format, $start );
                                $display_dates_end_only[] = '<span class="ldcms-end-date-label">'.__( 'Available till', 'cs_ld_addon' ).'</span> '.$endonly;
                            } else {
    
                                if( ( $start > $date_today && $date_today >  $end ) || ( $start > $date_today && $end > $date_today ) || ( $start < $date_today && $end < $date_today ) ) {
                                    $is_in_hide_range = true;
                                    if( intval( $rec->posted_by ) > 0 ) {
                                        $hide_lesson_message_option = html_entity_decode( get_user_meta( $rec->posted_by, 'cs_ld_addon_'.$show_hide_action.'_'. strtolower( $type ) .'_message', true ) );
                                        if( ! empty( $hide_lesson_message_option ) ) {
                                            $posted_by_id = $rec->posted_by;
                                            echo 'sdfsdfsdf111111';
                                        }
                                    }
    
                                } elseif( $date_today >= $start && $date_today <= $end  ) {
                                    $is_allowed_to_show = true;
                                    $is_one = true;
                                    if( intval( $rec->posted_by ) > 0 ) {
                                        $hide_lesson_message_option = html_entity_decode( get_user_meta( $rec->posted_by, 'cs_ld_addon_'.$show_hide_action.'_'. strtolower( $type ) .'_message', true ) );
                                        if( ! empty( $hide_lesson_message_option ) ) {
                                            $posted_by_id = $rec->posted_by;
                                        }
                                    }
                                }
                                $endonly = date_i18n( $format.' '.$time_format, $end );
                                if( $rec->is_end_date == 'no_end_date' ) {
                                    $endonly = __( 'Undefined Time', 'cs_ld_addon' );
                                }
                                $display_dates[] = '<span class="ldcms-start-date-label">'.__( 'From', 'cs_ld_addon' ).'</span> '.date_i18n( $format.' '.$time_format, $start ).' <span class="ldcms-end-date-label">'.__( 'to', 'cs_ld_addon' ).'</span> '.$endonly;
                                $display_dates_start_only[] = '<span class="ldcms-start-date-label">'.__( 'From', 'cs_ld_addon' ).'</span> '.date_i18n( $format.' '.$time_format, $start );
                                $display_dates_end_only[] = '<span class="ldcms-end-date-label">'.__( 'Available till', 'cs_ld_addon' ).'</span> '.$endonly;
							}
                        }
                    }
                }  
            }
        }
        

        if( !$is_group_schedule && count( $display_dates ) == 0 ) {
            return;
        }
        
        if( $is_allowed_to_show || $is_one ) {
            $message_option = html_entity_decode( get_user_meta( $posted_by_id, 'cs_ld_addon_'.$show_hide_action.'_'. strtolower( $type ) .'_message', true ) );
            if( ! empty( $message_option ) ) {
                $short_code_message = $message_option;
            } else {
                $short_code_message = html_entity_decode( get_option( 'cs_ld_addon_'.$show_hide_action.'_'. strtolower( $type ) .'_message' ) );
            }

            $output_string = '';
            if( count( $display_dates ) > 0 ) {
	            $display_dates = array_unique($display_dates);
                $output_string = '<ul class="cs_ld_date_list">';
                foreach( $display_dates as $date ) {
                    $output_string .= '<li>' . $date . '</li>';
                }
                $output_string .= '</ul>';
            }
            
            $short_code_message = str_replace('[cs_scheduled_dates]', $output_string, $short_code_message);
            $output_string = '';
            if( count( $display_dates_start_only ) > 0 ) {
	            $display_dates_start_only = array_unique($display_dates_start_only);
                $output_string = '<ul class="cs_ld_date_list">';
                foreach( $display_dates_start_only as $date ) {
                    $output_string .= '<li>' . $date . '</li>';
                }
                $output_string .= '</ul>';
            }
           
            $short_code_message = str_replace('[cs_scheduled_dates_start_only]', $output_string, $short_code_message);
            $output_string = '';
            if( count( $display_dates_end_only ) > 0 ) {
	            $display_dates = array_unique($display_dates_end_only); //Fix #8714
                $output_string = '<ul class="cs_ld_date_list">';
                foreach( $display_dates_end_only as $date ) {
                    $output_string .= '<li>' . $date . '</li>';
                }
                $output_string .= '</ul>';
            }
            
            $short_code_message = str_replace('[cs_scheduled_dates_end_only]', $output_string, $short_code_message);

            $total_output = '';
            if( !empty($short_code_message) ){ 
                $total_output = apply_filters('ld_cms_content_message', html_entity_decode( '<div class="ld-cms-content-message">'.$short_code_message.'</div>' ) );
            }
            return $total_output;
        } else if( ! $is_allowed_to_show && $is_in_hide_range ) {
            $message_option = get_user_meta( $posted_by_id, 'cs_ld_addon_'.$show_hide_action.'_'. strtolower( $type ) .'_message', true );
            if( ! empty( $message_option ) ) {
                $short_code_message = $message_option;
            } else {
                $short_code_message =  get_option( 'cs_ld_addon_'.$show_hide_action.'_'. strtolower( $type ) .'_message' );
            }
            
            $output_string = '';
            if( count( $display_dates ) > 0 ) {
	            $display_dates = array_unique($display_dates); //Fix #8714
                $output_string = '<ul class="cs_ld_date_list">';
                foreach( $display_dates as $date ) {
                    $output_string .= '<li>' . $date . '</li>';
                }
                $output_string .= '</ul>';
            }
            
            $short_code_message = str_replace('[cs_scheduled_dates]', $output_string, $short_code_message);
            $output_string = '';
            if( count( $display_dates_start_only ) > 0 ) {
	            $display_dates_start_only = array_unique($display_dates_start_only); //Fix #8714
                $output_string = '<ul class="cs_ld_date_list">';
                foreach( $display_dates_start_only as $date ) {
                    $output_string .= '<li>' . $date . '</li>';
                }
                $output_string .= '</ul>';
            }
           
            $short_code_message = str_replace('[cs_scheduled_dates_start_only]', $output_string, $short_code_message);
            $output_string = '';
            if( count( $display_dates_end_only ) > 0 ) {
	            $display_dates = array_unique($display_dates_end_only); //Fix #8714
                $output_string = '<ul class="cs_ld_date_list">';
                foreach( $display_dates_end_only as $date ) {
                    $output_string .= '<li>' . $date . '</li>';
                }
                $output_string .= '</ul>';
            }
            
            $short_code_message = str_replace('[cs_scheduled_dates_end_only]', $output_string, $short_code_message);
            
            $GLOBALS[ 'short_code_message' ] =  apply_filters('ld_cms_content_message', html_entity_decode( '<div class="ld-cms-content-message">'.$short_code_message.'</div>' ) );
            add_filter('learndash_content', function() {
                return '<div class="cs_ld_mng_frnt_msg">'.$GLOBALS[ 'short_code_message' ].'</div>';
            });
        } else {
            $csld_hide_all_users = get_post_meta( $object_id, '_csld_hide_all_users', true );
            if( empty( $csld_hide_all_users ) ) {
                $csld_hide_all_users = get_option( 'course_scheduler_ld_addon_hide_all_users' );
            }

            $object_type = get_post_type( $object_id );
            if( strtolower( $csld_hide_all_users ) == 'yes' ) {
                $rec_type = '';
                if( 'sfwd-courses' == $object_type ) {
                    $rec_type = 'Course';
                } elseif( 'sfwd-lessons' == $object_type ) {
                    $rec_type = 'Lesson';
                } elseif( 'sfwd-quiz' == $object_type ) {
                    $rec_type = 'Quiz';
                } elseif( 'sfwd-topic' == $object_type ) {
                    $rec_type = 'Topic';
                }

                $short_code_message = '';
                $message_option = html_entity_decode( get_user_meta( $object_id, 'cs_ld_addon_hide_for_all_'.strtolower( $rec_type ) .'_message', true ) );
                if( ! empty( $message_option ) ) {
                    $short_code_message = $message_option;
                } else {
                    $short_code_message = html_entity_decode( get_option( 'cs_ld_addon_hide_for_all_'.strtolower( $rec_type ) .'_message' ) );
                }
                $GLOBALS[ 'short_code_message' ] =  apply_filters('ld_cms_content_message', html_entity_decode( '<div class="ld-cms-content-message">'.$short_code_message.'</div>' ) );
                add_filter('learndash_content', function() {
                    return '<div class="cs_ld_mng_frnt_msg">'.$GLOBALS[ 'short_code_message' ].'</div>';
                });
            }
        }
    }

    /**
     * Get the WordPress Selected Time Zone
     * @param void
     *
     * @return string / time zone
     */
    function csld_timezone_string() {
        // If site timezone string exists, return it.
        $timezone = get_option( 'timezone_string' );
        if ( $timezone ) {
          return $timezone;
        }

        // Get UTC offset, if it isn't set then return UTC.
        $utc_offset = intval( get_option( 'gmt_offset', 0 ) );
        if ( 0 === $utc_offset ) {
          return 'UTC';
        }

        // Adjust UTC offset from hours to seconds.
        $utc_offset *= 3600;

        // Attempt to guess the timezone string from the UTC offset.
        $timezone = timezone_name_from_abbr( '', $utc_offset );
        if ( $timezone ) {
          return $timezone;
        }

        // Last try, guess timezone string manually.
        foreach ( timezone_abbreviations_list() as $abbr ) {
          foreach ( $abbr as $city ) {
            if ( (bool) date( 'I' ) === (bool) $city['dst'] && $city['timezone_id'] && intval( $city['offset'] ) === $utc_offset ) {
              return $city['timezone_id'];
            }
          }
        }

        // Fallback to UTC.
        return 'UTC';
    }

    /**
     * Enqueue scritps for plugin
     */
    public function get_parent_course_of_object( $object_id = 0 ) {
        $post_type = get_post_type( $object_id );
        if( $post_type == 'sfwd-courses' ) {
            return $object_id;
        } else {
            if( $post_type=='sfwd-lessons' ) {
                $course_id = learndash_get_course_id( $object_id );

                return $course_id;
            } else if( $post_type=='sfwd-topic' || $post_type=='sfwd-quiz' ) {
                $lesson_id = learndash_get_lesson_id( $object_id );
                if( intval( $lesson_id ) > 0 ) {
                    $course_id = learndash_get_course_id( $object_id );
                    return $course_id;
                } else {
                    $course_id = learndash_get_course_id( $object_id );
                    return $course_id;
                }
            }
        }
    }

    /**
     * Adds Reporting Chart menu page
     */
    public function ldccAdminMenu() {

        /**
         * Add LearnDash Course Planner Pro System Page
         */
        add_menu_page(
            __( 'LearnDash Course Planner Pro', 'cs_ld_addon' ),
            __( 'LearnDash Course Planner Pro', 'cs_ld_addon' ),
            'manage_options',
            'calendar_course',
            array( $this, ( 'csView' ) ),
            'dashicons-calendar-alt'
        );

        /**
         * Add Setting Page
         */
        add_submenu_page(
            'calendar_course',
            __( 'Calendar', 'cs_ld_addon' ),
            __( 'Calendar', 'cs_ld_addon' ),
            'manage_options',
            'calendar_course',
            array( $this, ( 'csView' ) )
        );

        /**
         * Add Setting Page
         */
        add_submenu_page(
            'calendar_course',
            __( 'Import Events', 'cs_ld_addon' ),
            __( 'Import Events', 'cs_ld_addon' ),
            'manage_options',
            'calendar_import_events',
            array( $this, ( 'csImportEvents' ) )
        );

        /**
         * Add Setting Page
         */
        add_submenu_page(
            'calendar_course',
            __( 'Settings', 'cs_ld_addon' ),
            __( 'Settings', 'cs_ld_addon' ),
            'manage_options',
            'calendar_course_settings',
            array( $this, ( 'csViewSetting' ) )
        );
    }



    /**
     * Loads calendar view
     */
    public function csView() {
        $user_id = get_current_user_id();
        if( file_exists( dirname(__FILE__) . '/views/calendar_view.php' ) ) {
            require_once( dirname(__FILE__) . '/views/calendar_view.php' );
        }
    }

    /**
     * Loads settings view
     */
    public function csImportEvents() {
        ?>
        <div class="ARwebcrafts_addon">
<div class="wn_wrap ARwebcrafts_addon_plnr-crse import_csv">
    <div id="ld_qie_import_messages"></div>
    <div id="ld_qie_content_wrap" class="ld-crse-plnr-wrp">
        <div id="ld_qie_loader_spinner" style="display: none;">
            <div class="ld_qie_spinner"></div>
        </div>
        <form id="ld_qie_upload_file_form" action="" method="post" enctype="multipart/form-data">
            <input type="hidden" name="action" id="ld_qie_action" value="ld_cms_events_list">
            <input type="hidden" name="ld_qie_ajax_nonce" value="<?php echo wp_create_nonce( 'ld-qie-ajax-nonce' ); ?>">
            <div id="ld_qie_import_step1">
                <div>
                 <h2><?php _e( "Please select CSV to import", "ldcms" ); ?></h2> 
                </div>
                <div class="import-excel-page">
                    <div class="content">
                        <div class="box">
                            <input type="file" id="ldcms_import_file" name="ldcms_import_file"
                                class="inputfile inputfile-6" accept=".csv" />
                            <label for="ldcms_import_file"> <strong>
                                    <svg xmlns='http://www.w3.org/2000/svg' width='20' height='17' viewBox='0 0 20 17'>
                                        <path
                                            d='M10 0l-5.2 4.9h3.3v5.1h3.8v-5.1h3.3l-5.2-4.9zm9.3 11.5l-3.2-2.1h-2l3.4 2.6h-3.5c-.1 0-.2.1-.2.1l-.8 2.3h-6l-.8-2.2c-.1-.1-.1-.2-.2-.2h-3.6l3.4-2.6h-2l-3.2 2.1c-.4.3-.7 1-.6 1.5l.6 3.1c.1.5.7.9 1.2.9h16.3c.6 0 1.1-.4 1.3-.9l.6-3.1c.1-.5-.2-1.2-.7-1.5z' />
                                    </svg>
                                    <?php _e('Select a file &hellip;', 'cs_ld_addon'); ?></strong><span></span></label>
                            <div class="ldcms-import-log"></div>
                        </div>
                        <div class="submit" style="text-align: center;">
                    <button class="ARwebcrafts_crse-plnr_button" type="submit"
                        name="import-btn"><?php _e('Import'); ?> <span
                            class="dashicons dashicons-arrow-right-alt2 no-left-margin"></span></button>
                </div>
                        
                    </div>
                </div> 
                
            </div>
        </form>
    </div>
</div>
</div>
<?php
    }
    
    /**
     * Loads settings view
     */
    public function csViewSetting() {

        $settings_sections = array(
            'general' => array(
                'title' => __( 'General Settings', 'cs_ld_addon' ),
                'icon' => 'fa-cog',
            ),
            'courses' => array(
                'title' => __( 'Course Messages', 'cs_ld_addon' ),
                'icon' => 'fa-hashtag',
            ),
            'lessons' => array(
                'title' => __( 'Lesson Messages', 'cs_ld_addon' ),
                'icon' => 'fa-arrow-up',
            ),
            'topics' => array(
                'title' => __( 'Topic Messages', 'cs_ld_addon' ),
                'icon' => 'fa fa-shield-alt',
            ),
            'quizzes' => array(
                'title' => __( 'Quiz Messages', 'cs_ld_addon' ),
                'icon' => 'fa-info',
            ),
            'shortcode' => array(
                'title' => __( 'Shortcode', 'cs_ld_addon' ),
                'icon' => 'fa-info',
            ),
        );

        if(get_option( 'ld_cms_send_course_availability_email', 'no') == 'yes') {
            $settings_sections['course_availability_email'] = array(
                'title' => __( 'Course Availability Email', 'cs_ld_addon' ),
                'icon'  => 'fa-envelope',
            );
        }

        $settings_sections['license'] = array(
            'title' => __( 'License', 'cs_ld_addon' ),
            'icon' => 'fa-check',
        );

        $settings_sections = apply_filters( 'cs_ld_settings_sections', $settings_sections );
        ?>
<div class="wrap ARwebcrafts_addon">
    <div id="icon-options-general" class="icon32"></div>
    <h1 class="course-plnr-addon_main_heading"><?php _e( 'LearnDash Course Planner Pro Settings ', 'cs_ld_addon' ); ?></h1>

    <div class="nav-tab-wrapper ARwebcrafts_addon_top_nav ">
        <?php
                foreach( $settings_sections as $key => $section ) {
                    ?>
        <a href="?page=calendar_course_settings&tab=<?php echo $key; ?>"
            class="nav-tab <?php echo $this->page_tab == $key ? 'nav-tab-active' : ''; ?>">
            <i class="fa <?php echo $section['icon']; ?>" aria-hidden="true"></i>
            <?php _e( $section['title'], 'cs_ld_addon' ); ?>
        </a>
        <?php
                }
                ?>
    </div>

    <?php
            foreach( $settings_sections as $key => $section ) {
                if( $this->page_tab == $key ) {
                    $key = str_replace( '_', '-', $key );
                    include( 'views/tabs/' . $key . '.php' );
                }
            }
            ?>
</div>
<?php
    }

    /**
     * Add Help Tab
     */
    public static function add_help_tab() {
        $screen = get_current_screen();
        if( $screen->base !== 'toplevel_page_calendar_course' )
            return;

        $screen->add_help_tab( array(
            'id'        => 'cs-ld-course-scheduler-details',
            'title'     => __( 'LearnDash Course Planner Pro', 'cs_ld_addon' ),
            'content'   =>
                '<p>' . __( 'Drag published '. strtolower( LearnDash_Custom_Label::get_label( 'courses' ) ) .' on left to the calendar to schedule them on specific dates or show them on all dates except the ones added on the calendar, this is based on the settings saved for the addon.', 'cs_ld_addon' ) . '</p>' .
                '<p>' . __( 'Each '. strtolower( LearnDash_Custom_Label::get_label( 'courses' ) ) . ' can be dragged and dropped on the calendar multiple times and multiple ' . strtolower( LearnDash_Custom_Label::get_label( 'courses' ) ) . ' can be scheduled for the same date.', 'cs_ld_addon' ) . '</p>' .
                 '<p>' . __( 'Click the cross icon to remove the '. strtolower( LearnDash_Custom_Label::get_label( 'courses' ) ) .' from calendar, you also have the option to move the dropped '. strtolower( LearnDash_Custom_Label::get_label( 'courses' ) ) .' to other dates on the calendar by simply drag and drop from the previous date to the new date' ) . '</p>'.
                '<p>' . __( 'Already dropped '. strtolower( LearnDash_Custom_Label::get_label( 'courses' ) ) .' would always show up on the calendar', 'cs_ld_addon' ) . '</p>'
        ) );
    }

    /**
     * Add footer branding
     *
     * @param $footer_text
     * @return mixed
     */
    public static function remove_my_footer_admin ( $footer_text ) {
        if( isset( $_GET[ 'page' ] ) && ( $_GET[ 'page' ] == 'calendar_course_settings' || $_GET[ 'page' ] == 'calendar_course' ) ){
            _e('Fueled by <a href="http://www.wordpress.org" target="_blank">WordPress</a> | developed and designed by <a href="https://www.arwebcrafts.com" target="_blank">ARwebcrafts</a></p>', "cs_ld_addon");
        } else {
            return $footer_text;
        }
    }

    /**
     * Show info notification on calendar page
     */
    public static function add_help_notification () {
        $screen = get_current_screen();

        if( isset( $_GET['csld_dismiss_notice'] ) ) {
            update_user_meta( get_current_user_id(), 'csld_review_dismissed', 1 );
        }

        if( isset($screen->id) && $screen->id === 'toplevel_page_calendar_course' ) {
            ?>
<div class="notice notice-info" style="margin-top:50px;">
    <p><?php _e( 'Drag and drop '. strtolower( LearnDash_Custom_Label::get_label( 'courses' ) ) .' from the left on the calendar to assign it <strong>on specific dates</strong> OR <strong>except the specific dates</strong> depending on your <a href="'.admin_url().'admin.php?page=calendar_course_settings">settings</a> here', 'cs_ld_addon' ); ?>
    </p>
</div>
<div class="notice notice-error invalid-date" style="display:none;margin-top:20px;">
    <p><?php _e( 'You cannot schedule a '. strtolower( LearnDash_Custom_Label::get_label( 'course' ) ) .' for a past date.', 'cs_ld_addon' ); ?>
    </p>
</div>
<?php
        } else {
            $user_data = get_userdata(get_current_user_id());
            $csld_review_dismissed = get_user_meta(get_current_user_id(), 'csld_review_dismissed', true);
            $dismiss_url = add_query_arg( 'csld_dismiss_notice', 1 );

            if ( ! $csld_review_dismissed ) {
            ?>
<div class="notice notice-info">
    <?php _e('<p>Hi <strong>' . $user_data->user_nicename . '</strong>, thankyou for using LearnDash Course Planner Pro If you find our plugin useful kindly take some time to leave a review and a rating for us <a href="https://www.arwebcrafts.com/wn-products/learndash-course-scheduler/" target="_blank" ><strong>here</strong></a> </p><p><a href="'.esc_attr($dismiss_url).'">Dismiss Notice</a></p>', 'cs_ld_addon'); ?>
</div>
<?php
            }
        }
    }

    /**
     * Save Plugin's Settings
     */
    public static function save_csld_settings () {

        $settings_saved = false;

        /**
         * General Settings
         */
        if( ( isset( $_POST['save_csld_general_settings'] ) && current_user_can( 'manage_options' ) && ! empty( $_POST ) && check_admin_referer( 'csld_general_settings', 'csld_general_settings_field' ) ) ) {
	        $settings_saved = true;
            
            if( isset( $_POST['show_courses'] ) && ! empty( $_POST['show_courses'] ) ) {
                update_option( 'course_scheduler_ld_addon_setting', $_POST['show_courses'] );
            }

            if( isset( $_POST['ld_cms_timezone_string'] ) && ! empty( $_POST['ld_cms_timezone_string'] ) ) {

                update_option( 'course_scheduler_ld_time_zone', $_POST['ld_cms_timezone_string'] );
            }

            if( isset($_POST['csld_hide_all_users']) ) {
                update_option( 'course_scheduler_ld_addon_hide_all_users', sanitize_text_field( $_POST['csld_hide_all_users'] ) );
            } else {
	            update_option( 'course_scheduler_ld_addon_hide_all_users', '' );
            }


            //Send course availability email option
            $ld_cms_send_availability_email = 'no';
            if( isset($_POST['ld_cms_send_availability_email']) && !empty($_POST['ld_cms_send_availability_email']) ) {
                $ld_cms_send_availability_email='yes';
            }
            $ld_cms_group_selected_roles_manage_their_courses = 'no';
            if( isset($_POST['ld_cms_group_selected_roles_manage_their_courses']) && !empty($_POST['ld_cms_group_selected_roles_manage_their_courses']) ) {
                $ld_cms_group_selected_roles_manage_their_courses = 'yes';
            }

            update_option( 'ld_cms_group_selected_roles_manage_their_courses', $ld_cms_group_selected_roles_manage_their_courses);
            update_option( 'ld_cms_send_course_availability_email', $ld_cms_send_availability_email);
			if( isset($_POST['ld_cms_group_roles_schedule'])) {
				update_option( 'ld_cms_group_roles_schedule', $_POST['ld_cms_group_roles_schedule']);
			}else{
			    update_option( 'ld_cms_group_roles_schedule', '');
			}
           

            //Hide courses if unavailable option
            $ld_cms_hide_unavailable_courses = 'no';
            if( isset($_POST['ld_cms_hide_unavailable_courses']) && !empty($_POST['ld_cms_hide_unavailable_courses']) ) {
                $ld_cms_hide_unavailable_courses='yes';
            }
            update_option( 'ld_cms_hide_unavailable_courses', $ld_cms_hide_unavailable_courses);
        
            if( isset($_POST['ld_cms_schedule_excluded_user_roles'])) {
				update_option( 'ld_cms_schedule_excluded_user_roles', $_POST['ld_cms_schedule_excluded_user_roles']);
			}else{
			 update_option( 'ld_cms_schedule_excluded_user_roles', '');
			}

        }

        /**
         * Course Settings
         */

        if( ( isset( $_POST['save_csld_course_settings'] ) && ! empty( $_POST ) && check_admin_referer( 'csld_course_settings', 'csld_course_settings_field' ) ) ) {
	        $settings_saved = true;
            if( is_admin() ) {
                if( isset( $_POST['show_courses_message'] ) && ! empty( $_POST['show_courses_message'] ) ) {
                    update_option( 'cs_ld_addon_show_course_message', wp_kses_post( stripslashes_deep( $_POST['show_courses_message'] ) ) );
                }

                if( isset( $_POST['hide_courses_message'] ) && ! empty( $_POST['hide_courses_message'] ) )
                {
                    update_option( 'cs_ld_addon_hide_course_message', wp_kses_post( stripslashes_deep( $_POST['hide_courses_message'] ) ) );
                }

                if( isset( $_POST['hide_for_all_course_message'] ) && ! empty( $_POST['hide_for_all_course_message'] ) ) {
                    update_option( 'cs_ld_addon_hide_for_all_course_message', wp_kses_post( stripslashes_deep( $_POST['hide_for_all_course_message'] ) ) );
                }

                if( isset( $_POST['parent_hide_courses_message'] ) && ! empty( $_POST['parent_hide_courses_message'] ) ) {
                    update_option( 'cs_ld_addon_parent_hide_courses_message', wp_kses_post( stripslashes_deep( $_POST['parent_hide_courses_message'] ) ) );
                }
            } else {
                $user_id = get_current_user_id();
                if( isset( $_POST['show_courses_message'] ) && ! empty( $_POST['show_courses_message'] ) ) {
                    update_user_meta( $user_id, 'cs_ld_addon_show_course_message', wp_kses_post( stripslashes_deep( $_POST['show_courses_message'] ) ) );
                }

                if( isset( $_POST['hide_for_all_course_message'] ) && ! empty( $_POST['hide_for_all_course_message'] ) ) {
                    update_user_meta( $user_id, 'cs_ld_addon_hide_for_all_course_message', wp_kses_post( stripslashes_deep( $_POST['hide_for_all_course_message'] ) ) );
                }

                if( isset( $_POST['hide_courses_message'] ) && ! empty( $_POST['hide_courses_message'] ) ) {
                    update_user_meta( $user_id, 'cs_ld_addon_hide_course_message', wp_kses_post( stripslashes_deep( $_POST['hide_courses_message'] ) ) );
                }

                if( isset( $_POST['parent_hide_courses_message'] ) && ! empty( $_POST['parent_hide_courses_message'] ) ) {
                    update_user_meta( $user_id, 'cs_ld_addon_parent_hide_courses_message', wp_kses_post( stripslashes_deep( $_POST['parent_hide_courses_message'] ) ) );
                }
            }

        }

        /**
         * Lesson Settings
         */
        if( ( isset( $_POST['save_csld_lesson_settings'] ) && ! empty( $_POST ) && check_admin_referer( 'csld_lesson_settings', 'csld_lesson_settings_field' ) ) ) {
	        $settings_saved = true;
            if( is_admin() ) {
                if( isset( $_POST['parent_hide_lesson_message'] ) && ! empty( $_POST['parent_hide_lesson_message'] ) ) {
                    update_option( 'cs_ld_addon_parent_hide_lesson_message', wp_kses_post( stripslashes_deep( $_POST['parent_hide_lesson_message'] ) ) );
                }

                if( isset( $_POST['show_lesson_message'] ) && ! empty( $_POST['show_lesson_message'] ) ) {
                    update_option( 'cs_ld_addon_show_lesson_message', wp_kses_post( stripslashes_deep( $_POST['show_lesson_message'] ) ) );
                }

                if( isset( $_POST['hide_for_all_lesson_message'] ) && ! empty( $_POST['hide_for_all_lesson_message'] ) ) {
                    update_option( 'cs_ld_addon_hide_for_all_lesson_message', wp_kses_post( stripslashes_deep( $_POST['hide_for_all_lesson_message'] ) ) );
                }

                if( isset( $_POST['hide_lesson_message'] ) && ! empty( $_POST['hide_lesson_message'] ) ) {
                    update_option( 'cs_ld_addon_hide_lesson_message', wp_kses_post( stripslashes_deep( $_POST['hide_lesson_message'] ) ) );
                }
            } else {
                $user_id = get_current_user_id();
                if( isset( $_POST['parent_hide_lesson_message'] ) && ! empty( $_POST['parent_hide_lesson_message'] ) ) {
                    update_user_meta( $user_id, 'cs_ld_addon_parent_hide_lesson_message', wp_kses_post( stripslashes_deep( $_POST['parent_hide_lesson_message'] ) ) );
                }

                if( isset( $_POST['hide_for_all_lesson_message'] ) && ! empty( $_POST['hide_for_all_lesson_message'] ) ) {
                    update_user_meta( $user_id, 'cs_ld_addon_hide_for_all_lesson_message', wp_kses_post( stripslashes_deep( $_POST['hide_for_all_lesson_message'] ) ) );
                }

                if( isset( $_POST['show_lesson_message'] ) && ! empty( $_POST['show_lesson_message'] ) ) {
                    update_user_meta( $user_id, 'cs_ld_addon_show_lesson_message', wp_kses_post( stripslashes_deep( $_POST['show_lesson_message'] ) ) );
                }

                if( isset( $_POST['hide_lesson_message'] ) && ! empty( $_POST['hide_lesson_message'] ) ) {
                    update_user_meta( $user_id, 'cs_ld_addon_hide_lesson_message', wp_kses_post( stripslashes_deep( $_POST['hide_lesson_message'] ) ) );
                }
            }
        }

        /**
         * Topic Settings
         */
        if( ( isset( $_POST['save_csld_topic_settings'] ) && ! empty( $_POST ) && check_admin_referer( 'csld_topic_settings', 'csld_topic_settings_field' ) ) ) {
	        $settings_saved = true;
            if( is_admin() ) {
                if( isset( $_POST[ 'show_topic_message' ] ) && ! empty( $_POST['show_topic_message'] ) ) {
                    update_option( 'cs_ld_addon_show_topic_message', wp_kses_post( stripslashes_deep( $_POST['show_topic_message'] ) ) );
                }

                if( isset( $_POST['hide_for_all_topic_message'] ) && ! empty( $_POST['hide_for_all_topic_message'] ) ) {
                    update_option( 'cs_ld_addon_hide_for_all_topic_message', wp_kses_post( stripslashes_deep( $_POST['hide_for_all_topic_message'] ) ) );
                }

                if( isset( $_POST['hide_topic_message'] ) && ! empty( $_POST['hide_topic_message'] ) ) {
                    update_option( 'cs_ld_addon_hide_topic_message', wp_kses_post( stripslashes_deep( $_POST['hide_topic_message'] ) ) );
                }
            } else {

                $user_id = get_current_user_id();
                if( isset( $_POST['show_topic_message'] ) && ! empty( $_POST['show_topic_message'] ) ) {
                    update_user_meta( $user_id, 'cs_ld_addon_show_topic_message', wp_kses_post( stripslashes_deep( $_POST['show_topic_message'] ) ) );
                }

                if( isset( $_POST['hide_for_all_topic_message'] ) && ! empty( $_POST['hide_for_all_topic_message'] ) ) {
                    update_user_meta( $user_id, 'cs_ld_addon_hide_for_all_topic_message', wp_kses_post( stripslashes_deep( $_POST['hide_for_all_topic_message'] ) ) );
                }

                if( isset( $_POST['hide_topic_message'] ) && ! empty( $_POST['hide_topic_message'] ) ) {
                    update_user_meta( $user_id, 'cs_ld_addon_hide_topic_message', wp_kses_post( stripslashes_deep( $_POST['hide_topic_message'] ) ) );
                }
            }
        }

        /**
         * Quiz Settings
         */
        if( ( isset( $_POST['save_csld_quiz_settings'] ) && ! empty( $_POST ) && check_admin_referer( 'csld_quiz_settings', 'csld_quiz_settings_field' ) ) ) {
	        $settings_saved = true;
            if( is_admin() ) {
                if( isset( $_POST['show_quiz_message'] ) && ! empty( $_POST['show_quiz_message'] ) ) {
                    update_option( 'cs_ld_addon_show_quiz_message', wp_kses_post( stripslashes_deep( $_POST['show_quiz_message'] ) ) );
                }

                if( isset( $_POST['hide_for_all_quiz_message'] ) && ! empty( $_POST['hide_for_all_quiz_message'] ) ) {
                    update_option( 'cs_ld_addon_hide_for_all_quiz_message', wp_kses_post( stripslashes_deep( $_POST['hide_for_all_quiz_message'] ) ) );
                }

                if( isset( $_POST['hide_quiz_message'] ) && ! empty( $_POST['hide_quiz_message'] ) ) {
                    update_option( 'cs_ld_addon_hide_quiz_message', wp_kses_post( stripslashes_deep( $_POST['hide_quiz_message'] ) ) );
                }
            } else {
                $user_id = get_current_user_id();
                if( isset( $_POST['show_quiz_message'] ) && ! empty( $_POST['show_quiz_message'] ) ) {
                    update_user_meta( $user_id, 'cs_ld_addon_show_quiz_message', wp_kses_post( stripslashes_deep( $_POST['show_quiz_message'] ) ) );
                }

                if( isset( $_POST['hide_for_all_quiz_message'] ) && ! empty( $_POST['hide_for_all_quiz_message'] ) ) {
                    update_user_meta( $user_id, 'cs_ld_addon_hide_for_all_quiz_message', wp_kses_post( stripslashes_deep( $_POST['hide_for_all_quiz_message'] ) ) );
                }

                if( isset( $_POST['hide_quiz_message'] ) && ! empty( $_POST['hide_quiz_message'] ) ) {
                    update_user_meta( $user_id, 'cs_ld_addon_hide_quiz_message', wp_kses_post( stripslashes_deep( $_POST['hide_quiz_message'] ) ) );
                }
            }
        }

	    if($settings_saved) {
		    add_action( 'admin_notices', [ __CLASS__, 'display_settings_saved_notice' ], 100 );
	    }
    }

    public static function display_settings_saved_notice() {
	    $class   = "notice notice-success";
	    $message = __( 'Settings Updated.', 'cs_ld_addon' );
	    printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( $message ) );
    }

    /**
     * Save setting course availability email settings
     */
    public function save_course_availability_email_tab() {

        $url = admin_url('admin.php');
        $url = add_query_arg('page', 'calendar_course_settings', $url);
        $url = add_query_arg('tab', 'course_availability_email', $url);

        if( check_admin_referer('save_ld_cms_settings_nonce') ) {

            $settings['subject'] = sanitize_textarea_field(stripslashes_deep($_POST['ld_cms_availability_email_subject']));
            $settings['message'] = wp_kses_post(stripslashes_deep($_POST['ld_cms_availability_email_message']));
            $settings['interval'] = sanitize_text_field($_POST['ld_cms_availability_email_interval']);
            $settings['interval_unit'] = sanitize_text_field($_POST['ld_cms_availability_email_interval_unit']);

            update_option('ld_cms_availability_email_settings', $settings);

            $url = add_query_arg('ld_cms_setting_saved', 1, $url);
        }

        wp_redirect($url);
        exit;
    }

    public function settings_saved_notice() {
        $ld_cms_setting_saved = filter_input(INPUT_GET,'ld_cms_setting_saved');
        if(!empty($ld_cms_setting_saved)) {
            $class   = "notice notice-success";
            $message = __( 'Settings Updated.', 'cs_ld_addon' );
            printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( $message ) );
        }
    }

    /**
     * Returns the parent hidden for all users meta settings
     *
     * @param $object_id
     *
     * @return mixed
     */
    public function check_parent_hidden_for_all_user_meta_setting( $object_id, $lesson = 0, $parent_course_id = 0 ) {

        global $wpdb;
        
        $post_type = get_post_type( $object_id );
        $roles = array();
        $user_id = '';
        $rec_id = 0;
        if( is_user_logged_in() ) {
            $user = wp_get_current_user();
            $user_id = $user->ID;
            $roles = ( array ) $user->roles;
        }

        if ( isset( $post_type ) && ( 'sfwd-courses' == $post_type || 'sfwd-lessons' == $post_type || 'sfwd-topic' == $post_type || 'sfwd-quiz' == $post_type ) ) {

            $current_course_id = learndash_get_course_id( $object_id );
            if( empty( $current_course_id ) )
                $current_course_id = 0;
            if( intval( $parent_course_id ) > 0 ) {
                $current_course_id = $parent_course_id;
            }

            $user_groups = self::cs_ld_get_user_grups( $user_id );
            if( 'sfwd-courses' == $post_type ) {
                $cat_taxonomy = 'ld_course_category';
                $tag_taxonomy = 'ld_course_tag';
            } elseif( 'sfwd-lessons' == $post_type ) {
                $cat_taxonomy = 'ld_lesson_category';
                $tag_taxonomy = 'ld_lesson_tag';
            } elseif( 'sfwd-quiz' == $post_type ) {
                $cat_taxonomy = 'category';
                $tag_taxonomy = 'post_tag';
            } elseif( 'sfwd-topic' == $post_type ) {
                $cat_taxonomy = 'ld_topic_category';
                $tag_taxonomy = 'ld_topic_tag';
            }

            $cat_string = '';
            if( ! empty( $cat_taxonomy ) ) {
                $cats = self::get_terms_ids_by_id_n_taxonomy( $object_id, $cat_taxonomy );
                if( count( $cats ) > 0 ) {
                    $cat_string = implode(',', $cats);
                }
            }
            $tag_string = '';
            if( ! empty( $tag_taxonomy ) ) {
                $tags = self::get_terms_ids_by_id_n_taxonomy( $object_id, $tag_taxonomy );
                if( count( $tags ) > 0 ) {
                    $tag_string = implode(',', $tags);
                }
            }
            $where = " object_id='0'";
            if( 'sfwd-courses' == $post_type ) {
                $where = "( object_id='".$object_id."' and object_parent_lesson='0' and object_parent_course='0' ) or object_id='0'";
            } elseif( 'sfwd-lessons' == $post_type ) {
                $where = "( object_id='".$object_id."' and object_parent_lesson='0' and object_parent_course='".$current_course_id."' ) or object_id='0'";
            }

            if( ! empty( $cat_string ) ) {
                $where .= " or category in (".$cat_string.")";
            }
            if( ! empty( $tag_string ) ) {
                $where .= " or tag in (".$tag_string.")";
            }

            $query = "SELECT * FROM {$wpdb->prefix}csld_events WHERE ( $where )";
            if( count( $user_groups ) > 0 ) {
                $query .= " and ( ld_group in ( ".implode(', ', $user_groups )." )  or ld_group = '' or ld_group = '0')";
            } else {
                $query .= " and ( ld_group = '' or ld_group = '0' )";
            }

            $date_today = current_time('timestamp');
            $today = current_time('Y-m-d H:i:s');
            $query .= " and '$today' between start and end";
            $results = $wpdb->get_results($query);

            $hide_all_users = get_post_meta( $object_id, '_csld_hide_all_users', true );
            if( empty( $hide_all_users ) ) {
                if( $post_type == 'sfwd-lessons' ) {
                    if( intval( $parent_course_id ) > 0 ) {
                        $course_id = $parent_course_id;
                    } else {
                        $course_id = learndash_get_course_id( $object_id );
                    }

                    if( intval( $course_id ) > 0 ) {
                        $hide_all_users = get_post_meta( $course_id, '_csld_hide_all_users', true );
                        if( empty( $hide_all_users ) ) {
                            $hide_all_users = get_option( 'course_scheduler_ld_addon_hide_all_users' );
                        }
                    } else {
                        $hide_all_users = get_option( 'course_scheduler_ld_addon_hide_all_users' );
                    }
                } else {
                    $hide_all_users = get_option( 'course_scheduler_ld_addon_hide_all_users' );
                }
            }

            $categories = $this->get_terms_ids_by_id_n_taxonomy( $object_id, $cat_taxonomy);
            $tags = $this->get_terms_ids_by_id_n_taxonomy( $object_id, $tag_taxonomy );
            $is_in_hide_range = false;
            $format = get_option( 'date_format' );

            foreach( $results as $rec ) {
                if( $rec->object_id == $object_id || $rec->object_id == '0' ) {

                    $is_users_n_roles = $this->is_exist_allowed_users_n_roles( $rec->user_filter_type, $rec->excluded_role, $rec->excluded_users );
                    $is_group   = $this->is_exist_in_groups( $object_id, $rec->ld_group );
                    $is_cat     = $this->is_exist_in_terms( $rec->category, $object_id, $cat_taxonomy, 'category' );
                    $is_tag     = $this->is_exist_in_terms( $rec->tag, $object_id, $tag_taxonomy, 'tag' );

                    if( $is_cat && $is_tag && $is_group && $is_users_n_roles ) {

                        $subsdate = $this->get_course_subscription_date( $object_id );
                        $start = strtotime( $rec->start );
                        $end = strtotime( $rec->end );
                        if( $rec->is_subsdate_as_startdate == 'Yes' && intval( $subsdate ) > 0 ) {
                            $start = $subsdate;
                            $end = strtotime( '+'.$rec->duration.' '.$rec->duration_type, $subsdate );
                        } else if(  $rec->is_subsdate_as_startdate == 'Yes' && intval( $subsdate ) <= 0 ) {
                            $start = 0;
                            $end = 0;
                        }

                        if( $start > 0 && $end > 0 ) {
                            if( $start <= $date_today && $date_today <=  $end ) {
                                $is_in_hide_range = false;
                                $rec_id = $rec->id;
                                $hide_all_users = 'no';
                            } else if( $hide_all_users == 'yes' ) {
                                $is_in_hide_range = true;
                                $rec_id = $rec->id;
                            }
                        } else if( $hide_all_users == 'yes' ) {
                            $is_in_hide_range = true;
                            $rec_id = $rec->id;
                        }
                    }
                }
            }

            if( $is_in_hide_range )
                return array( 'rec_id'=>$rec_id, 'hidden'=>$hide_all_users, 'object_id'=>$object_id, 'object_type'=>$post_type, 'tvp'=>'condition' );
            else {
                if( $post_type=='sfwd-courses' ) {
                    return array( 'rec_id'=>$rec_id, 'hidden' => $hide_all_users, 'object_id' => $object_id, 'object_type'=>$post_type, 'tvp'=>'courses' );
                } else {
                    if( $post_type=='sfwd-lessons' ) {

                        if( intval( $parent_course_id ) > 0 ) {
                            $course_id = $parent_course_id;
                        } else {
                            $course_id = learndash_get_course_id( $object_id );
                        }

                        $hide_all_users = get_post_meta( $object_id, '_csld_hide_all_users', true );
                        if( $hide_all_users == 'yes' ) {
                            return array( 'rec_id' => $rec_id, 'hidden'=>$hide_all_users, 'object_id'=>$object_id, 'object_type'=>$post_type, 'tvp'=>'lesson' );
                        } else {
                            return $ret = self::check_parent_hidden_for_all_user_meta_setting( $course_id, 0, $parent_course_id );
                        }
                    }
                }
            }
        }

        return array( 'rec_id'=>$rec_id, 'hidden'=>'', 'object_id'=>$object_id, 'object_type'=>$post_type, 'tvp'=>'no_post_type' );
    }

    /**
     * Returns the parent data
     *
     * @param $object_id
     *
     * @return mixed
     */
    public function check_show_hide_status( $object_id, $lesson = 0, $parent_course_id = 0 ) {

        global $wpdb;

        $post_type = get_post_type( $object_id );
        $roles = array();
        $user_id = '';
        $rec_id = 0;
        if( is_user_logged_in() ) {
            $user = wp_get_current_user();
            $user_id = $user->ID;
            $roles = ( array ) $user->roles;
        }

        $current_post_type = get_post_type($object_id);
        $allowed_types = '';
        switch( $current_post_type ){
            case "sfwd-courses":
                $allowed_types = "'schedule_courses', 'sfwd-courses'";
                break;
                case "sfwd-lessons":
                $allowed_types = "'schedule_lessons', 'sfwd-lessons'";
                break;
            case "sfwd-topic":
                $allowed_types = "'schedule_topics', 'sfwd-topic'";
                break;
            case "sfwd-quiz":
                $allowed_types = "'sfwd-quiz'";
                break;
        }

        if ( isset( $post_type ) && ( 'sfwd-courses' == $post_type || 'sfwd-lessons' == $post_type || 'sfwd-topic' == $post_type || 'sfwd-quiz' == $post_type ) ) {

            $current_course_id = learndash_get_course_id( $object_id );
            if( empty( $current_course_id ) )
                $current_course_id = 0;
            if( intval( $parent_course_id ) > 0 ) {
                $current_course_id = $parent_course_id;
            }

            $user_groups = self::cs_ld_get_user_grups( $user_id );
            if( 'sfwd-courses' == $post_type ) {
                $cat_taxonomy = 'ld_course_category';
                $tag_taxonomy = 'ld_course_tag';
            } elseif( 'sfwd-lessons' == $post_type ) {
                $cat_taxonomy = 'ld_lesson_category';
                $tag_taxonomy = 'ld_lesson_tag';
            } elseif( 'sfwd-quiz' == $post_type ) {
                $cat_taxonomy = 'category';
                $tag_taxonomy = 'post_tag';
            } elseif( 'sfwd-topic' == $post_type ) {
                $cat_taxonomy = 'ld_topic_category';
                $tag_taxonomy = 'ld_topic_tag';
            }

            $cat_string = '';
            if( ! empty( $cat_taxonomy ) ) {
                $cats = self::get_terms_ids_by_id_n_taxonomy( $object_id, $cat_taxonomy );
                if( count( $cats ) > 0 ) {
                    $cat_string = implode(',', $cats);
                }
            }
            $tag_string = '';
            if( ! empty( $tag_taxonomy ) ) {
                $tags = self::get_terms_ids_by_id_n_taxonomy( $object_id, $tag_taxonomy );
                if( count( $tags ) > 0 ) {
                    $tag_string = implode(',', $tags);
                }
            }
            $where = " object_id='0'";
            if( 'sfwd-courses' == $post_type ) {
                $where = "( object_id='".$object_id."' and object_parent_lesson='0' and object_parent_course='0' ) or object_id='0'";
            } elseif( 'sfwd-lessons' == $post_type ) {
                // $where = "( object_id='".$object_id."' and object_parent_lesson='0' and object_parent_course='".$current_course_id."' ) or object_id='0'";

                $where = " ( object_id='".$object_id."' and object_parent_lesson='0' and object_parent_course='0' ) 
                            OR
                            ( object_id='".$object_id."' and object_parent_lesson='0' AND object_parent_course='".$current_course_id."' )
                            OR 
                            object_id='0' 
                             ";
            }elseif ('sfwd-topic' == $post_type ) {
                    $where = "( object_id='".$object_id."' and object_parent_lesson='0' and object_parent_course='0' ) 
                            OR
                            ( object_id='".$object_id."' and object_parent_lesson='0' AND object_parent_course='".$current_course_id."' )
                            OR 
                            object_id='0' ";
            }

            if( ! empty( $cat_string ) ) {
                $where .= " or category in (".$cat_string.")";
            }
            if( ! empty( $tag_string ) ) {
                $where .= " or tag in (".$tag_string.")";
            }

            $query = "SELECT * FROM {$wpdb->prefix}csld_events WHERE ( ( $where ) and object_type in ($allowed_types) )";
            if( count( $user_groups ) > 0 ) {
                $query .= " and ( ld_group in ( ".implode(', ', $user_groups )." )  or ld_group = '' or ld_group = '0')";
            } else {
                $query .= " and ( ld_group = '' or ld_group = '0' )";
            }

            $show_hide_action = get_post_meta( $object_id, '_show_hide_action', true );
            if( empty( $show_hide_action ) ) {
                if( $post_type == 'sfwd-lessons' ) {
                    if( intval( $parent_course_id ) > 0 ) {
                        $course_id = $parent_course_id;
                    } else {
                        $course_id = learndash_get_course_id( $object_id );
                    }

                    if( intval( $course_id ) > 0 ) {
                        $show_hide_action = get_post_meta( $course_id, '_show_hide_action', true );
                        if( empty( $show_hide_action ) ) {
                            $show_hide_action = get_option( 'course_scheduler_ld_addon_setting' );
                        }
                    } else {
                        $show_hide_action = get_option( 'course_scheduler_ld_addon_setting' );
                    }
                } else {
                    $show_hide_action = get_option( 'course_scheduler_ld_addon_setting' );
                }
            }

            $date_today = current_time('timestamp');
            $today = current_time('mysql');
            if( $show_hide_action != 'show' ) {
                $query .= " and '$today' between start and end";
            }
            $query .= " order by start desc";
            $results = $wpdb->get_results($query);

            $categories = $this->get_terms_ids_by_id_n_taxonomy( $object_id, $cat_taxonomy);
            $tags = $this->get_terms_ids_by_id_n_taxonomy( $object_id, $tag_taxonomy );
            $display_dates = array();
            $is_in_hide_range = false;
            $format = get_option( 'date_format' );

            foreach( $results as $rec ) {
                if( $rec->object_id == $object_id || $rec->object_id == '0' ) {
                    $is_users_n_roles = $this->is_exist_allowed_users_n_roles( $rec->user_filter_type, $rec->excluded_role, $rec->excluded_users );
                    $is_group   = $this->is_exist_in_groups( $object_id, $rec->ld_group );
                    $is_cat     = $this->is_exist_in_terms( $rec->category, $object_id, $cat_taxonomy, 'category' );
                    $is_tag     = $this->is_exist_in_terms( $rec->tag, $object_id, $tag_taxonomy, 'tag' );

                    if( $is_cat && $is_tag && $is_group && $is_users_n_roles ) {

                        $subsdate = $this->get_course_subscription_date( $object_id );
                        $start = strtotime( $rec->start );
                        $end = strtotime( $rec->end );
                        if( $rec->is_subsdate_as_startdate == 'Yes' && intval( $subsdate ) > 0 ) {
                            $start = $subsdate;
                            $end = strtotime( '+'.$rec->duration.' '.$rec->duration_type, $subsdate );
                        } else if(  $rec->is_subsdate_as_startdate == 'Yes' && intval( $subsdate ) <= 0 ) {
                            $start = 0;
                            $end = 0;
                        }

                        if( $start > 0 && $end > 0 ) {
                            if( $show_hide_action == 'hide' ) {
                                if( $start <= $date_today && $date_today <=  $end ) {
                                    $is_in_hide_range = true;
                                    $rec_id = $rec->id;
                                }
                            } else {
                                if( ( $start > $date_today && $date_today >  $end ) || ( $start > $date_today && $end > $date_today ) || ( $start < $date_today && $end < $date_today ) ) {
                                    $is_in_hide_range = true;
                                    $rec_id = $rec->id;
                                } elseif( $date_today >= $start && $date_today <= $end  ) {
                                    $is_in_hide_range = false;
                                    $rec_id = $rec->id;
                                }
                            }
                        }
                    }
                }
            }
            
            if( $is_in_hide_range )
                return array( 'rec_id'=>$rec_id, 'status' => $is_in_hide_range, 'display'=>$show_hide_action, 'object_id'=>$object_id, 'object_type'=>$post_type, 'tvp'=>'condition' );
            else {
                if( $post_type=='sfwd-courses' ) {
                    if( intval( $lesson ) > 0 ) {
                        return array( 'rec_id'=>$rec_id, 'status' => false, 'display' => 'show', 'object_id'=>$lesson, 'object_type'=>$post_type, 'tvp'=>'lesson' );
                    } else {
                        return array( 'rec_id'=>$rec_id, 'status' => false, 'display' => $show_hide_action, 'object_id' => $object_id, 'object_type'=>$post_type, 'tvp'=>'courses' );
                    }
                } else {

                    if( $post_type=='sfwd-lessons' ) {

                        if( intval( $parent_course_id ) > 0 ) {
                            $course_id = $parent_course_id;
                        } else {
                            $course_id = learndash_get_course_id( $object_id );
                        }

                        $course_show_hide_action = get_post_meta( $course_id, '_show_hide_action', true );

                        $show_hide_action = get_post_meta( $object_id, '_show_hide_action', true );
                        if( $show_hide_action == 'hide' ) {
                            return array( 'rec_id' => $rec_id,'status'=>true, 'display'=>$show_hide_action, 'object_id'=>$object_id, 'object_type'=>$post_type, 'tvp'=>'lesson' );
                        } else if( $show_hide_action == 'show' && ( $course_show_hide_action=='show' || empty( $course_show_hide_action ) ) ) {
                            return array( 'rec_id' => $rec_id,'status'=>false, 'display'=>$show_hide_action, 'object_id'=>$object_id, 'object_type'=>$post_type, 'tvp'=>'lesson' );
                        } else if( $show_hide_action == 'show' && $course_show_hide_action=='hide' ) {
                            return $ret = self::check_show_hide_status( $course_id, $object_id, $parent_course_id );
                         } else {
                            return $ret = self::check_show_hide_status( $course_id, 0, $parent_course_id );
                        }
                    } else if( $post_type=='sfwd-topic' ) {
                        $lesson_id = learndash_get_lesson_id( $object_id );
                        return self::check_show_hide_status( $lesson_id, 0, $parent_course_id );
                    } else if( $post_type=='sfwd-quiz' ) {
                        $lesson_id = learndash_get_lesson_id( $object_id, 0, $parent_course_id );
                        if( intval( $lesson_id ) > 0  )
                            return self::check_show_hide_status( $lesson_id, 0, $parent_course_id );
                        else {
                            if( intval( $parent_course_id ) > 0 ) {
                                $course_id = $parent_course_id;
                            } else {
                                $course_id = learndash_get_course_id( $object_id );
                            }
                            return self::check_show_hide_status( $course_id, 0, $parent_course_id );
                        }
                    }
                }
            }
        }

        return array( 'rec_id'=>$rec_id, 'status'=>true, 'display'=>'', 'object_id'=>$object_id, 'object_type'=>$post_type, 'tvp'=>'no_post_type' );
    }

    /**
     * Show a message if parent is hidden for a specific event.
     *
     * @param  $object_id
     * @param  $parent_check
     * @return none
     */
    function show_parent_hidden_message( $object_id, $parent_check , $rec_id = 0) {
        global $wpdb;

        $query = "SELECT * FROM {$wpdb->prefix}csld_events WHERE id='".$rec_id."'";
        $results = $wpdb->get_results($query);
        if( count( $results ) > 0 ) {
            $record = $results[0];
            if( intval( $record->posted_by ) > 0 ) {
                switch( trim( $parent_check[ 'object_type' ] ) ) {
                    case 'sfwd-courses':
                        $parent_hide_course_message = html_entity_decode( get_user_meta( $record->posted_by, 'cs_ld_addon_parent_hide_courses_message', true ) );
                        if( empty( $parent_hide_course_message ) ) {
                            $parent_hide_course_message = html_entity_decode( get_option( 'cs_ld_addon_parent_hide_courses_message' ) );
                        }
                        return $parent_hide_course_message;
                        break;
                    case 'sfwd-lessons':
                        $parent_hide_lesson_message = html_entity_decode( get_user_meta( $record->posted_by, 'cs_ld_addon_parent_hide_lesson_message', true ) );
                        if( empty( $parent_hide_lesson_message ) ) {
                            $parent_hide_lesson_message = html_entity_decode( get_option( 'cs_ld_addon_parent_hide_lesson_message' ) );
                        }

                        return $parent_hide_lesson_message;
                        break;
                    case 'sfwd-topic':
                        $parent_hide_topic_message = apply_filters( 'cs_ld_addon_parent_hide_topic_message',__('You are unable to view this content because its parent topic is hidden.', "cs_ld_addon"));
                        // if( empty( $parent_hide_topic_message ) ) {
                        //     $parent_hide_topic_message = html_entity_decode( get_option( 'cs_ld_addon_parent_hide_lesson_message' ) );
                        // }

                        return $parent_hide_topic_message;
                        break;
                }
            }
        }

        switch( trim( $parent_check[ 'object_type' ] ) ) {
            case 'sfwd-courses':
                return  html_entity_decode( get_option( 'cs_ld_addon_parent_hide_courses_message' ) );
                break;
            case 'sfwd-lessons':
                return  html_entity_decode( get_option( 'cs_ld_addon_parent_hide_lesson_message' ) );
                break;
        }
    }

    /**
     * Shortcode to output object(course/lesson/quiz/topic) dates
     *
     * @param  array    $atts   shortcode attributes
     * @return string           output of shortcode
     */
    function check_node_availability( $object_id ) {
        $show_hide_action = get_post_meta( $object_id, '_show_hide_action', true );
        if( empty( $show_hide_action ) ) {
            if( ! empty( $status ) ) {
                $show_hide_action = $status;
            } else {
                $show_hide_action = get_option( 'course_scheduler_ld_addon_setting' );
            }
        }

        if( $show_hide_action == 'hide' ) {
            return false;
        } else {
            return true;
        }

    }

    /**
     * Shortcode to output object(course/lesson/quiz/topic) dates
     *
     * @param  array    $atts   shortcode attributes
     * @return string           output of shortcode
     */
    function csld_schedule_shortcode( $atts ) {

        global $wpdb;
        
        $output = '';
        if( isset( $atts[ 'object_id' ] ) && ! empty( $atts[ 'object_id' ] ) ) {
            $object_id = $atts[ 'object_id' ];
            $post_type = get_post_type( $object_id );

            if ( isset( $post_type ) && ( 'sfwd-courses' == $post_type || 'sfwd-lessons' == $post_type || 'sfwd-topic' == $post_type || 'sfwd-quiz' == $post_type ) ) {

                $parent_course_id = 0;
                if( isset( $atts[ 'course_id' ] ) && ! empty( $atts[ 'course_id' ] ) ) {
                    $parent_course_id = $atts[ 'course_id' ];
                }

                $roles = array();
                $user_id = '';
                if( is_user_logged_in() ) {
                    $user = wp_get_current_user();
                    $user_id = $user->ID;
                    $roles = ( array ) $user->roles;
                }
                $user_groups = self::cs_ld_get_user_grups( $user_id );
                $where = " 1=1 ";
                if( 'sfwd-courses' == $post_type ) {
                    $where = "( object_id='".$object_id."' and object_parent_course='0' )";
                } else {
                    $where = "( object_id='".$object_id."' and object_parent_course='".$parent_course_id."' )";
                }

                $query = "SELECT * FROM {$wpdb->prefix}csld_events WHERE ".$where;
                if( count( $user_groups ) > 0 ) {
                    $query .= " and ( ld_group in ( ".implode(', ', $user_groups )." )  or ld_group = '' or ld_group = '0' )";
                } else {
                    $query .= " and ( ld_group = '' or ld_group = '0' )";
                }
                
                $results = $wpdb->get_results($query);
                if( count( $results ) > 0 ) {
                    foreach( $results as $row ) {

                        $course_id = $row->object_parent_course;
                        $lesson_id = $row->object_parent_lesson;

                        $parent_check = self::check_show_hide_status( $row->object_parent_lesson, 0, $row->object_parent_course );
                        if( is_array( $parent_check ) && count( $parent_check ) > 0 ) {
                            $parent_msg = self::show_parent_hidden_message(  $row->object_id, $parent_check,$row->id );
                            if( $parent_check['status'] == true && ! empty( $parent_msg ) ) {
                                $output = '<div class = "csld-object-record">';
                                $output .= '<div class="csld-object-title">'.get_the_title( $object_id ).'</div>';
                                $output .= self::show_parent_hidden_message(  $object_id, $parent_check ,$row->id);
                                $output .= '</div>';
                                continue;
                            } else {
                                $status = $parent_check['display'];
                            }
                        }

                        $parent_hidden_for_all_user_check = self::check_parent_hidden_for_all_user_meta_setting( $row->object_parent_lesson, 0, $row->object_parent_course );
                        if( is_array( $parent_hidden_for_all_user_check ) && count( $parent_hidden_for_all_user_check ) > 0 ) {
                            if( $parent_hidden_for_all_user_check['hidden'] == 'yes' ) {
                                $output = '<div class = "csld-object-record">';
                                $output .= '<div class="csld-object-title">'.get_the_title( $object_id ).'</div>';

                                $rec_type = '';
                                if( 'sfwd-courses' == $post_type ) {
                                    $rec_type = 'Course';
                                } elseif( 'sfwd-lessons' == $post_type ) {
                                    $rec_type = 'Lesson';
                                } elseif( 'sfwd-quiz' == $post_type ) {
                                    $rec_type = 'Quiz';
                                } elseif( 'sfwd-topic' == $post_type ) {
                                    $rec_type = 'Topic';
                                }

                                $short_code_message = '';
                                $message_option = html_entity_decode( get_user_meta( $object_id, 'cs_ld_addon_hide_for_all_'.strtolower( $rec_type ) .'_message', true ) );
                                if( ! empty( $message_option ) ) {
                                    $short_code_message = $message_option;
                                } else {
                                    $short_code_message = html_entity_decode( get_option( 'cs_ld_addon_hide_for_all_'.strtolower( $rec_type ) .'_message' ) );
                                }

                                $output .= $short_code_message;
                                $output .= '</div>';
                                continue;
                            } else {
                                $status = $parent_check['display'];
                            }
                        }

                        $list = '';
                        if( 'sfwd-courses' == $post_type ) {
                            $list = $this->ldccShowHide( $object_id, 'ld_course_category', 'ld_course_tag', array($row), 'Course', true, $status, $course_id, $lesson_id );
                        } elseif( 'sfwd-lessons' == $post_type ) {
                            $list = $this->ldccShowHide( $object_id, 'ld_lesson_category', 'ld_lesson_tag', array($row), 'Lesson', true, $status, $course_id, $lesson_id );
                        } elseif( 'sfwd-quiz' == $post_type ) {
                            $list = $this->ldccShowHide( $object_id, 'category', 'post_tag', array($row), 'Quiz', true, $status, $course_id, $lesson_id );
                        } elseif( 'sfwd-topic' == $post_type ) {
                            $list = $this->ldccShowHide( $object_id, 'ld_topic_category', 'ld_topic_tag', array($row), 'Topic', true, $status, $course_id, $lesson_id );
                        }

                        if( ! empty( trim( $list ) ) ) {
                            $output .= '<div class = "csld-object-record">';
                            $output .= '<div class="csld-object-title">'.get_the_title( $object_id ).'</div>';
                            $output .= $list;
                            $output .= '</div>';
                        }
                    }
                } else {

                    $csld_hide_all_users = get_post_meta( $object_id, '_csld_hide_all_users', true );
                    if( empty( $csld_hide_all_users ) ) {
                        $csld_hide_all_users = get_option( 'course_scheduler_ld_addon_hide_all_users' );
                    }

                    if( strtolower( $csld_hide_all_users ) == 'yes' ) {
                        $rec_type = '';
                        if( 'sfwd-courses' == $post_type ) {
                            $rec_type = 'Course';
                        } elseif( 'sfwd-lessons' == $post_type ) {
                            $rec_type = 'Lesson';
                        } elseif( 'sfwd-quiz' == $post_type ) {
                            $rec_type = 'Quiz';
                        } elseif( 'sfwd-topic' == $post_type ) {
                            $rec_type = 'Topic';
                        }

                        $short_code_message = '';
                        $message_option = html_entity_decode( get_user_meta( $object_id, 'cs_ld_addon_hide_for_all_'.strtolower( $rec_type ) .'_message', true ) );
                        if( ! empty( $message_option ) ) {
                            $short_code_message = $message_option;
                        } else {
                            $short_code_message = html_entity_decode( get_option( 'cs_ld_addon_hide_for_all_'.strtolower( $rec_type ) .'_message' ) );
                        }

                        $output .= '<div class = "csld-object-record">';
                        $output .= '<div class="csld-object-title">'.get_the_title( $object_id ).'</div>';
                        $output .= $short_code_message;
                        $output .= '</div>';
                    }
                }
            }
        }
        return $output;
    }

    function current_user_has_specific_role() {
        $user = wp_get_current_user();
        $roles = $user->roles;
        $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) ) {
                    return true;
                }
            }
        }
        
        return false;
    }

    function ld_cms_calendar_cb( ) {
	    $active_tab = isset($_GET['tab']) ? trim($_GET['tab']) : '';

	    if( $active_tab === 'calendar' || $active_tab === '' ) {
		    //Enqueue calendar assets
		    LD_CMS_HELPER::enqueue_calendar_scripts();

        }

        ob_start();
        if( is_user_logged_in() ) {
            $user_id = get_current_user_id();
            if( $this->current_user_has_specific_role( ) || is_super_admin( $user_id ) ) {

                $csld_user_groups = learndash_get_administrators_group_ids( $user_id );

                if ( count( $csld_user_groups ) > 0 || is_super_admin( $user_id ) || 1 ) 
                {

                    $settings_sections = array (
                        'calendar' => array(
                            'title' => __( 'Calendar', 'cs_ld_addon' ),
                            'icon' => 'fa-hashtag',
                        ),
                        'courses' => array(
                            'title' => __( LearnDash_Custom_Label::get_label( 'course' ) . ' Messages', 'cs_ld_addon' ),
                            'icon' => 'fa-hashtag',
                        ),
                        'lessons' => array(
                            'title' => __( LearnDash_Custom_Label::get_label( 'lesson' ) . ' Messages', 'cs_ld_addon' ),
                            'icon' => 'fa-arrow-up',
                        ),
                        'topics' => array(
                            'title' => __( LearnDash_Custom_Label::get_label( 'Topic' ) . ' Messages', 'cs_ld_addon' ),
                            'icon' => 'fa-shield',
                        ),
                        'quizzes' => array(
                            'title' => __( LearnDash_Custom_Label::get_label( 'quiz' ) . ' Messages', 'cs_ld_addon' ),
                            'icon' => 'fa-info',
                        )
                    );


                    $settings_sections = apply_filters( 'cs_ld_settings_front_sections', $settings_sections );
                    ?>
<div class="wrap csld_front_wrapper">
    <div id="icon-options-general" class="icon32"></div>
    <h2><?php _e( 'LearnDash Course Planner Pro', 'cs_ld_addon' ); ?></h2>

    <div class="nav-tab-wrapper frnt-nv-wrpr">
        <?php
                            $current_page       = get_permalink();

                            foreach( $settings_sections as $key => $section ) {
                                $current_tab_link   = add_query_arg( 'tab', $key, $current_page );
                                ?>
        <a href="<?php echo $current_tab_link; ?>"
            class="nav-tab <?php echo $this->front_page_tab == $key ? 'nav-tab-active' : ''; ?>">
            <i class="fa <?php echo $section['icon']; ?>" aria-hidden="true"></i>
            <?php _e( $section['title'], 'cs_ld_addon' ); ?>
        </a>
        <?php
                            }
                            ?>
    </div>
    <div class="csld_front_tabs_wrapper">
        <?php
                                foreach( $settings_sections as $key => $section ) {
                                    if( $this->front_page_tab == $key ) {
                                        $key = str_replace( '_', '-', $key );
                                        include( 'views/tabs/' . $key . '.php' );
                                    }
                                }
                            ?>
    </div>
</div>
<?php
                } else {
                    ?>
<div class="wrap">
    <p><?php _e( 'You do not have administrative permission on any '. strtolower( LearnDash_Custom_Label::get_label( 'courses' ) ) .' groups.', 'cs_ld_addon' ); ?>
    </p>
</div>
<?php
                }
            } else {
                ?>
<div class="wrap">
    <p><?php _e( 'You do not have required permissions to access this resource.', 'cs_ld_addon' ); ?></p>
</div>
<?php
            }
        } else {
            ?>
<div class="wrap">
    <p><?php _e( 'Please, login before using this resource.', 'cs_ld_addon' ); ?></p>
</div>
<?php
        }

        return ob_get_clean();
    }

    function ld_cms_monthly_user_calendar_cb( $atts = [] , $content = null, $tag = '' ) {
        $atts = shortcode_atts(
            array(
                'user_id' => get_current_user_id(),
                'month' => date('m'),
                'year' => date('Y'),
            ), $atts, $tag
        );
        
	    LD_CMS_HELPER::enqueue_calendar_scripts();

        ob_start();
        if( is_user_logged_in() ) {

            $user_id = $atts['user_id'];
            ?>
                <div class="wrap csld_front_wrapper">
                    <div id="icon-options-general" class="icon32"></div>
                    <h2><?php _e( 'LearnDash Course Planner Pro: Monthly Calendar', 'cs_ld_addon' ); ?></h2>
                    <?php include( 'views/shortcodes/monthly-calendar.php' ); ?>

                </div>
            <?php
        } else {
            ?>
                <div class="wrap">
                    <p><?php _e( 'Please, login before using this resource.', 'cs_ld_addon' ); ?></p>
                </div>
            <?php
        }
        return ob_get_clean();
    }

    function ld_cms_user_calendar_cb( $atts = [] , $content = null, $tag = '' ) {
        //Enqueue fullcalendar assets
	    LD_CMS_HELPER::enqueue_calendar_scripts();
        wp_enqueue_style( 'jquery-ui');
        wp_enqueue_script( 'ld-cms-ui-js');
        ob_start();
        if( is_user_logged_in() ) {

            $atts = shortcode_atts(
                array(
                    'user_id' => get_current_user_id(),
                ), $atts, $tag
            );

            $user_id = $atts['user_id'];
            ?>
                <div class="wrap csld_front_wrapper">
                    <div id="icon-options-general" class="icon32"></div>
                    <h2><?php _e( 'LearnDash Course Planner Pro', 'cs_ld_addon' ); ?></h2>
                    <?php include( 'views/shortcodes/calendar.php' ); ?>

                </div>
            <?php
        } else {
            ?>
                <div class="wrap">
                    <p><?php _e( 'Please, login before using this resource.', 'cs_ld_addon' ); ?></p>
                </div>
            <?php
        }
        return ob_get_clean();
    }

	/**
     * Retrieve datetime based on add-on timezone
     *
	 * @param string $format
	 *
	 * @return false|string
	 */
    function get_date_time($format = 'Y-m-d H:i:s') {
		$tz = date_default_timezone_get();
		date_default_timezone_set( $this->get_timezone() );
		$datetime = date( $format);
		date_default_timezone_set( $tz );

		return $datetime;
	}

	/**
     * Retrieve add-on timezone
     *
	 * @return string timezone/UTC
	 */
	function get_timezone() {

		$saved_timezone = get_option( 'course_scheduler_ld_time_zone', '');

		if( empty($saved_timezone) || $saved_timezone === 'select_time_zone' ) {
			return 'UTC';
		}

		return $saved_timezone;
	}
}
$GLOBALS['lcms_license'] = new CS_LD_HELPER();


/*add_action('admin_init', function() {
    var_dump($GLOBALS['lcms_license']->get_date_time());
	//exit;
});*/