<?php

namespace SugarCalendarBookings\Support\Ajax;

use SugarCalendarBookings\Plugin;
use SugarCalendarBookings\Support\Bootable;

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

/**
 * AJAX request handler.
 *
 * @since 1.0.0
 */
class RequestHandler implements Bootable {

	/**
	 * Hooks.
	 *
	 * @since 1.0.0
	 */
	public function hooks() {

		add_action( 'wp_ajax_sugar_calendar_bookings', [ $this, 'handle_request' ] );
		add_action( 'wp_ajax_nopriv_sugar_calendar_bookings', [ $this, 'handle_request' ] );
	}

	/**
	 * Handle the request.
	 *
	 * @since 1.0.0
	 */
	public function handle_request() { // phpcs:ignore Generic.Metrics.CyclomaticComplexity.TooHigh

		// Bail if request can't be trusted.
		if ( ! check_ajax_referer( 'sugar_calendar_bookings', false, false ) ) {
			wp_send_json_error();
		}

		$task = null;

		if ( isset( $_GET['task'] ) ) {
			$task = wp_unslash( sanitize_key( $_GET['task'] ) );
		}

		// Bail if no task is defined.
		if ( empty( $task ) ) {
			wp_send_json_error();
		}

		$context = isset( $_GET['context'] ) ? wp_unslash( sanitize_key( $_GET['context'] ) ) : 'admin';

		$routes = Plugin::get( RouteRegistry::class );

		foreach ( $routes->get_routes() as $route ) {
			if ( $route->get_context() === $context && $route->get_task() === $task ) {
				$route->handle();
				break;
			}
		}

		// If no route is found, send an error.
		wp_send_json_error( esc_html__( 'Invalid task.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
	}
}
