<?php
/**
 * Removes technical identifiers once they are no longer needed.
 *
 * @package SkyServers\Retragere
 */

declare(strict_types=1);

namespace SkyServers\Retragere\Wp;

use WP_Query;

/**
 * IP address and user agent support the evidentiary value of a request in its
 * first weeks. Keeping them for years serves nobody.
 */
final class Retention
{
    public const HOOK = 'ssrc_purge_personal_data';

    private const BATCH = 100;

    public static function schedule(): void
    {
        if (!wp_next_scheduled(self::HOOK)) {
            wp_schedule_event(time() + HOUR_IN_SECONDS, 'daily', self::HOOK);
        }
    }

    public static function unschedule(): void
    {
        wp_clear_scheduled_hook(self::HOOK);
    }

    public static function purge(): void
    {
        $days = (int) Settings::get('retention_days');

        if ($days <= 0) {
            return;
        }

        $query = new WP_Query(
            [
                'post_type'      => PostType::NAME,
                'post_status'    => array_keys(PostType::statusLabels()),
                'posts_per_page' => self::BATCH,
                'fields'         => 'ids',
                'date_query'     => [
                    [
                        'column' => 'post_date_gmt',
                        'before' => gmdate('Y-m-d H:i:s', time() - ($days * DAY_IN_SECONDS)),
                    ],
                ],
                // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- bounded lookup on a small post type.
                'meta_query'     => [
                    'relation' => 'OR',
                    [
                        'key'     => Repository::META_IP,
                        'value'   => '',
                        'compare' => '!=',
                    ],
                    [
                        'key'     => Repository::META_UA,
                        'value'   => '',
                        'compare' => '!=',
                    ],
                ],
            ]
        );

        foreach ($query->posts as $id) {
            update_post_meta((int) $id, Repository::META_IP, '');
            update_post_meta((int) $id, Repository::META_UA, '');
        }
    }
}
