<?php
/**
 * Abstract update module for packages.
 *
 * @package northmill-online-shared
 */

declare(strict_types=1);

namespace Northmill_Online_Shared\Modules\Updaters;

use Northmill_Online_Shared\Modules\Abstract_Module;

/**
 * Abstract updater class.
 */
abstract class Abstract_Updater_Module extends Abstract_Module {

	/**
	 * Array of transient name/keys.
	 *
	 * @var string[]
	 */
	private array $transients;

	/**
	 * Whether the updater is set up.
	 *
	 * @var bool
	 */
	protected bool $is_setup = false;

	/**
	 * Run setup for the package updater.
	 */
	public function setup(): void {
		$this->transients = array(
			'remote_data'  => $this->shared->package_info->get_service_name_underscored() . '_package_update_remote_data',
			'remote_error' => $this->shared->package_info->get_service_name_underscored() . '_package_update_remote_error',
		);

		$this->is_setup = true;
	}

	/**
	 * Checks if the updater should be set up.
	 *
	 * @return bool
	 */
	public function should_setup(): bool {
		return ! empty( $this->shared->package_info->get_info_json_url() );
	}

	/**
	 * Returns all defined transients.
	 *
	 * @return array The array of defined transients.
	 */
	public function get_all_transients(): array {
		return $this->transients;
	}

	/**
	 * Retrieves a transient value.
	 *
	 * @param string $key The key of the transient to retrieve.
	 *
	 * @return mixed The value of the transient.
	 */
	public function get_transient( string $key ): mixed {
		return get_transient( $this->transients[ $key ] );
	}

	/**
	 * Deletes a transient value.
	 *
	 * @param string $key The key of the transient to delete.
	 *
	 * @return bool True if the transient was deleted, false otherwise.
	 */
	public function delete_transient( string $key ): bool {
		return delete_transient( $this->transients[ $key ] );
	}

	/**
	 * Delete all transients.
	 *
	 * @return void
	 */
	public function delete_all_transients(): void {
		foreach ( $this->transients as $key ) {
			delete_transient( $key );
		}
	}

	/**
	 * Updates a transient value.
	 *
	 * @param string $key        The key of the transient to update.
	 * @param mixed  $value      The new value of the transient.
	 * @param int    $expiration Optional. The duration in seconds for the transient. It defaults to 0, which means no expiration.
	 *
	 * @return void
	 */
	public function set_transient( string $key, mixed $value, int $expiration = 0 ): void {
		set_transient( $this->transients[ $key ], $value, $expiration );
	}
}
