<?php
/**
 * Admin REST endpoints.
 *
 * @package Live_Traffic_Analytics
 */

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

/**
 * Exposes analytics data to the admin dashboard.
 */
class WPLTA_Admin_REST {

	/**
	 * Singleton instance.
	 *
	 * @var WPLTA_Admin_REST|null
	 */
	private static $instance = null;

	/**
	 * Get instance.
	 *
	 * @return WPLTA_Admin_REST
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * Register hooks.
	 */
	private function __construct() {
		add_action( 'rest_api_init', array( $this, 'register_routes' ) );
	}

	/**
	 * Register admin routes.
	 *
	 * @return void
	 */
	public function register_routes() {
		register_rest_route(
			'wplta/v1',
			'/admin/dashboard',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_dashboard_data' ),
				'permission_callback' => array( $this, 'validate_admin_request' ),
			)
		);
	}

	/**
	 * Validate admin capabilities and nonce.
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return true|WP_Error
	 */
	public function validate_admin_request( $request ) {
		if ( ! current_user_can( 'manage_options' ) ) {
			return new WP_Error(
				'wplta_forbidden',
				__( 'You are not allowed to view analytics.', 'live-traffic-analytics' ),
				array( 'status' => 403 )
			);
		}

		if ( ! WPLTA_Helpers::verify_rest_nonce( $request ) ) {
			return new WP_Error(
				'wplta_invalid_nonce',
				__( 'Invalid admin nonce.', 'live-traffic-analytics' ),
				array( 'status' => 403 )
			);
		}

		return true;
	}

	/**
	 * Return dashboard payload.
	 *
	 * @return WP_REST_Response
	 */
	public function get_dashboard_data() {
		return rest_ensure_response(
			array(
				'success' => true,
				'data'    => WPLTA_Repository::get_admin_dashboard_payload(),
			)
		);
	}
}
