<?php
/**
 * Ajax handler for pagination on the public profile.
 *
 * Handles pagination requests for the public profile using Ajax.
 *
 * @since 2.6.8
 *
 * @package Masteriyo\Addons\PublicProfile\AjaxHandlers
 */

namespace Masteriyo\Addons\PublicProfile\AjaxHandlers;

defined( 'ABSPATH' ) || exit;


use Masteriyo\Abstracts\AjaxHandler;
use Masteriyo\Constants;
use Masteriyo\Exceptions\RestException;

/**
 * Class PaginationAjaxHandler
 *
 * @package Masteriyo\Addons\PublicProfile\AjaxHandlers
 */
class PaginationAjaxHandler extends AjaxHandler {

	/**
	 * The Ajax action for pagination.
	 *
	 * @since 2.6.8
	 *
	 * @var string
	 */
	public $action = 'masteriyo_public_profile_pagination';

	/**
	 * Register the pagination Ajax handler.
	 *
	 * @since 2.6.8
	 */
	public function register() {
		add_action( "wp_ajax_nopriv_{$this->action}", array( $this, 'process' ) );
		add_action( "wp_ajax_{$this->action}", array( $this, 'process' ) );
	}

	/**
	 * Process the pagination Ajax request.
	 *
	 * @since 2.6.8
	 *
	 * @throws RestException If there is an error processing the request.
	 *
	 *  @return void Returns no explicit value. Sends JSON response using wp_send_json_success() or wp_send_json_error().
	 */
	public function process() {

		if ( ! isset( $_POST['nonce'] ) ) {
			wp_send_json_error(
				array(
					'message' => __( 'Nonce is required.', 'learning-management-system' ),
				),
				400
			);
			return;
		}

		try {
			if ( ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'masteriyo_public_profile_pagination_nonce' ) ) {
				throw new \Exception( __( 'Invalid nonce. Maybe you should reload the page.', 'learning-management-system' ) );
			}

			if ( ! isset( $_POST['page'] ) && ! isset( $_POST['user_id'] ) && ! isset( $_POST['course_type'] ) ) {
				throw new RestException( 'masteriyo_invalid_action', __( 'Invalid request parameters!', 'learning-management-system' ) );
			}

			$page        = absint( $_POST['page'] );
			$user_id     = absint( $_POST['user_id'] );
			$course_type = sanitize_text_field( $_POST['course_type'] );

			$html = '';

			if ( 'offered' === $course_type ) {
				list( $offered_courses_list, $total_pages, $current_page ) = masteriyo_get_user_courses_with_pagination( $user_id, $page );
				$html = $offered_courses_list;
			} else {
				list( $enrolled_courses, $total_pages, $current_page ) = masteriyo_get_user_enrolled_courses_with_pagination( $user_id, $page );
				if ( count( $enrolled_courses ) ) {
					ob_start();
					require Constants::get( 'MASTERIYO_PUBLIC_PROFILE_ADDON_TEMPLATES' ) . '/partials/enrolled-courses-gridcard.php';
					$html = ob_get_clean();
				}
			}

			$data = array(
				'html'       => $html,
				'pagination' => array(
					'total_pages'  => $total_pages,
					'current_page' => $current_page,
				),
			);

			wp_send_json_success( $data );

		} catch ( \Exception $e ) {
			wp_send_json_error(
				array(
					'message' => $e->getMessage(),
				),
				400
			);
		}
	}
}
