<?php

namespace SugarCalendarBookings\Support\Ajax;

use SugarCalendarBookings\Plugin;

/**
 * AJAX route.
 *
 * @since 1.0.0
 */
class Route {

	/**
	 * The task.
	 *
	 * @since 1.0.0
	 *
	 * @var string
	 */
	private $task;

	/**
	 * The callback.
	 *
	 * @since 1.0.0
	 *
	 * @var callable
	 */
	private $callback;

	/**
	 * The context.
	 *
	 * @since 1.0.0
	 *
	 * @var string
	 */
	private $context = 'admin';

	/**
	 * Constructor.
	 *
	 * @since 1.0.0
	 *
	 * @param string                      $task     The task.
	 * @param array{0: string, 1: string} $callback The callback.
	 */
	public function __construct( $task, $callback ) {

		$this->task     = $task;
		$this->callback = $callback;
	}

	/**
	 * Get the task.
	 *
	 * @since 1.0.0
	 *
	 * @return string
	 */
	public function get_task() {

		return $this->task;
	}

	/**
	 * Get the context.
	 *
	 * @since 1.0.0
	 *
	 * @return string
	 */
	public function get_context() {

		return $this->context;
	}

	/**
	 * Set the route to public.
	 *
	 * @since 1.0.0
	 *
	 * @return $this
	 */
	public function public() {

		$this->context = 'public';

		return $this;
	}

	/**
	 * Set the route to admin.
	 *
	 * @since 1.0.0
	 *
	 * @return $this
	 */
	public function admin() {

		$this->context = 'admin';

		return $this;
	}

	/**
	 * Check if the route is public.
	 *
	 * @since 1.0.0
	 *
	 * @return bool
	 */
	public function is_public() {

		return $this->context === 'public';
	}

	/**
	 * Check if the route is admin.
	 *
	 * @since 1.0.0
	 *
	 * @return bool
	 */
	public function is_admin() {

		return $this->context === 'admin';
	}

	/**
	 * Handle the request.
	 *
	 * @since 1.0.0
	 */
	public function handle() {

		if ( $this->is_admin() && ! is_user_logged_in() ) {
			wp_send_json_error( esc_html__( 'You are not allowed to access this resource.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		[ $class, $method ] = $this->callback;
		$instance           = Plugin::get( $class );
		$callback           = [ $instance, $method ];

		call_user_func( $callback );
	}
}
