<?php

declare(strict_types=1);

namespace FormConnector\Features\Analytics;

use FormConnector\Features\License\License;

/**
 * Submission Tracker
 * 
 * Records form submissions to the FormConnector analytics API.
 * GDPR-friendly: only sends homeId, formId, formName, and timestamp.
 * No IP addresses, user agents, or personal data are transmitted.
 */
class SubmissionTracker {

	/**
	 * Singleton instance
	 */
	private static ?SubmissionTracker $instance = null;

	/**
	 * License instance
	 */
	private License $license;

	/**
	 * API endpoint base
	 */
	private string $api_endpoint;

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

	/**
	 * Constructor
	 */
	private function __construct() {
		$this->license = new License();
		$this->api_endpoint = defined('FC_LICENSE_API_ENDPOINT')
			? FC_LICENSE_API_ENDPOINT
			: 'https://app.formconnector.co.uk';
	}

	/**
	 * Track a form submission in the analytics API.
	 *
	 * @param string $form_id   Form identifier (e.g., 'gf-5', 'cf7-123')
	 * @param string $form_name Human-readable form name
	 * @param string $home_id   The CareHQ home/location ID
	 * @return array Result with success status and optional error message
	 */
	public function track(string $form_id, string $form_name, string $home_id): array {
		// Check if analytics tracking is enabled
		$settings = \FormConnector\Core\Settings\Settings::get_instance();
		if (!$settings->get('analytics_tracking_enabled', true)) {
			return [
				'success' => false,
				'error' => 'disabled',
				'message' => 'Analytics tracking is disabled.',
			];
		}

		// Require an active license
		if (!$this->license->is_active()) {
			return [
				'success' => false,
				'error' => 'license_inactive',
				'message' => 'License must be active for analytics tracking.',
			];
		}

		$key = $this->license->get_key();
		if (empty($key)) {
			return [
				'success' => false,
				'error' => 'no_license_key',
				'message' => 'No license key configured.',
			];
		}

		// Validate required fields
		if (empty($home_id)) {
			return [
				'success' => false,
				'error' => 'missing_home_id',
				'message' => 'Home ID is required for analytics tracking.',
			];
		}

		if (empty($form_id)) {
			return [
				'success' => false,
				'error' => 'missing_form_id',
				'message' => 'Form ID is required for analytics tracking.',
			];
		}

		// Build request payload (GDPR-friendly: no PII)
		$payload = [
			'homeId'   => sanitize_text_field($home_id),
			'formId'   => sanitize_text_field($form_id),
			'formName' => sanitize_text_field($form_name),
		];

		// Send to analytics API
		$url = rtrim($this->api_endpoint, '/') . '/api/submissions';

		$response = wp_remote_post($url, [
			'timeout' => 15,
			'headers' => [
				'x-api-key'     => $key,
				'Content-Type'  => 'application/json',
				'Accept'        => 'application/json',
			],
			'body' => wp_json_encode($payload),
		]);

		if (is_wp_error($response)) {
			$error_msg = $response->get_error_message();
			error_log(sprintf('[FormConnector Analytics] Network error: %s', $error_msg));
			return [
				'success' => false,
				'error' => 'network_error',
				'message' => $error_msg,
			];
		}

		$code = wp_remote_retrieve_response_code($response);
		$body = wp_remote_retrieve_body($response);
		$data = json_decode($body, true);

		if ($code !== 200 || empty($data['success'])) {
			$error_msg = $data['message'] ?? 'Unknown error';
			error_log(sprintf(
				'[FormConnector Analytics] API error (HTTP %d): %s',
				$code,
				$error_msg
			));
			return [
				'success' => false,
				'error' => $data['error'] ?? 'api_error',
				'message' => $error_msg,
			];
		}

		return [
			'success' => true,
			'message' => 'Submission recorded.',
			'data' => $data['data'] ?? null,
		];
	}
}
