<?php
/**
 * Search Course Ajax handler.
 *
 * @since 2.6.8
 *
 * @package Masteriyo\Addons\EDDIntegration
 */

namespace Masteriyo\Addons\EDDIntegration;

defined( 'ABSPATH' ) || exit;


use Masteriyo\Abstracts\AjaxHandler;
use Masteriyo\PostType\PostType;
use Masteriyo\Taxonomy\Taxonomy;

/**
 * List course ajax handler.
 */
class SearchCourseAjaxHandler extends AjaxHandler {

	/**
	 * ListCourse ajax action.
	 *
	 * @since 2.6.8
	 * @var string
	 */
	public $action = 'edd_mto_course_search';

	/**
	 * Register ajax handler.
	 *
	 * @since 2.6.8
	 */
	public function register() {
		add_action( "wp_ajax_{$this->action}", array( $this, 'search_courses' ) );
	}

	/**
	 * Search courses.
	 *
	 * @since 2.6.8
	 */
	public function search_courses() {
		$search = isset( $_GET['s'] ) ? sanitize_text_field( $_GET['s'] ) : '';

		$query = new \WP_Query(
			array(
				'post_type'      => PostType::COURSE,
				'posts_per_page' => 10,
				's'              => $search,
				'tax_query'      => array(
					array(
						'taxonomy' => Taxonomy::COURSE_VISIBILITY,
						'field'    => 'slug',
						'terms'    => 'paid',
					),
				),
			)
		);

		$courses = array_map(
			function( $post ) {
				return array(
					'id'   => $post->ID,
					'name' => $post->post_title,
				);
			},
			$query->posts
		);

		wp_send_json( $courses );
	}
}
