<?php
/**
 * Data Synchronizer.
 * To keep everything clean & managed.
 *
 * @package HBFWC\Utils
 */

namespace HBFWC\Utils;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use function HBFWC\HBF_WC;

/**
 * Class: Data_Cleaner.
 */
class Data_Cleaner {
	/**
	 * Hook in methods.
	 */
	public static function run() {
		add_action( 'wp_scheduled_delete', array( __CLASS__, 'clear_past_data' ), 9 );
	}

	/**
	 * Clear past data that dont needed anymore.
	 */
	public static function clear_past_data() {
		self::clear_default_rate_prices();
		self::clear_past_availability_data();
		do_action( 'hbfwc_inner_action_data_cleaner' );
	}

	/**
	 * Clear default rate pricing for past dates.
	 */
	private static function clear_default_rate_prices() {
		$args     = array(
			'type'  => 'accommodation',
			'limit' => -1,
		);
		$products = \wc_get_products( $args );

		if ( $products ) {
			foreach ( $products as $product ) {
				$prices = $product->get_meta( '_default_rate_prices' );
				if ( ! is_array( $prices ) ) {
					continue;
				}

				foreach ( $prices as $rate_date => $price ) {
					if ( $rate_date < wp_date( 'Ymd' ) ) {
						unset( $prices[ $rate_date ] );
					}
				}

				if ( empty( $prices ) ) {
					delete_post_meta( $product->get_id(), '_default_rate_prices' );
				} else {
					update_post_meta( $product->get_id(), '_default_rate_prices', $prices );
				}
			}
		}
	}

	/**
	 * Clear availability data for past dates.
	 */
	private static function clear_past_availability_data() {
		HBF_WC()->db->delete_entries_before_today();
	}
}

Data_Cleaner::run();
