<?php

defined( 'ABSPATH' ) || exit;

class ZACLS_Auto_Cleanup {

	public static function init() {
		add_action( 'zacls_daily_cleanup', array( __CLASS__, 'run_cleanup' ) );
		add_action( 'admin_init', array( __CLASS__, 'schedule' ) );

		$frequency = get_option( 'zacls_cleanup_frequency', 'daily' );
		if ( 'disabled' !== $frequency ) {
			if ( ! wp_next_scheduled( 'zacls_daily_cleanup' ) ) {
				self::schedule();
			}
		}
	}

	public static function schedule() {
		$frequency = get_option( 'zacls_cleanup_frequency', 'daily' );
		$map       = array(
			'daily'   => 'daily',
			'weekly'  => 'weekly',
			'monthly' => 'monthly',
		);
		$schedule  = isset( $map[ $frequency ] ) ? $map[ $frequency ] : 'daily';

		if ( 'disabled' === $frequency ) {
			$timestamp = wp_next_scheduled( 'zacls_daily_cleanup' );
			if ( $timestamp ) {
				wp_unschedule_event( $timestamp, 'zacls_daily_cleanup' );
			}
			return;
		}

		if ( ! wp_next_scheduled( 'zacls_daily_cleanup' ) ) {
			wp_schedule_event( time(), $schedule, 'zacls_daily_cleanup' );
		}
	}

	public static function run_cleanup() {
		$retention_days = absint( get_option( 'zacls_cleanup_retention_days', 90 ) );
		if ( $retention_days < 1 ) {
			$retention_days = 90;
		}

		$retention_days = max( 7, min( $retention_days, 365 ) );
		ZACLS_Performance::cleanup_old_data( $retention_days );
	}
}
