<?php
/**
 * Records when a request was actually refunded.
 *
 * @package SkyServers\Retragere
 */

declare(strict_types=1);

namespace SkyServers\Retragere\Wp;

use WP_Post;

/**
 * Written on the transition rather than by the screen that triggers it, so a
 * status changed from anywhere - the decision screen, a bulk action, another
 * plugin - still stops the clock.
 */
final class Settlement
{
    public static function register(): void
    {
        add_action('transition_post_status', [self::class, 'onTransition'], 10, 3);
    }

    /**
     * @param string  $new
     * @param string  $old
     * @param WP_Post $post
     */
    public static function onTransition($new, $old, $post): void
    {
        if (!$post instanceof WP_Post || PostType::NAME !== $post->post_type) {
            return;
        }

        if ($new === $old) {
            return;
        }

        if (PostType::STATUS_RAMBURSATA === $new) {
            if ('' === Repository::settledAt((int) $post->ID)) {
                update_post_meta((int) $post->ID, Repository::META_SETTLED, gmdate('Y-m-d H:i:s'));
            }

            return;
        }

        // Moving back out of "refunded" means the refund did not stand. The
        // clock has to start running again, otherwise the register would show a
        // settled request that was never settled.
        if (PostType::STATUS_RAMBURSATA === $old) {
            delete_post_meta((int) $post->ID, Repository::META_SETTLED);
        }
    }
}
