<?php
/**
 * Scheduled data-retention purge (PRIV-03 / PRIV-06).
 *
 * A daily WP-Cron event (wrenchpress_retention_purge) invokes run(). The purge
 * is driven by two shop-configurable windows stored in the wrenchpress_settings
 * option with conservative defaults (unpromoted leads 180 days, submitter IP 30
 * days). It deletes unpromoted visit-request leads past the lead window, strips
 * the submitter IP and user-agent from older leads past the IP window, and
 * removes expired portal-session rows on their own expiry window.
 *
 * The purge is idempotent: it uses absolute date thresholds, so a missed or a
 * duplicated cron run is harmless (a second run in the same window changes no
 * further rows). It NEVER touches customers or work orders; only leads and
 * expired customer-session rows are ever mutated or deleted here.
 *
 * @package WrenchPress
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class WrenchPress_Retention
 */
class WrenchPress_Retention {

	/**
	 * Run the retention purge. Wired to the daily wrenchpress_retention_purge
	 * cron event in wrenchpress.php.
	 *
	 * Reads the two retention windows from Settings, computes absolute cutoff
	 * datetimes (now minus N days, in the site timezone so they line up with the
	 * created_at values stored via current_time( 'mysql' )), and:
	 *
	 *  - deletes unpromoted leads created before the lead cutoff;
	 *  - strips submit_ip/submit_ua from leads created before the IP cutoff;
	 *  - purges expired customer-session rows (their own expiry window), which
	 *    also clears the sign-in ip/ua fingerprint carried on those rows
	 *    (closes the 08-01 T-08-01-03 accumulation risk).
	 *
	 * A window of 0 turns that particular cleanup off, so a misconfigured window
	 * can never immediately wipe every lead. Customers and work orders are never
	 * touched.
	 *
	 * @return void
	 */
	public static function run() {
		$settings  = WrenchPress_Settings_Page::get();
		$lead_days = absint( $settings['retention_lead_days'] );
		$ip_days   = absint( $settings['retention_ip_days'] );

		$now = current_datetime();

		if ( $lead_days > 0 ) {
			$lead_cutoff = $now->modify( '-' . $lead_days . ' days' )->format( 'Y-m-d H:i:s' );
			WrenchPress_Leads_Repository::purge_unpromoted_before( $lead_cutoff );
		}

		if ( $ip_days > 0 ) {
			$ip_cutoff = $now->modify( '-' . $ip_days . ' days' )->format( 'Y-m-d H:i:s' );
			WrenchPress_Leads_Repository::strip_ip_before( $ip_cutoff );
		}

		WrenchPress_Customer_Sessions_Repository::purge_expired();
	}
}
