<?php
/**
 * BookiFlex Reservation Extension
 *
 * @package    BookiFlex
 * @subpackage Reservation
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */

declare(strict_types=1);

namespace BookiFlex\Extensions\Reservation;

use BookiFlex\Core\Contract\ExtensionInterface;
use BookiFlex\Core\Contract\PluginInterface;
use BookiFlex\Extensions\Reservation\Job\CheckOverdueReservationsJob;

defined( 'ABSPATH' ) || exit;

/**
 * Reservation manager extension.
 * TODO: migrating in progress
 */
class Reservation implements ExtensionInterface
{
    protected PluginInterface $plugin;

    public function init(PluginInterface $plugin): void
    {
        $this->plugin = $plugin;

	    $plugin->getContainer()->register(new ServiceProvider());

	    // Register queue handlers for background jobs
	    $this->registerQueueHandlers();
    }

	/**
	 * Register queue handlers for background jobs
	 */
	private function registerQueueHandlers(): void
	{
		// Async quota deletion job (triggered on AccommodationType deletion)
		$this->plugin->addAction(
			CheckOverdueReservationsJob::HOOK,
			[$this, 'handleCheckOverdueReservations'],
			10,
			1
		);
	}

	/**
	 * Handle checking reservation's overdue status
	 *
	 * @param array $args Arguments from queue
	 */
	public function handleCheckOverdueReservations($args = []): void
	{
		$job = $this->plugin->getContainer()->get(CheckOverdueReservationsJob::class);

		if (is_array($args)) {
			$job->handle($args);
		} else {
			$this->plugin->getLogger()?->warning(
				'Invalid args passed to ' . CheckOverdueReservationsJob::HOOK,
				['args' => $args]
			);
		}
	}

    public function getName(): string
    {
        return 'Reservation';
    }

    public function getVersion(): string
    {
        return '1.0.0';
    }

    public function isCompatible(string $pluginVersion): bool
    {
        return version_compare($pluginVersion, '1.0.0', '>=');
    }
}
