<?php

namespace SugarCalendarBookings\Availability\Tasks;

use SugarCalendarBookings\Options;
use SugarCalendarBookings\Plugin;
use SugarCalendarBookings\Support\Helpers\Date;
use SugarCalendarBookings\Support\Tasks\AbstractTask;

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

/**
 * Date Overrides Cleanup Task.
 *
 * Scheduled task to clean up old date overrides.
 *
 * @since 1.1.0
 */
class DateOverridesCleanupTask extends AbstractTask {

	/**
	 * Action name for this task.
	 *
	 * @since 1.1.0
	 */
	const ACTION = 'sugar_calendar_bookings_date_overrides_cleanup';

	/**
	 * Class constructor.
	 *
	 * @since 1.1.0
	 */
	public function __construct() {

		parent::__construct( self::ACTION );
	}

	/**
	 * Initialize the task.
	 *
	 * @since 1.1.0
	 */
	public function init() { // phpcs:ignore WPForms.PHP.HooksMethod.InvalidPlaceForAddingHooks

		add_action( self::ACTION, [ $this, 'process' ] );
		add_action( 'action_scheduler_after_process_queue', [ $this, 'cleanup' ] );

		// Schedule the task to run daily.
		$this->recurring( strtotime( 'now' ), DAY_IN_SECONDS )
				->unique()
				->register();
	}

	/**
	 * Process task.
	 *
	 * Removes date overrides where the end_date is before today.
	 *
	 * @since 1.1.0
	 */
	public function process() {

		$options          = Plugin::get( Options::class );
		$working_schedule = $options->get( 'availability.working_schedule' );
		$overrides        = $working_schedule['overrides'] ?? [];

		if ( empty( $overrides ) ) {
			return;
		}

		// Get today's date in Y-m-d format.
		$today = Date::create( 'now' )->format( 'Y-m-d' );

		// Filter out old overrides (keep only today and future dates).
		$filtered_overrides = array_filter(
			$overrides,
			function ( $override ) use ( $today ) {

				$end_date = $override['end_date'] ?? '';

				// Keep the override if end_date is today or in the future.
				return ! empty( $end_date ) && $end_date >= $today;
			}
		);

		// Re-index array to avoid gaps in keys.
		$filtered_overrides = array_values( $filtered_overrides );

		// Only update if something changed.
		if ( count( $filtered_overrides ) !== count( $overrides ) ) {
			// Update only the overrides key while preserving other working_schedule fields.
			$working_schedule['overrides'] = $filtered_overrides;

			$options->update(
				[
					'availability' => [
						'working_schedule' => $working_schedule,
					],
				]
			);
		}
	}

	/**
	 * Cleanup completed tasks.
	 *
	 * @since 1.1.0
	 */
	public function cleanup() {

		$this->remove_completed( 10 );
	}
}
