<?php

namespace MDCE;

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

class Scheduler {

	private const CRON_HOOK = 'mdce_expire_post';

	public function register(): void {
		add_action( 'mdce_expiration_saved',   [ $this, 'schedule' ], 10, 3 );
		add_action( 'mdce_expiration_cleared', [ $this, 'unschedule' ] );
		add_action( 'before_delete_post',     [ $this, 'unschedule' ] );
		add_action( 'trashed_post',           [ $this, 'unschedule' ] );
	}

	public function schedule( int $post_id, int $timestamp, string $action ): void {
		$scheduled = wp_next_scheduled( self::CRON_HOOK, [ $post_id ] );
		if ( $scheduled === $timestamp ) {
			return;
		}

		$this->unschedule( $post_id );
		wp_schedule_single_event( $timestamp, self::CRON_HOOK, [ $post_id ] );
	}

	public function unschedule( int $post_id ): void {
		wp_clear_scheduled_hook( self::CRON_HOOK, [ $post_id ] );
	}

	public static function get_hook(): string {
		return self::CRON_HOOK;
	}
}
