<?php
namespace StoreEngine\Classes;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class LogCleanup {

	/**
	 * main cleanup logic
	 */
	public static function execute_cleanup() {
		global $wpdb;
		$table = $wpdb->prefix . 'storeengine_logs';

		// admin setting
		$settings = get_option( 'storeengine_log_settings',[
			'retention_days'   => 30, 
			'cleanup_statuses' => [ 'success' ] 
		] );

		$days     = (int) ( $settings['retention_days'] ?? 30 );
		$statuses = $settings['cleanup_statuses'] ?? [ 'success' ];

		if ( $days <= 0 || empty( $statuses ) || ! is_array( $statuses ) ) {
			return;
		}

		//  date calculation
		$threshold_timestamp = current_time( 'timestamp' ) - ( $days * DAY_IN_SECONDS );
		$threshold_date      = date( 'Y-m-d H:i:s', $threshold_timestamp );

		//  SQL Query Prepare 
		$placeholders = implode( ',', array_fill( 0, count( $statuses ), '%s' ) );
		
		$query = $wpdb->prepare(
			"DELETE FROM {$table} WHERE date < %s AND status IN ($placeholders)",
			array_merge( [ $threshold_date ], $statuses )
		);

		// delete for db
		$wpdb->query( $query );
	}
}