<?php
namespace AcademyProEnrollment\Admin;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
use Academy\Classes\AbstractAjaxHandler;
use Academy\Classes\Sanitizer;

class Ajax extends AbstractAjaxHandler {
	protected $namespace = 'academy_pro_enrollment/admin';

	public function __construct() {
		$this->actions = array(
			'get_users' => array(
				'callback' => array( $this, 'get_users' ),
				'capability' => 'manage_options',
			),
			'get_courses' => array(
				'callback' => array( $this, 'get_courses' ),
				'capability' => 'manage_options',
			),
			'do_enrollment' => array(
				'callback' => array( $this, 'do_enrollment' ),
				'capability' => 'manage_options',
			),
			'cancel_enrollment' => array(
				'callback' => array( $this, 'cancel_enrollment' ),
				'capability' => 'manage_options',
			),
		);
	}

	public function get_users( $payload_data ) {
		$payload = Sanitizer::sanitize_payload([
			'keyword' => 'string',
		], $payload_data );

		$keyword = isset( $payload['keyword'] ) ? $payload['keyword'] : '';

		$args = array(
			'number' => 10,
			'fields' => array( 'ID', 'user_login', 'user_email', 'user_nicename', 'display_name' )
		);

		$all_users = get_users( $args );

		if ( $keyword ) {
			$all_users = \Academy\Helper::get_search_students( $keyword );
		}

		$prepared_response = [];
		if ( count( $all_users ) ) {
			foreach ( $all_users as $user ) {
				$prepared_response[] = array(
					'label' => $user->display_name . ' (' . $user->ID . ' - ' . $user->user_email . ')',
					'value' => (int) $user->ID
				);
			}
		}
		wp_send_json_success( $prepared_response );
	}

	public function get_courses( $payload_data ) {
		$payload = Sanitizer::sanitize_payload([
			'keyword' => 'string',
		], $payload_data );

		$keyword = isset( $payload['keyword'] ) ? $payload['keyword'] : '';

		$args = array(
			'post_status' => array( 'publish', 'private' ),
			'post_type' => 'academy_courses',
			'numberposts' => 10,
		);

		$all_courses = get_posts( $args );

		if ( $keyword ) {
			$all_courses = \Academy\Helper::get_search_courses( $keyword );
		}

		$prepared_response = [];
		if ( count( $all_courses ) ) {
			foreach ( $all_courses as $course ) {
				$prepared_response[] = array(
					'label' => $course->post_title,
					'value' => (int) $course->ID
				);
			}
		}
		wp_send_json_success( $prepared_response );
	}

	public static function do_enrollment( $payload_data ) {
		$payload = Sanitizer::sanitize_payload([
			'course_id' => 'string',
			'student_id' => 'string',
		], $payload_data );

		$course_id = isset( $payload['course_id'] ) ? $payload['course_id'] : [];
		$student_id = isset( $payload['student_id'] ) ? $payload['student_id'] : [];
		$course_ids = explode( ',', $course_id );
		$student_ids = explode( ',', $student_id );
		if ( empty( $course_ids ) || empty( $student_ids ) ) {
			wp_send_json_error( __( 'Course ID and Student ID is Required', 'academy-pro' ) );
		}
		$log = [];
		foreach ( $course_ids as $course_id ) {
			foreach ( $student_ids as $student_id ) {
				$student_name = get_userdata( $student_id )->display_name;
				$enrolled    = \Academy\Helper::is_enrolled( $course_id, $student_id, 'any' );
				if ( $enrolled ) {
					if ( 'completed' !== $enrolled->enrolled_status ) {
						$is_enrolled = \Academy\Helper::update_enrollment_status( $course_id, $enrolled->ID, $student_id );
						if ( $is_enrolled ) {
							// translators: %s is the student name
							$log[] = sprintf( __( 'Enrollment successful for %s.', 'academy-pro' ), $student_name );
						} else {
							$log[] = sprintf(
								// translators: %1$s is enrolled status %2$s is student name
								__( 'Enroll status is %1$s for %2$s.', 'academy-pro' ),
								$enrolled->enrolled_status,
								$student_name
							);
						}
					} else {
						// translators: %s is the student name
						$log[] = sprintf( __( 'Already Enrolled! %s.', 'academy-pro' ), $student_name );
					}
					continue;
				}

				$is_enrolled = \Academy\Helper::do_enroll( $course_id, $student_id );
				if ( $is_enrolled ) {
					// translators: %s is the student name
					$log[] = sprintf( __( 'Enrollment successful for %s.', 'academy-pro' ), $student_name );
				} else {
					// translators: %s is the student name
					$log[] = sprintf( __( 'Enrollment failed for %s.', 'academy-pro' ), $student_name );
				}
			}//end foreach
		}//end foreach
		wp_send_json_success( $log );
	}

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

		$course_id = isset( $payload['course_id'] ) ? $payload['course_id'] : 0;
		$student_id = isset( $payload['student_id'] ) ? $payload['student_id'] : 0;

		if ( ! $course_id || ! $student_id ) {
			wp_send_json_error( __( 'Course ID and Student ID is Required', 'academy-pro' ) );
		}

		$cancel_enroll_ids = \AcademyProEnrollment\Helper::cancel_enroll( $course_id, $student_id );
		if ( count( $cancel_enroll_ids ) ) {
			// reset student saved topics
			delete_user_meta( $student_id, 'academy_course_' . $course_id . '_completed_topics' );
			wp_send_json_success( __( 'Successfully Remove Enrolled!', 'academy-pro' ) );
		}

		wp_send_json_error( __( 'Failed, something went wrong!', 'academy-pro' ) );
	}
}
