<?php

declare(strict_types=1);

namespace FormConnector\API\Endpoints;

use FormConnector\Features\Analytics\SubmissionTracker;

/**
 * Analytics REST API endpoints.
 * 
 * Provides admin endpoints for testing analytics tracking.
 */
class AnalyticsEndpoints {

	private const NAMESPACE = 'fc/v1';

	/**
	 * Register analytics routes.
	 */
	public static function register(): void {
		// Test analytics tracking with a sample submission
		register_rest_route(self::NAMESPACE, '/analytics/test', [
			'methods'             => \WP_REST_Server::CREATABLE,
			'callback'            => [self::class, 'test_tracking'],
			'permission_callback' => [self::class, 'permission_check'],
		]);
	}

	/**
	 * Permission check for admin-only endpoints.
	 */
	public static function permission_check(): bool {
		return current_user_can('manage_options');
	}

	/**
	 * Test analytics tracking by sending a test submission.
	 */
	public static function test_tracking(\WP_REST_Request $request): \WP_REST_Response {
		$params = $request->get_json_params();

		$home_id   = sanitize_text_field($params['homeId'] ?? '');
		$form_id   = sanitize_text_field($params['formId'] ?? 'test-form');
		$form_name = sanitize_text_field($params['formName'] ?? 'Test Form');

		if (empty($home_id)) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => __('homeId is required.', 'form-connector'),
			], 400);
		}

		$tracker = SubmissionTracker::get_instance();
		$result  = $tracker->track($form_id, $form_name, $home_id);

		$status_code = $result['success'] ? 200 : 400;

		return new \WP_REST_Response([
			'success' => $result['success'],
			'message' => $result['message'] ?? '',
			'data'    => $result['data'] ?? null,
		], $status_code);
	}
}
