<?php

namespace SugarCalendarBookings\Appointments\Tasks;

use SugarCalendarBookings\Appointments\AppointmentModel;
use SugarCalendarBookings\Support\Helpers\Date;
use SugarCalendarBookings\Support\Tasks\AbstractTask;

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

/**
 * Class RemoveDraftAppointmentsTask.
 *
 * @since 1.0.0
 */
class DraftAppointmentsCleanupTask extends AbstractTask {

	/**
	 * Action name for this task.
	 *
	 * @since 1.0.0
	 */
	const ACTION = 'sugar_calendar_bookings_draft_appointments_cleanup';

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

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

	/**
	 * Initialize the task.
	 *
	 * @since 1.0.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.
		$this->recurring( strtotime( 'now' ), DAY_IN_SECONDS )
			->unique()
			->register();
	}

	/**
	 * Process task.
	 *
	 * @since 1.0.0
	 */
	public function process() {

		$last_week = Date::create( '-1 week' )->format( Date::DB_DATETIME_FORMAT );

		AppointmentModel::query()
			->where( 'status', '=', AppointmentModel::STATUS_DRAFT, '%s' )
			->where( 'created_at', '<=', $last_week, '%s' )
			->delete();
	}

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

		$this->remove_completed( 10 );
	}
}
