<?php

namespace MDCE;

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

class ExpirationProcessor {

	public function register(): void {
		add_action( Scheduler::get_hook(), [ $this, 'process' ] );
	}

	public function process( int $post_id ): void {
		$post = get_post( $post_id );
		if ( ! $post ) {
			return;
		}

		// Only published posts are expired by default; PRO extends this via `mdce_expirable_statuses`.
		$expirable = (array) apply_filters( 'mdce_expirable_statuses', [ 'publish' ] );
		if ( ! in_array( $post->post_status, $expirable, true ) ) {
			return;
		}

		$timestamp = (int) get_post_meta( $post_id, '_mdce_expiration_date', true );
		$action    = (string) get_post_meta( $post_id, '_mdce_expiration_action', true );

		if ( ! $timestamp || ! $action ) {
			return;
		}

		if ( ! (bool) apply_filters( 'mdce_before_expire', true, $post_id, $action ) ) {
			return;
		}

		$this->execute( $post, $action );

		delete_post_meta( $post_id, '_mdce_expiration_date' );
		delete_post_meta( $post_id, '_mdce_expiration_action' );
		delete_post_meta( $post_id, '_mdce_expiry_category_ids' );
		delete_post_meta( $post_id, '_mdce_expiry_new_title' );

		// Fires after expiry so PRO notifiers, logs, etc. can react.
		do_action( 'mdce_post_expired', $post_id, $action );
	}

	private function execute( \WP_Post $post, string $action ): void {
		switch ( $action ) {
			case 'draft':
				wp_update_post( [ 'ID' => $post->ID, 'post_status' => 'draft' ] );
				break;

			case 'trash':
				wp_trash_post( $post->ID );
				break;

			case 'private':
				wp_update_post( [ 'ID' => $post->ID, 'post_status' => 'private' ] );
				break;

			case 'delete':
				wp_delete_post( $post->ID, true );
				break;

			case 'category':
				$ids = array_filter( array_map( 'intval', (array) get_post_meta( $post->ID, '_mdce_expiry_category_ids', true ) ) );
				if ( $ids ) {
					wp_set_post_categories( $post->ID, $ids );
				}
				break;

			case 'title':
				$new_title = (string) get_post_meta( $post->ID, '_mdce_expiry_new_title', true );
				if ( $new_title ) {
					wp_update_post( [ 'ID' => $post->ID, 'post_title' => sanitize_text_field( $new_title ) ] );
				}
				break;

			default:
				// PRO actions (redirect, replace) hook into this dynamic action.
				do_action( "mdce_expire_action_{$action}", $post );
				break;
		}
	}
}
