<?php
/**
 * Authenticated REST API consumed by the admin dashboard.
 *
 * @package Defog
 */

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

class Defog_Rest {

	public function __construct() {
		add_action( 'rest_api_init', array( $this, 'register' ) );
	}

	/**
	 * Only logged-in users who manage the site may read analytics.
	 *
	 * @return bool
	 */
	public function can_read() {
		return current_user_can( 'manage_options' );
	}

	/**
	 * Register read routes.
	 */
	public function register() {
		register_rest_route(
			'defog/v1',
			'/stats',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'stats' ),
				'permission_callback' => array( $this, 'can_read' ),
				'args'                => array(
					'range' => array(
						'default'           => '7d',
						'sanitize_callback' => 'sanitize_key',
						'validate_callback' => function ( $v ) {
							return in_array( $v, array( 'today', '7d', '30d' ), true );
						},
					),
				),
			)
		);

		register_rest_route(
			'defog/v1',
			'/realtime',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'realtime' ),
				'permission_callback' => array( $this, 'can_read' ),
			)
		);

		register_rest_route(
			'defog/v1',
			'/page',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'page' ),
				'permission_callback' => array( $this, 'can_read' ),
				'args'                => array(
					'range' => array(
						'default'           => '7d',
						'sanitize_callback' => 'sanitize_key',
						'validate_callback' => function ( $v ) {
							return in_array( $v, array( 'today', '7d', '30d' ), true );
						},
					),
					'path'  => array(
						'required'          => true,
						'sanitize_callback' => 'sanitize_text_field',
					),
				),
			)
		);
	}

	/**
	 * Full dashboard payload for a range.
	 *
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response
	 */
	public function stats( WP_REST_Request $request ) {
		$range = $request->get_param( 'range' );
		$q     = new Defog_Query();

		$data = array(
			'range'     => $range,
			'kpis'      => $q->kpis( $range ),
			'series'    => array(
				'visitors'  => $q->series( $range, 'visitors' ),
				'pageviews' => $q->series( $range, 'pageviews' ),
				'sessions'  => $q->series( $range, 'sessions' ),
			),
			'channels'  => $q->dimension( $range, 'source' ),
			'countries' => $q->dimension( $range, 'country' ),
			'devices'   => $q->dimension( $range, 'device' ),
			'pages'     => $q->dimension( $range, 'page' ),
		);

		$actions = $q->actions( $range );
		if ( null !== $actions ) {
			$data['actions'] = $actions;
		}

		$ecommerce = $q->ecommerce( $range );
		if ( null !== $ecommerce ) {
			$data['ecommerce'] = $ecommerce;
		}

		// Extension point: the Pro add-on rides along here (e.g. adds `insights`).
		$data = apply_filters( 'defog_stats_payload', $data, $range );

		return rest_ensure_response( $data );
	}

	/**
	 * Realtime snapshot.
	 *
	 * @return WP_REST_Response
	 */
	public function realtime() {
		$q = new Defog_Query();
		return rest_ensure_response( $q->realtime() );
	}


	/**
	 * Behavioural detail for a single page.
	 *
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response
	 */
	public function page( WP_REST_Request $request ) {
		$path = (string) $request->get_param( 'path' );
		$path = '/' . ltrim( (string) wp_parse_url( $path, PHP_URL_PATH ), '/' );
		$path = substr( $path, 0, 190 );

		$q = new Defog_Query();
		return rest_ensure_response( $q->page_detail( $request->get_param( 'range' ), $path ) );
	}
}
