<?php
/**
 * REST API routes for Cart Recovery Analytics.
 *
 * Handles analytics and stats endpoints for abandoned cart recovery.
 *
 * @package EDD\Pro\CartRecovery\REST\Routes
 * @copyright Copyright (c) 2026, Sandhills Development, LLC
 * @license https://opensource.org/licenses/GPL-3.0 GNU General Public License v3.0
 * @since 3.6.5
 */

namespace EDD\Pro\CartRecovery\REST\Routes;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit; // @codeCoverageIgnore

use EDD\REST\Routes\Route;
use EDD\Pro\CartRecovery\REST\Controllers\Analytics as Controller;

/**
 * Analytics route class.
 *
 * @since 3.6.5
 */
final class Analytics extends Route {

	/**
	 * REST API base.
	 *
	 * @since 3.6.5
	 * @var string
	 */
	const BASE = 'acr/stats';

	/**
	 * Constructor.
	 *
	 * @since 3.6.5
	 */
	public function __construct() {
		$this->controller = new Controller();
	}

	/**
	 * Register REST routes.
	 *
	 * @since 3.6.5
	 */
	public function register(): void {
		register_rest_route(
			self::NAMESPACE,
			'/' . self::$version . '/' . self::BASE,
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( $this->controller, 'get_stats' ),
				'permission_callback' => array( $this->controller, 'can_view_stats' ),
				'args'                => array(
					'start_date' => array(
						'required'          => false,
						'description'       => 'Start date (Y-m-d). Defaults to Last 30 Days.',
						'type'              => 'string',
						'validate_callback' => function ( $param ) {
							if ( null === $param || '' === $param ) {
								return true;
							}
							return is_string( $param ) && (bool) preg_match( '/^\d{4}-\d{2}-\d{2}$/', $param );
						},
						'sanitize_callback' => 'sanitize_text_field',
					),
					'end_date'   => array(
						'required'          => false,
						'description'       => 'End date (Y-m-d). Defaults to today.',
						'type'              => 'string',
						'validate_callback' => function ( $param ) {
							if ( null === $param || '' === $param ) {
								return true;
							}
							return is_string( $param ) && (bool) preg_match( '/^\d{4}-\d{2}-\d{2}$/', $param );
						},
						'sanitize_callback' => 'sanitize_text_field',
					),
				),
			)
		);
	}
}
