<?php
/**
 * A class to clean the Fast Events old messages, old logs, and optional expired, cancelled, and failed orders
 *
 * @since 3.0.0
 */

declare( strict_types=1 );
namespace FeData\FastEvents\Hooks\Actions;

defined( 'ABSPATH' ) || exit;

use FeData\FastEvents\Helpers\OrderHelper;
use FeData\FastEvents\Storage\PluginSettings;
use FeData\FastEvents\Utilities\TimeUtil;

/**
 * A class to clean the Fast Events old messages, old logs, and optional expired, cancelled, and failed orders
 */
final class CleanCacheAction {

	/**
	 * CleanCacheAction constructor.
	 *
	 * @since 3.0.0
	 *
	 * @param PluginSettings $settings Plugin settings.
	 */
	public function __construct( private readonly PluginSettings $settings ) {
	}

	/**
	 * Clean free format saved emails from the option table if older than 7 days.
	 * Log rows older than 30 days will be deleted
	 *
	 * @since 1.0
	 * @since 1.9 - Remove rows from the log table older than 30 days
	 * @since 2.0.3 - a Clean free format saved emails from the option table if older than 7 days
	 * @since 2.5.0 - Clean log table depending on the setting: 'log_retention_days'.
	 *              - Optional delete 'expired', 'failed' and 'cancelled' orders.
	 */
	public function clean_cache(): void {
		global $wpdb;
		global $fevt_container;

		// Clean free format saved emails from the option table.
		$messages = $wpdb->get_results( "SELECT * FROM $wpdb->options WHERE option_name LIKE 'fast_events_email_msg_%'" );
		if ( ! empty( $messages ) ) {
			foreach ( $messages as $message ) {
				$info = @unserialize( $message->option_value ); //phpcs:ignore

				// If the date is not set or anything older than 7 days is deleted.
				if ( ! isset( $info['date'] ) || ( TimeUtil::local_time() - strtotime( $info['date'] ) ) > WEEK_IN_SECONDS ) {
					delete_option( $message->option_name );
				}
			}
		}

		// Clean the log table.
		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM {$wpdb->prefix}fe_event_log WHERE created_at < NOW() - INTERVAL %d DAY",
				$this->settings->log_retention_days()
			)
		);

		// Clean expired, failed and cancelled orders?
		if ( $this->settings->misc_orders_cleanups() ) {
			$orders = $wpdb->get_results( "SELECT id FROM {$wpdb->prefix}fe_event_orders WHERE payment_status IN ('expired', 'failed', 'canceled')" );
			if ( ! empty( $orders ) ) {
				$order_helper = $fevt_container->get( OrderHelper::class );
				foreach ( $orders as $order ) {
					$order_helper->order_delete( (int) $order->id );
				}
			}
		}
	}
}
