<?php
/**
 * Writes events into the wmk_events table.
 *
 * @package SuiteMkt3k
 */

namespace SuiteMkt3k\Modules\Statistics;

use SuiteMkt3k\Installer;
use SuiteMkt3k\Security\Rate_Limiter;
use SuiteMkt3k\Utils\Sanitizer;

defined( 'ABSPATH' ) || exit;
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching

final class Stats_Collector {

	public static function register(): void {}

	public static function record( array $args ): void {
		global $wpdb;
		$payload = array(
			'event_type'    => Sanitizer::slug( $args['event_type'] ?? 'impression', 30 ),
			'entity_type'   => Sanitizer::slug( $args['entity_type'] ?? 'misc', 30 ),
			'entity_id'     => isset( $args['entity_id'] ) ? Sanitizer::int( $args['entity_id'], 0 ) : null,
			'subscriber_id' => isset( $args['subscriber_id'] ) ? Sanitizer::int( $args['subscriber_id'], 0 ) : null,
			'visitor_hash'  => isset( $args['visitor_hash'] ) ? substr( (string) $args['visitor_hash'], 0, 64 ) : Rate_Limiter::visitor_id(),
			'meta_json'     => isset( $args['meta'] ) ? wp_json_encode( $args['meta'] ) : null,
		);
		$wpdb->insert( Installer::table( 'events' ), $payload );
	}
}
