<?php

namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\I18n\Time;

class CleanupScheduler implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $lastRun = cache('last_cleanup_run');

        if ($lastRun === null || Time::now()->difference($lastRun)->getMinutes() >= 2) {
            // Trigger the cleanup
            $this->runCleanup();

            // Update the last run time
            cache()->save('last_cleanup_run', Time::now());
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Do nothing after the request
    }

    private function runCleanup()
    {
        // Call the cleanup controller method
        \CodeIgniter\CLI\CLI::init();
        command('cleanup:unverified_users');
    }
}
