<?php
/**
 * Public built-in form analytics service.
 *
 * @package SubmissionInbox
 */

namespace SUBIN\Forms;

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

/**
 * Accepts anonymous lifecycle signals and records authoritative submits.
 */
class FormAnalyticsService {
	const REST_NAMESPACE = 'submission-inbox/v1';
	const SUBMIT_HOOK    = 'subin_builtin_form_submission_success';

	/** @var FormAnalyticsRepository */
	private $events;

	/** @var FormRepository */
	private $forms;

	/** @var SubmissionRateLimiter */
	private $limiter;

	/**
	 * Constructor.
	 *
	 * @param FormAnalyticsRepository    $events Event repository.
	 * @param FormRepository             $forms Form repository.
	 * @param SubmissionRateLimiter|null $limiter Anonymous event rate limiter.
	 */
	public function __construct( FormAnalyticsRepository $events, FormRepository $forms, ?SubmissionRateLimiter $limiter = null ) {
		$this->events  = $events;
		$this->forms   = $forms;
		$this->limiter = $limiter ?: new SubmissionRateLimiter();
	}

	/**
	 * Register public tracking and authoritative submit hooks.
	 *
	 * @return void
	 */
	public function register() {
		add_action( 'rest_api_init', array( $this, 'register_rest_routes' ) );
		add_action( self::SUBMIT_HOOK, array( $this, 'record_submit' ), 10, 3 );
	}

	/**
	 * Build cache-safe public configuration containing no visitor data.
	 *
	 * @param int $form_id Form id.
	 * @return array{url:string,token:string}
	 */
	public function public_config( $form_id ) {
		$form_id = absint( $form_id );
		return array(
			'url'   => rest_url( self::REST_NAMESPACE . '/forms/' . $form_id . '/analytics' ),
			'token' => $this->token( $form_id ),
		);
	}

	/**
	 * Register the anonymous lifecycle event endpoint.
	 *
	 * @return void
	 */
	public function register_rest_routes() {
		register_rest_route(
			self::REST_NAMESPACE,
			'/forms/(?P<form_id>\d+)/analytics',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'handle_event' ),
				'permission_callback' => '__return_true',
				'args'                => array(
					'form_id' => array(
						'required'          => true,
						'sanitize_callback' => 'absint',
					),
				),
			)
		);
	}

	/**
	 * Store one browser lifecycle event without cookies or request metadata.
	 *
	 * @param \WP_REST_Request $request Request.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public function handle_event( \WP_REST_Request $request ) {
		$form_id = absint( $request['form_id'] ?? 0 );
		$payload = $request->get_json_params();
		if ( ! is_array( $payload ) ) {
			$payload = $request->get_body_params();
		}
		$payload    = is_array( $payload ) ? $payload : array();
		$event_type = sanitize_key( (string) ( $payload['event_type'] ?? '' ) );
		$event_id   = sanitize_text_field( (string) ( $payload['event_id'] ?? '' ) );
		$token      = sanitize_text_field( (string) ( $payload['token'] ?? '' ) );

		if ( ! in_array( $event_type, array( FormAnalyticsRepository::EVENT_VIEW, FormAnalyticsRepository::EVENT_START, FormAnalyticsRepository::EVENT_INTERACTION ), true ) ) {
			return new \WP_Error( 'subin_form_analytics_event_not_allowed', __( 'This form analytics event is not allowed.', 'submission-inbox' ), array( 'status' => 400 ) );
		}
		if ( ! $this->valid_token( $form_id, $token ) ) {
			return new \WP_Error( 'subin_form_analytics_invalid_token', __( 'The form analytics token is invalid.', 'submission-inbox' ), array( 'status' => 403 ) );
		}

		$form = $this->forms->get( $form_id );
		if ( ! $form || FormRepository::STATUS_ACTIVE !== sanitize_key( (string) ( $form['status'] ?? '' ) ) ) {
			return new \WP_Error( 'subin_form_analytics_form_unavailable', __( 'This form is not available.', 'submission-inbox' ), array( 'status' => 404 ) );
		}

		$allowed = $this->limiter->consume_analytics( $form_id );
		if ( is_wp_error( $allowed ) ) {
			$data = $allowed->get_error_data();
			$data = is_array( $data ) ? $data : array();
			$data['status'] = 429;

			return new \WP_Error( $allowed->get_error_code(), $allowed->get_error_message(), $data );
		}

		$recorded = $this->events->record_event( $form_id, $event_type, $event_id );
		if ( is_wp_error( $recorded ) ) {
			return new \WP_Error(
				'subin_form_analytics_storage_unavailable',
				__( 'Form analytics is temporarily unavailable.', 'submission-inbox' ),
				array( 'status' => 503 )
			);
		}

		$response = new \WP_REST_Response( array( 'recorded' => (bool) $recorded ), 202 );
		$response->header( 'Cache-Control', 'no-store, no-cache, must-revalidate' );
		return $response;
	}

	/**
	 * Record a successful submit idempotently using its durable identity.
	 *
	 * @param int    $form_id Form id.
	 * @param string $submission_id Client submission id.
	 * @param int    $receipt_id Durable receipt id fallback.
	 * @return void
	 */
	public function record_submit( $form_id, $submission_id, $receipt_id = 0 ) {
		$submission_id = trim( sanitize_text_field( (string) $submission_id ) );
		if ( strlen( $submission_id ) < 16 || strlen( $submission_id ) > 128 || 1 !== preg_match( '/^[A-Za-z0-9._:-]+$/', $submission_id ) ) {
			$receipt_id = absint( $receipt_id );
			if ( $receipt_id <= 0 ) {
				return;
			}
			$submission_id = 'receipt:' . hash( 'sha256', (string) $receipt_id );
		}

		// Analytics must never affect submission acceptance, so storage errors are intentionally ignored here.
		$this->events->record_event( absint( $form_id ), FormAnalyticsRepository::EVENT_SUBMIT, $submission_id );
	}

	/**
	 * Return 7/30 day funnels for a form portfolio.
	 *
	 * @param array<int,int|string> $form_ids Form ids.
	 * @param string                $as_of Optional inclusive date.
	 * @return array<int,array<string,array<string,int|float>>>
	 */
	public function batch_aggregates( array $form_ids, $as_of = '' ) {
		return $this->events->get_funnel_aggregates( $form_ids, $as_of );
	}

	/**
	 * Create a deterministic token that remains valid in cached form markup.
	 *
	 * @param int $form_id Form id.
	 * @return string
	 */
	private function token( $form_id ) {
		return hash_hmac( 'sha256', 'form-analytics-token:v1|' . absint( $form_id ), wp_salt( 'nonce' ) );
	}

	/**
	 * Verify a form-bound public token.
	 *
	 * @param int    $form_id Form id.
	 * @param string $token Token.
	 * @return bool
	 */
	private function valid_token( $form_id, $token ) {
		$token = strtolower( trim( (string) $token ) );
		return absint( $form_id ) > 0 && 64 === strlen( $token ) && hash_equals( $this->token( $form_id ), $token );
	}
}
