<?php
namespace AcademyProAdvancedAnalytics;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

use AcademyProAdvancedAnalytics\Helper;
use Academy\Classes\Sanitizer;
use Academy\Classes\AbstractAjaxHandler;

class Ajax extends AbstractAjaxHandler {
	protected $namespace = 'academy_pro_advanced_analytics';
	public function __construct() {
		$this->actions = array(
			'get_analytics_for_earnings' => array(
				'callback' => array( $this, 'get_analytics_for_earnings' ),
				'capability'    => 'manage_options'
			),
			'get_analytics_for_refunds' => array(
				'callback' => array( $this, 'get_analytics_for_refunds' ),
				'capability'    => 'manage_options'
			),
			'get_analytics_for_discounts' => array(
				'callback' => array( $this, 'get_analytics_for_discounts' ),
				'capability'    => 'manage_options'
			),
			'get_popular_courses' => array(
				'callback' => array( $this, 'get_popular_courses' ),
				'capability'    => 'manage_options'
			),
			'recent_enrolled_courses' => array(
				'callback' => array( $this, 'recent_enrolled_courses' ),
				'capability'    => 'manage_options'
			),
			'recent_reviews' => array(
				'callback' => array( $this, 'recent_reviews' ),
				'capability'    => 'manage_options'
			),
			'recent_students' => array(
				'callback' => array( $this, 'recent_students' ),
				'capability'    => 'manage_options'
			),
			'recent_instructors' => array(
				'callback' => array( $this, 'recent_instructors' ),
				'capability'    => 'manage_options'
			),
			'get_course_total_views' => array(
				'callback' => array( $this, 'get_course_total_views' ),
				'capability'    => 'manage_options'
			),
			'admin/get_courses' => array(
				'callback' => array( $this, 'get_courses' ),
				'capability'    => 'manage_options'
			),
			'admin/get_students_by_course_id' => array(
				'callback' => array( $this, 'get_students_by_course_id' ),
				'capability'    => 'manage_options'
			),
			'admin/get_instructors_by_course_id' => array(
				'callback' => array( $this, 'get_instructors_by_course_id' ),
				'capability'    => 'manage_options'
			),
			'admin/get_students' => array(
				'callback' => array( $this, 'get_students' ),
				'capability'    => 'manage_options'
			),
			'admin/get_student_details' => array(
				'callback' => array( $this, 'get_student_details' ),
				'capability'    => 'manage_options'
			),
			'frontend/get_student_details' => array(
				'callback' => array( $this, 'get_student_details' ),
				'capability'    => 'manage_academy_instructor'
			),
			'admin/get_single_course_view_details' => array(
				'callback' => array( $this, 'get_single_course_view_details' ),
				'capability'    => 'manage_options'
			)
		);
	}

	public function get_analytics_for_earnings() {
		$earnings = Helper::get_earnings_analytics();
		wp_send_json_success( $earnings );
	}

	public function get_analytics_for_refunds() {
		$refunds = Helper::get_refunds_analytics();
		wp_send_json_success( $refunds );
	}

	public function get_analytics_for_discounts() {
		$discounts = Helper::get_discounts_analytics();
		wp_send_json_success( $discounts );
	}

	public function get_popular_courses() {
		$response = [];
		$courses = Helper::get_popular_courses();
		if ( is_array( $courses ) ) {
			foreach ( $courses as $course ) {
				$course->permalink = get_permalink( $course->ID );
				$course->reviews = \Academy\Helper::get_course_rating( $course->ID );
				$response[] = $course;
			}
		}
		wp_send_json_success( $response );
	}

	public function recent_enrolled_courses() {
		$response = [];
		$courses = Helper::get_recent_enrolled_courses();
		if ( is_array( $courses ) ) {
			foreach ( $courses as $course ) {
				$course->permalink = get_permalink( $course->ID );
				$course->reviews = \Academy\Helper::get_course_rating( $course->ID );
				$response[] = $course;
			}
		}
		wp_send_json_success( $response );
	}

	public function recent_reviews() {
		$response = [];
		$reviews = Helper::get_recent_reviews();
		if ( is_array( $reviews ) ) {
			foreach ( $reviews as $review ) {
				$review->course = [
					'title' => get_the_title( $review->comment_post_ID ),
					'permalink' => get_permalink( $review->comment_post_ID )
				];
				$response[] = $review;
			}
		}
		wp_send_json_success( $response );
	}
	public function recent_students() {
		$students = Helper::get_recent_registered_students();
		wp_send_json_success( $students );
	}
	public function recent_instructors() {
		$courses = Helper::get_recent_registered_instructors();
		wp_send_json_success( $courses );
	}

	public function get_course_total_views( $payload_data ) {
		$payload = Sanitizer::sanitize_payload( [
			'page' => 'integer',
			'per_page' => 'integer'
		], $payload_data );

		$response = [];
		$page = $payload['page'] ?? 1;
		$per_page = $payload['per_page'] ?? 10;
		$offset = ( $page - 1 ) * $per_page;
		$args = array(
			'post_type'     => 'academy_courses',
			'post_status'   => 'publish',
			'offset'         => $offset,
			'posts_per_page' => $per_page
		);

		$query = new \WP_Query( $args );

		// Set the x-wp-total header
		header( 'x-wp-total: ' . $query->found_posts );

		if ( $query->have_posts() ) {
			while ( $query->have_posts() ) :
				$query->the_post();
				$course = get_post();
				$course->permalink = get_permalink( $course->ID );
				$course->reviews = \Academy\Helper::get_course_rating( $course->ID );
				$course->total_course_views = Helper::get_total_views_by_course_id( $course->ID );
				$response[] = $course;
			endwhile;
			wp_reset_postdata();
		}//end if

		wp_send_json_success( $response );
	}

	public function get_courses( $payload_data ) {
		$payload = Sanitizer::sanitize_payload( [
			'page' => 'integer',
			'per_page' => 'integer'
		], $payload_data );

		$page = $payload['page'] ?? 1;
		$per_page = $payload['per_page'] ?? 10;
		$offset = ( $page - 1 ) * $per_page;

		$response = [];
		$args = array(
			'post_type'     => 'academy_courses',
			'post_status'   => 'publish',
			'offset'         => $offset,
			'posts_per_page' => $per_page
		);

		$query = new \WP_Query( $args );

		// Set the x-wp-total header
		header( 'x-wp-total: ' . $query->found_posts );

		$Analytics = new \Academy\Classes\Analytics();

		if ( $query->have_posts() ) {
			while ( $query->have_posts() ) :
				$query->the_post();
				$course = get_post();
				$course_curriculums = \Academy\Helper::get_course_curriculums_number_of_counts( $course->ID );
				$course->number_of_questions     = $Analytics->get_number_of_questions_by_course_id( $course->ID );
				$course->number_of_instructors   = $Analytics->get_total_number_of_instructors( $course->ID );
				$course->number_of_lessons      = $course_curriculums['total_lessons'];
				$course->number_of_quizzes         = $course_curriculums['total_quizzes'];
				$course->number_of_assignments   = $course_curriculums['total_assignments'];
				$course->number_of_tutor_bookings  = $course_curriculums['total_tutor_bookings'];
				$course->number_of_zoom_meetings = $course_curriculums['total_zoom_meetings'];
				$course->number_of_enrolled     = $Analytics->get_total_number_of_enrolled_by_course_id( $course->ID );
				$course->number_of_reviews                 = $Analytics->get_total_number_of_reviews_by_course_id( $course->ID );
				$course_type = \Academy\Helper::get_course_type( $course->ID );
				$course->course_type = $course_type;
				if ( 'paid' === $course_type ) {
					$course->total_earnings          = $Analytics->get_total_earning_by_course_id( $course->ID );
				}
				$response[] = apply_filters( 'academy/get_course_analytics', $course, $course->ID );
			endwhile;
			wp_reset_postdata();
		}//end if
		wp_send_json_success( $response );
	}

	public function get_students_by_course_id( $payload_data ) {
		$payload = Sanitizer::sanitize_payload( [
			'page' => 'integer',
			'per_page' => 'integer',
			'course_id' => 'integer',
		], $payload_data );

		$page = $payload['page'] ?? 1;
		$per_page = $payload['per_page'] ?? 10;
		$course_id = $payload['course_id'] ?? 0;
		$offset = ( $page - 1 ) * $per_page;

		global $wpdb;
		$courses_data = [];
		$course_id = (int) isset( $_POST['course_id'] ) ? sanitize_text_field( wp_unslash( $_POST['course_id'] ) ) : 0;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$courses = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT * 
				FROM {$wpdb->posts}
				WHERE post_type = %s
				AND post_status = %s
				AND post_parent = %d ORDER BY post_date DESC LIMIT %d, %d;",
				'academy_enrolled', 'completed', $course_id, $offset, $per_page
			)
		);

		$Analytics = new \Academy\Classes\Analytics();
		// Set the x-wp-total header
		header( 'x-wp-total: ' . $Analytics->get_total_number_of_student_by_course_id( $course_id ) );

		$course_curriculums = \Academy\Helper::get_course_curriculums_number_of_counts( $course_id );
		foreach ( $courses as $course ) {
			$student = get_user_by( 'ID', $course->post_author );
			$completed_topics = json_decode( get_user_meta( $student->ID, 'academy_course_' . $course_id . '_completed_topics', true ) );

			$total_completed_topics = \Academy\Helper::get_total_number_of_completed_course_topics_by_course_and_student_id( $course_id, $student->ID );
			$percentage              = \Academy\Helper::calculate_percentage( $course_curriculums['total_topics'], $total_completed_topics );
			$course->student_ID                 = $student->ID; //phpcs:ignore
			$course->student_display_name       = $student->display_name;
			$course->number_of_lessons          = $course_curriculums['total_lessons'];
			$course->number_of_quizzes          = $course_curriculums['total_quizzes'];
			$course->number_of_assignments      = $course_curriculums['total_assignments'];
			$course->number_of_tutor_bookings   = $course_curriculums['total_tutor_bookings'];
			$course->number_of_zoom_meetings    = $course_curriculums['total_zoom_meetings'];
			$course->completed_topics           = $completed_topics;
			$course->progress_percentage        = $percentage . '%';
			$courses_data[]                     = apply_filters( 'academy/get_course_analytics', $course, $course_id );
		}
		wp_send_json_success( $courses_data );
	}

	public function get_instructors_by_course_id( $payload_data ) {
		$payload = Sanitizer::sanitize_payload( [
			'page' => 'integer',
			'per_page' => 'integer',
			'course_id' => 'integer',
		], $payload_data );

		$response = [];
		$instructors = [];
		$page = $payload['page'] ?? 1;
		$per_page = $payload['per_page'] ?? 10;
		$course_id = $payload['course_id'] ?? 0;
		$offset = ( $page - 1 ) * $per_page;
		$course = get_post( $course_id );

		$Analytics = new \Academy\Classes\Analytics();
		// Set the x-wp-total header
		header( 'x-wp-total: ' . $Analytics->get_total_number_of_instructors( $course_id ) );

		if ( \Academy\Helper::get_addon_active_status( 'multi_instructor' ) ) {
			$instructors = \Academy\Helper::get_instructors_by_course_id( $course_id, $offset, $per_page );
		} else {
			$instructors = \Academy\Helper::get_instructor_by_author_id( $course->post_author );
		}
		if ( count( $instructors ) ) {
			foreach ( $instructors as $instructor ) {
				$instructor->total_number_of_courses = count_user_posts( $instructor->ID, 'academy_courses' );
				$instructor->total_number_of_students = \Academy\Helper::get_total_number_of_students_by_instructor( $instructor->ID );
				$instructor->reviews = \Academy\Helper::get_instructor_ratings( $instructor->ID );
				$response[] = $instructor;
			}
		}
		wp_send_json_success( $response );
	}

	public function get_students( $payload_data ) {
		$payload = Sanitizer::sanitize_payload( [
			'page' => 'integer',
			'per_page' => 'integer',
		], $payload_data );

		$page = $payload['page'] ?? 1;
		$per_page = $payload['per_page'] ?? 10;
		$offset = ( $page - 1 ) * $per_page;

		$Analytics = new \Academy\Classes\Analytics();

		// Set the x-wp-total header
		header( 'x-wp-total: ' . $Analytics->get_total_number_of_students() );

		$array = [];
		$students = \Academy\Helper::get_all_students( $offset, $per_page );
		foreach ( $students as $student ) {
			$Analytics    = new \Academy\Classes\Analytics();
			$complete_course            = (int) $Analytics->get_total_number_of_completed_courses_by_student_id( $student->ID );
			$course_taken               = (int) $Analytics->get_total_number_of_enrolled_courses( $student->ID );
			$student->total_number_of_enrolled_course   = $course_taken;
			$student->total_number_of_complete_course   = $complete_course;
			$student->total_number_of_course_taken      = $course_taken;
			$student->total_number_of_inprogress_course = $course_taken - $complete_course;
			$student->total_number_of_write_reviews = $Analytics->get_total_number_of_reviews( $student->ID );
			$array[]                    = $student;
		}
		wp_send_json_success( $array );
	}

	public function get_student_details( $payload_data ) {
		$payload = Sanitizer::sanitize_payload( [
			'page' => 'integer',
			'per_page' => 'integer',
			'student_id' => 'integer',
		], $payload_data );

		$page = $payload['page'] ?? 1;
		$per_page = $payload['per_page'] ?? 10;
		$student_id = $payload['student_id'] ?? 0;
		$offset = ( $page - 1 ) * $per_page;

		$Analytics    = new \Academy\Classes\Analytics();
		$complete_course            = (int) $Analytics->get_total_number_of_completed_courses_by_student_id( $student_id );
		$course_taken               = (int) $Analytics->get_total_number_of_enrolled_courses( $student_id );

		$response = [
			'total_number_of_enrolled_course' => $course_taken,
			'total_number_of_complete_course' => $complete_course,
			'total_number_of_course_taken'      => $course_taken,
			'total_number_of_inprogress_course' => $course_taken - $complete_course,
			'total_number_of_write_reviews' => $Analytics->get_total_number_of_reviews( $student_id ),
			'enrolled_courses' => []
		];

		$enrolled_courses = [];

		// Set the x-wp-total header
		header( 'x-wp-total: ' . $Analytics->get_total_number_of_enrolled_courses( $student_id ) );

		// custom query
		$query = \Academy\Helper::get_enrolled_courses_by_user( $student_id, 'publish', $offset, $per_page );
		if ( $query && $query->have_posts() ) {
			while ( $query->have_posts() ) :
				$query->the_post();
				$course_id = get_the_ID();
				$enrolled_courses[] = apply_filters( 'academy/get_course_analytics', \Academy\Helper::prepare_analytics_for_user( $student_id, $course_id ), $course_id );
			endwhile;
		}//end if
		$response['enrolled_courses'] = $enrolled_courses;
		wp_send_json_success( $response );
	}

	public function get_single_course_view_details( $payload_data ) {
		$payload = Sanitizer::sanitize_payload( [
			'course_id' => 'integer',
		], $payload_data );

		$course_id = $payload['course_id'] ?? 0;

		$course_details = Helper::get_course_view_details( $course_id );
		wp_send_json_success( $course_details );
	}
}

