<?php
use Elementor\Tutor\Elementor_Helper;
if( class_exists( 'Ajax_handler' ) ) {
    return;
}
final class Ajax_handler {
	private static $_instance = null;

	public function __construct() {
		add_action( 'wp_ajax_review_ajax', [ $this, 'instructor_review_ajax' ] );
		add_action( 'wp_ajax_nopriv_review_ajax', [ $this, 'instructor_review_ajax' ] );

		add_action( 'wp_ajax_profile_course_enrolled', [ $this, 'enrolled_course_ajax' ] );
		add_action( 'wp_ajax_nopriv_profile_course_enrolled', [ $this, 'enrolled_course_ajax' ] );

		add_action( 'wp_ajax_course_search', [ $this, 'course_search' ] );
		add_action( 'wp_ajax_nopriv_course_search', [ $this, 'course_search' ] );
		
		
	}
	
	public static function instance() {

		if ( is_null( self::$_instance ) ) {
			self::$_instance = new self();
		}

		return self::$_instance;
	}

	public function course_search() {

		$search_post_category = esc_attr( $_REQUEST['category_val'] );
		$search_keyword       = esc_attr( $_REQUEST['keyword'] );

		$args = array(
			's'              => $search_keyword,
			'post_type'      => 'courses',
			'posts_per_page' => - 1,
		);

			if ( ! empty( $search_post_category ) ) {
				$args['tax_query'] = array(
					array(
						'taxonomy' => 'course-category',
						'field'    => 'term_id',
						'terms'    => $search_post_category,
					),

				);
			}
			$query = new WP_Query( $args );

			if ( ! empty( $query ) ) {
				if ( $query->have_posts() ) :
					echo '<ul>';
					while ( $query->have_posts() ) : $query->the_post();
						echo '<li>
							<div class="thumb"><a href="' . get_the_permalink() . '">' . get_the_post_thumbnail('','thumbnail') . '</a></div>
							<h3 class="title"><a href="' . get_the_permalink() . '">' . get_the_title() . '</a></h3>
						</li>';
					endwhile;
					echo '</ul>';
				else :
					echo '<div class="error_message">' . __( 'No Course Found.', 'histudy' ) . '</div>';
				endif;
			}
			die();
		

	}

	// Get enrolled courses by user id

	public function instructor_review_ajax() {

		$userid         = esc_attr( $_REQUEST['userid'] );
		$review_per_pge = esc_attr( $_REQUEST['review_per_page'] );
		$offset         = esc_attr( $_REQUEST['offset'] );

		$reviews = tutor_utils()->get_reviews_by_instructor( $userid, $offset, $review_per_pge );
		?>
        <div class="tutor-dashboard-content-inner">
            <div class="tutor-dashboard-reviews-wrap">
				<?php
				if ( $reviews->count ) {
					?>
                    <div class="tutor-dashboard-reviews">
						<?php
						foreach ( $reviews->results as $review ) {
							$profile_url = tutor_utils()->profile_url( $review->user_id );
							?>
                            <div class="tutor-dashboard-single-review tutor-review-<?php echo esc_attr( $review->comment_ID ); ?>">
                                <div class="tutor-dashboard-review-header">

                                    <div class="tutor-dashboard-review-heading">
                                        <div class="tutor-dashboard-review-title">
											<?php _e( 'Course: ', 'histudy' ); ?>
                                            <a href="<?php echo get_the_permalink( $review->comment_post_ID ); ?>"><?php echo get_the_title( $review->comment_post_ID ); ?></a>
                                        </div>
                                    </div>
                                </div>
                                <div class="individual-dashboard-review-body">
                                    <div class="individual-star-rating-wrap">
										<?php tutor_utils()->star_rating_generator( $review->rating ); ?>
                                        <p class="review-meta"><?php echo sprintf( __( '%s ago', 'histudy' ), human_time_diff( strtotime( $review->comment_date ) ) ); ?></p>
                                    </div>

									<?php echo wpautop( stripslashes( $review->comment_content ) ); ?>
                                </div>
                            </div>
							<?php
						}
						?>
                    </div>
				<?php } else {
					?>
                    <div class="tutor-dashboard-content-inner">
                        <p><?php _e( "Sorry, but you are looking for something that isn't here.", 'histudy' ); ?></p>
                    </div>
					<?php
				} ?>

            </div>
        </div>
		<?php
		die();
	}

	public function enrolled_course_ajax() {

		$userid          = esc_attr( $_REQUEST['userid'] );
		$user_type       = esc_attr( $_REQUEST['user_role'] );
		$course_per_page = esc_attr( $_REQUEST['course_per_page'] );
		$offset          = esc_attr( $_REQUEST['offset'] );

		if ( $user_type == "instructor" ) {
			$course_query_data = new WP_Query(
				array(
					'author'         => $userid,
					'posts_per_page' => $course_per_page,
					'post_type'      => tutor()->course_post_type,
					'offset'         => $offset,
				)
			);
		} else if ( $user_type == "student" ) {
			$course_ids = $this->get_enrolled_course_ids( $userid );
			if ( ! empty( $course_ids ) ) {
				if ( count( $course_ids ) ) {
					$course_post_type  = tutor()->course_post_type;
					$course_args       = array(
						'post_type'      => $course_post_type,
						'post__in'       => $course_ids,
						'posts_per_page' => $course_per_page,
						'offset'         => $offset,
					);
					$course_query_data = new WP_Query( $course_args );
				}
			} else {
				echo '<div class="alert alert-warning text-center empty_course_alert" role="alert">' . __( 'Sorry !!!  No Enrolled Course Found.', 'histudy' ) . '</div>';
			}

		}


		if ( ! empty( $course_query_data ) ) {

			if ( $course_query_data->have_posts() ) :
				while ( $course_query_data->have_posts() ) : $course_query_data->the_post();
					$course_id          = get_the_ID();
					$course_meta        = \Elementor_Helper::course_meta_data( $course_id );
					$post_thumbnail_url = get_the_post_thumbnail_url( $course_id );
					$course_categories  = get_the_terms( $course_id, TUTOR_TAXONOMY );
					$course_instructors = tutor_utils()->get_instructors_by_course( $course_id );
					$course_duration    = get_tutor_course_duration_context( $course_id );

					$course_price        = "Free";
					$courses_price_class = "free_course";
					if ( array_key_exists( '_tutor_course_price_type', $course_meta ) ) {
						if ( strtolower( $course_meta['_tutor_course_price_type'][0] ) != "free" ) {
							$course_price        = \Elementor_Helper::get_woocommerce_course_price( $course_meta['_tutor_course_product_id'][0] );
							$courses_price_class = "paid_course";
						}
					}
					$course_category_color_count = 1;

					if( function_exists( 'tutor' ) ) {
                        $total_lessons = tutor_utils()->get_lesson_count_by_course( $course_id );  
                        $total_lessons  = sprintf( _n( '%s Lesson', '%s Lessons', $total_lessons, 'histudy' ), $total_lessons );
                    }

					?>
                    <div class="col-lg-4 col-md-6 col-sm-12 course_archive_style_1 course_widget">
                        <div class="course-box style-1">
                            <div class="figure-box">
                                <img src="<?php echo get_the_post_thumbnail_url( $course_id ); ?>" alt="Course"
                                     width="500" height="273">
                            </div>
                            <div class="content-box">
								
                                <div class="category-name color-<?php echo esc_attr( $course_category_color_count ); ?>">
									<?php
									$course_category_color_count += 1;
									if ( $course_category_color_count > 5 ) {
										$course_category_color_count = 1;
									}
									foreach ( $course_categories as $index => $course_category ) {
										$Category_name_in_loop = $course_category->name;
										if ( $index > 0 ) {
											$Category_name_in_loop = ", " . $Category_name_in_loop;
										}
										echo wp_kses_post( $Category_name_in_loop );
									}
									?>
                                </div>
                                <h3 class="title"><?php the_title(); ?></h3>
                                <h4 class="sub-title">
									<?php
									foreach ( $course_instructors as $course_instructor ) {
										echo ucwords( $course_instructor->display_name );
									}
									?>
                                </h4>
                                <ul class="inline-list course-feature">
                                    <li>
                                        <i class="fas fa-file-excel"></i><?php echo esc_html($total_lessons); ?>
                                    </li>
                                    <li><i class="fas fa-briefcase"></i><?php _e( 'Online Class', 'histudy' ); ?></li>
                                </ul>
                                <div class="course-footer">
                                    <div class="course-fee"><?php echo wp_kses_post( $course_price ); ?></div>
                                    <ul class="course-rating inline-list">

										<?php
										$course_rating = tutor_utils()->get_course_rating( $course_id );
										tutor_utils()->star_rating_generator( $course_rating->rating_avg );
										?>
                                        <li>
                                            <span class="rating-count">(<?php echo esc_html($course_rating->rating_count); ?>)</span>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                            <div class="hover-content">
                                <div class="inner">
                                    <a href="#" class="course-wish-list tutor_addons_course-wish-list"
                                       course-id="<?php echo esc_attr( $course_id ); ?>"><i class="far fa-heart"></i>
                                        <div class="lds-dual-ring"></div>
                                    </a>
                                    <div class="category-name">
										<?php
										foreach ( $course_categories as $index => $course_category ) {
											$Category_name_in_loop = $course_category->name;
											if ( $index > 0 ) {
												$Category_name_in_loop = ", " . $Category_name_in_loop;
											}
											echo wp_kses_post( $Category_name_in_loop );
										}
										?>
                                    </div>
                                    <h3 class="title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
                                    <div class="course-admin">
                                        <div class="admin">
											<?php
											foreach ( $course_instructors as $course_instructor ) {
												echo tutor_utils()->get_tutor_avatar( $course_instructor->ID );
												echo "<span>".wp_kses_post(ucwords( $course_instructor->display_name ))."</span>";
											}
											?>
                                        </div>
                                        <ul class="course-rating inline-list">
											<?php
											$course_rating = tutor_utils()->get_course_rating( $course_id );
											tutor_utils()->star_rating_generator( $course_rating->rating_avg );
											?>
                                            <li>
                                                <span class="rating-count">(<?php echo esc_html( $course_rating->rating_count ); ?>)</span>
                                            </li>
                                        </ul>
                                    </div>
                                    <div class="description"><?php the_excerpt(); ?></div>
                                    <ul class="inline-list course-feature">
                                        <li>
                                            <i class="fas fa-bars"></i><?php echo esc_html($total_lessons); ?>
                                        </li>
                                        <li><i class="far fa-clock"></i>
											<?php
											if ( $course_duration ) {
												echo wp_kses_post($course_duration);
											}
											?>
                                        </li>
                                    </ul>
                                    <div class="course-footer">
                                        <a href="<?php esc_url( get_permalink( $course_id ) ); ?>" class="btn-fill style-4"><?php _e( 'See Details', 'histudy' ); ?></a>
                                        <div class="price"><?php echo wp_kses_post( $course_price ); ?></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
				<?php
				endwhile;
			else :
				$image_url = get_template_directory_uri(). '/assets/images/shape/emptystate.svg';
				$html = '';
				$html .= '<div class="w-100 rainbow-course-not-found-error container">';
				$html .= '<img src="'.esc_url( $image_url ).'" alt="'.__( 'No data found', 'histudy' ).'" />';
				$html .= '<h4 class="histudy-course-ajax-not-found-title">'.__( 'No Course found', 'histudy' ).'</h4>';
				$html .= "</div>";
				echo wp_kses_post($html);
			endif;
		}


		?>
        <div class="profile_enrolled_courses_pagination">
            <ul>
				<?php
				$page_index = 1;
				if ( $course_query_data->found_posts > $course_per_page ) {
					$total_index = ceil( $course_query_data->found_posts / $course_per_page );
					while ( $page_index <= $total_index ) {
						echo "<li class='$page_index'>$page_index</li>";
						$page_index ++;
					}
				}
				?>
            </ul>
        </div>
		<?php

		die();
	}

	public function get_enrolled_course_ids( $user_id = 0 ) {

		global $wpdb;
		$table_name = $wpdb->posts;
		$post_type  = "tutor_enrolled";
		$course_id  = $wpdb->get_col( $wpdb->prepare( "SELECT `post_parent` FROM `{$table_name}` WHERE `post_author`= $user_id AND `post_type` = '{$post_type}'" ) );

		return $course_id;
	}
}

Ajax_handler::instance();