<?php
/**
 * Retention_Cron — daily purge of velocity_events older than the retention
 * window. Default 48h, configurable 24–168h via the admin Settings tab.
 *
 * @package TrustLens
 * @since   1.2.2
 */

defined( 'ABSPATH' ) || exit;

class TrustLens_Card_Testing_Retention_Cron {

	public const HOOK = 'trustlens/card_testing/retention_cleanup';

	public function register_hooks(): void {
		add_action( self::HOOK, array( $this, 'run' ) );
		if ( ! wp_next_scheduled( self::HOOK ) ) {
			wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::HOOK );
		}
	}

	public function run(): void {
		global $wpdb;
		$hours = max( 24, min( 168, (int) get_option( 'trustlens_card_testing_retention_hours', 48 ) ) );

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Scheduled retention cleanup of a custom table; table name from $wpdb->prefix.
		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM {$wpdb->prefix}trustlens_velocity_events WHERE created_at < DATE_SUB(UTC_TIMESTAMP(), INTERVAL %d HOUR)",
				$hours
			)
		);

		// Sweep expired card-testing target options. Unlike transients they don't
		// self-expire, so without this the wstl_ct_tgt_* rows would accumulate after an
		// attack subsides. Correctness never depends on it — expiry is enforced on read.
		if ( class_exists( 'TrustLens_Lockdown_State' ) ) {
			( new TrustLens_Lockdown_State() )->prune_expired_targets();
		}
	}
}
