<?php
namespace AcademyProGradeBook\Admin;

if ( ! defined( 'ABSPATH' ) ) {
	exit();
}

use AcademyProGradeBook\Helper as GradeHelper;
use stdClass;

class Ajax {

	public static function init(): void {
		$self = new self();
		add_action(
			'academy_quizzes/after_quiz_insert',
			[ $self, 'quiz_attempt_result_insert_to_grade_book_result' ],
			10,
			1
		);
		add_action(
			'academy_pro/frontend/after_evaluate_assignment',
			[
				$self,
				'assignment_result_insert_to_grade_book_result_when_evalute',
			],
			10,
			1
		);

		add_action(
			'wp_ajax_academy_pro_grade_book/generate_grade_builder_sample_data',
			[ $self, 'import_sample_grade_data' ]
		);
		add_action('wp_ajax_academy_pro_grade_book/add_new_grade', [
			$self,
			'add_new_grade',
		]);
		add_action('wp_ajax_academy_pro_grade_book/update_grade', [
			$self,
			'update_existing_grade',
		]);
		add_action('wp_ajax_academy_pro_grade_book/delete_grade', [
			$self,
			'delete_existing_grade',
		]);
		add_action('wp_ajax_academy_pro_grade_book/get_all_grades', [
			$self,
			'get_all_grades',
		]);

		add_action('wp_ajax_academy_pro_grade_book/get_student_grade', [
			$self,
			'get_student_grade',
		]);
		add_action('wp_ajax_academy_pro_grade_book/get_all_students_grade', [
			$self,
			'get_all_students_grade',
		]);
		add_action('wp_ajax_academy_pro_grade_book/delete_student_grade', [
			$self,
			'delete_student_grade_result',
		]);
		add_action(
			'wp_ajax_academy_pro_grade_book/delete_single_student_grade',
			[ $self, 'delete_student_single_grade_result' ]
		);
	}

	public function quiz_attempt_result_insert_to_grade_book_result(
		$quiz_data
	): void {
		$grade_data = GradeHelper::get_grade_by_percentage(
			$quiz_data->earned_percentage
		);

		if ( $grade_data ) {
			$grade_data = current( $grade_data );

			$quiz_data->gradebook_id = $grade_data->gradebook_id;
			$quiz_data->grade_name = $grade_data->grade_name;
			$quiz_data->grade_point = GradeHelper::get_max_grade_point();
			$quiz_data->user_grade_point = $grade_data->grade_point;

			if ( GradeHelper::insert_quiz_result( $quiz_data ) ) {
				GradeHelper::create_or_update_final_grade([
					'course_id' => $quiz_data->course_id,
					'user_id' => $quiz_data->user_id,
				]);
			}
		}
	}

	public function assignment_result_insert_to_grade_book_result_when_evalute(
		$assignment_data
	): void {
		$grade_data = GradeHelper::get_grade_by_percentage(
			$assignment_data->earned_percentage
		);

		if ( $grade_data ) {
			$grade_data = current( $grade_data );

			$assignment_data->gradebook_id = $grade_data->gradebook_id;
			$assignment_data->grade_name = $grade_data->grade_name;
			$assignment_data->grade_point = GradeHelper::get_max_grade_point();
			$assignment_data->user_grade_point = $grade_data->grade_point;

			if ( GradeHelper::insert_assignment_result( $assignment_data ) ) {
				GradeHelper::create_or_update_final_grade([
					'course_id' => $assignment_data->course_id,
					'user_id' => $assignment_data->user_id,
				]);
			}
		}
	}

	public function import_sample_grade_data(): void {
		check_ajax_referer( 'academy_nonce', 'security' );

		if ( ! current_user_can( 'manage_academy_instructor' ) ) {
			wp_die();
		}

		if ( GradeHelper::import_grade_book_sample_data() ) {
			wp_send_json_success();
		}

		wp_send_json_error();
	}

	public function add_new_grade(): void {
		check_ajax_referer( 'academy_nonce', 'security' );

		if ( ! current_user_can( 'manage_academy_instructor' ) ) {
			wp_die();
		}

		$grade_data = new stdClass();
		// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$grade_data->grade_name = sanitize_text_field( wp_unslash( $_POST['grade_name'] ) ) ?? '';
		$grade_data->grade_point = (float) sanitize_text_field(
			// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
			wp_unslash( $_POST['grade_point'] )
		) ?? 0;
		// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$grade_data->percent_from = (float) sanitize_text_field( wp_unslash( $_POST['percent_from'] ) ) ?? 0;
		// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$grade_data->percent_to = (float) sanitize_text_field( wp_unslash( $_POST['percent_to'] ) ) ?? 0;
		$grade_data->grade_config = maybe_serialize([
			// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
			'grade_color' => sanitize_text_field( wp_unslash( $_POST['grade_color'] ) ) ?? '',
		]);

		if ( GradeHelper::grade_book_validation( $grade_data ) ) {
			wp_send_json_error( GradeHelper::grade_book_validation( $grade_data ) );
		} else {
			$gradebook_id = GradeHelper::add_new_grade_book( $grade_data );
			if ( $gradebook_id ) {
				$grade_data = GradeHelper::get_the_latest_grade();
				wp_send_json_success( $grade_data );
			}

			wp_send_json_error();
		}
	}

	public function update_existing_grade(): void {
		check_ajax_referer( 'academy_nonce', 'security' );

		if ( ! current_user_can( 'manage_academy_instructor' ) ) {
			wp_die();
		}

		$grade_data = new stdClass();

		$grade_data->gradebook_id = (int) sanitize_text_field(
			// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
			wp_unslash( $_POST['gradebook_id'] )
		) ?? 0;
		// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$grade_data->grade_name = sanitize_text_field( wp_unslash( $_POST['grade_name'] ) ) ?? '';
		$grade_data->grade_point = (float) sanitize_text_field(
			// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
			wp_unslash( $_POST['grade_point'] )
		) ?? 0;
		$grade_data->percent_from = (float) sanitize_text_field(
			// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
			wp_unslash( $_POST['percent_from'] )
		) ?? 0;
		$grade_data->percent_to = (float) sanitize_text_field(
			// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
			wp_unslash( $_POST['percent_to'] )
		) ?? 0;
		$grade_data->grade_config = maybe_serialize([
			// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
			'grade_color' => sanitize_text_field( wp_unslash( $_POST['grade_color'] ) ),
		]);

		if ( GradeHelper::grade_book_validation( $grade_data ) ) {
			wp_send_json_error( GradeHelper::grade_book_validation( $grade_data ) );
		} else {
			if ( GradeHelper::update_grade_book( $grade_data ) ) {
				$grade_data->grade_config = maybe_unserialize(
					$grade_data->grade_config
				);
				wp_send_json_success( $grade_data );
			}

			wp_send_json_error();
		}
	}

	public function delete_existing_grade(): void {
		check_ajax_referer( 'academy_nonce', 'security' );

		if ( ! current_user_can( 'manage_academy_instructor' ) ) {
			wp_die();
		}

		// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$id = (int) sanitize_text_field( wp_unslash( $_POST['gradebook_id'] ) ) ?? 0;

		if ( GradeHelper::delete_grade_book( $id ) ) {
			wp_send_json_success();
		}

		wp_send_json_error();
	}

	public function get_all_grades(): void {
		check_ajax_referer( 'academy_nonce', 'security' );

		if ( ! current_user_can( 'manage_academy_instructor' ) ) {
			wp_die();
		}

		$args = new stdClass();

		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$page = (int) sanitize_text_field( $_POST['page'] ) ? sanitize_text_field( wp_unslash( $_POST['page'] ) ) : 1;
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$args->per_page = (int) sanitize_text_field( $_POST['per_page'] ) ? sanitize_text_field( wp_unslash( $_POST['per_page'] ) ) : 10;
		$args->offset = ( $page - 1 ) * $args->per_page;
		// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$args->search = sanitize_text_field( wp_unslash( $_POST['search'] ) ) ?? '';

		wp_send_json_success( GradeHelper::get_all_grades( $args ) );
	}

	public function get_student_grade(): void {
		check_ajax_referer( 'academy_nonce', 'security' );

		if ( ! current_user_can( 'manage_academy_instructor' ) ) {
			wp_die();
		}

		$args = new stdClass();
		// need to improve
		// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$page = (int) sanitize_text_field( wp_unslash( $_POST['page'] ) ) ?? 1;

		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$page = (int) sanitize_text_field( $_POST['page'] ) ? sanitize_text_field( wp_unslash( $_POST['page'] ) ) : 1;
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$args->per_page = (int) sanitize_text_field( $_POST['per_page'] ) ? sanitize_text_field( wp_unslash( $_POST['per_page'] ) ) : 10;
		$args->offset = ( $page - 1 ) * $args->per_page;
		// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$args->search = sanitize_text_field( wp_unslash( $_POST['search'] ) ) ?? '';
		// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$args->course_id = (int) sanitize_text_field( wp_unslash( $_POST['course_id'] ) ) ?? 0;
		// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$args->user_id = (int) sanitize_text_field( wp_unslash( $_POST['user_id'] ) ) ?? 0;

		wp_send_json_success(
			GradeHelper::get_all_or_single_student_grade_details_depend_on_args(
				$args
			)
		);
	}

	public function get_all_students_grade(): void {
		check_ajax_referer( 'academy_nonce', 'security' );

		if ( ! current_user_can( 'manage_academy_instructor' ) ) {
			wp_die();
		}
		global $wpdb;
		// We can use ass array
		$args = new stdClass();

		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$page = (int) sanitize_text_field( $_POST['page'] ) ? sanitize_text_field( wp_unslash( $_POST['page'] ) ) : 1;
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$args->per_page = (int) sanitize_text_field( $_POST['per_page'] ) ? sanitize_text_field( wp_unslash( $_POST['per_page'] ) ) : 10;
		$args->offset = ( $page - 1 ) * $args->per_page;
		// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$args->search = isset( $_POST['search'] ) ? sanitize_text_field( wp_unslash( $_POST['search'] ) ) : '';
		$args->course_id = null;
		$args->user_id = null;
		$total_count_query = "SELECT * FROM {$wpdb->prefix}academy_grade_book_results WHERE result_for = 'final'";

		$total_count = $wpdb->get_results( $total_count_query );//phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$student_grade = GradeHelper::get_all_or_single_student_grade_details_depend_on_args(
			$args
		);
		$grade_books = $student_grade;
		header( 'x-wp-total:' . count( $total_count ) );
		wp_send_json_success(
			$grade_books
		);
	}

	public function delete_student_grade_result(): void {
		check_ajax_referer( 'academy_nonce', 'security' );

		if ( ! current_user_can( 'manage_academy_instructor' ) ) {
			wp_die();
		}

		// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$gradebook_result_id = isset( $_POST['gradebook_result_id'] ) ? sanitize_text_field( wp_unslash( $_POST['gradebook_result_id'] ) ) : 0;
		if ( GradeHelper::delete_grade_book_result( $gradebook_result_id ) ) {
			wp_send_json_success();
		}

		wp_send_json_error();
	}

	public function delete_student_single_grade_result() {
		check_ajax_referer( 'academy_nonce', 'security' );

		$args = [];
		// type juggling
		// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$args['gradebook_result_id'] = (int) isset( $_POST['gradebook_result_id'] ) ? sanitize_text_field( wp_unslash( $_POST['gradebook_result_id'] ) ) : 0;
		// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$args['user_id'] = isset( $_POST['user_id'] ) ? sanitize_text_field( wp_unslash( $_POST['user_id'] ) ) : 0;
		// phpcs:ignore  WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$args['course_id'] = isset( $_POST['course_id'] ) ? sanitize_text_field( wp_unslash( $_POST['course_id'] ) ) : 0;

		if ( GradeHelper::delete_single_grade_book_result( $args ) ) {
			wp_send_json_success();
		}

		wp_send_json_error();
	}
}
