<?php

namespace WeDevs\AppBridge\Integrations\Dokan;

use WeDevs\AppBridge\Core\AbstractIntegration;
use WeDevs\AppBridge\Core\Contracts\Hookable;
use WeDevs\AppBridge\Core\REST\PushNotificationsController;
use WeDevs\AppBridge\Integrations\Dokan\Notifications\VendorEventCatalog;
use WeDevs\AppBridge\Integrations\Dokan\Notifications\VendorEventDispatcher;
use WeDevs\AppBridge\Integrations\Dokan\REST\LicenseController;
use WeDevs\AppBridge\Integrations\Dokan\REST\ModuleController;
use WeDevs\AppBridge\Integrations\Dokan\REST\SettingsController;

class DokanIntegration extends AbstractIntegration {

	private LicenseManager $license_manager;

	public static function is_active(): bool {
		return class_exists( 'WeDevs\Dokan\Dokan' ) || function_exists( 'dokan' );
	}

	public function __construct() {
		$this->license_manager = new LicenseManager();
	}

	public function get_license_manager(): LicenseManager {
		return $this->license_manager;
	}

	/**
	 * Always-on hookables: LicenseManager must load regardless of license
	 * so the admin notice and license REST endpoint work.
	 *
	 * @return Hookable[]
	 */
	public function hookables(): array {
		$hookables = [
			$this->license_manager,
			new VendorEventDispatcher(),
		];

		if ( function_exists( 'dokan_pro' ) ) {
			$hookables[] = new DokanProLicenseVerification();
		}

		return $hookables;
	}

	/**
	 * License-gated hookables: only registered when license is valid.
	 *
	 * @return Hookable[]
	 */
	public function conditional_hookables(): array {
		if ( ! $this->is_licensed() ) {
			return [];
		}

		return [
			new DokanHooks(),
		];
	}

	/**
	 * REST controllers:
	 *   - Always-on: Settings + License (user must be able to activate).
	 *   - Licensed: vendor-app feature controllers.
	 *
	 * @return object[]
	 */
	public function rest_controllers(): array {
		$controllers = [
			new SettingsController( $this->license_manager ),
			new LicenseController( $this->license_manager ),
			new ModuleController(),
		];

		if ( $this->is_licensed() ) {
			array_push(
				$controllers,
				new PushNotificationsController(
                    'app-bridge/v1/vendor-app',
                    'app_bridge_vendor_settings'
                ),
			);
		}

		return $controllers;
	}

	public function menus(): array {
		return [
			[
				'label'    => __( 'Vendor App', 'app-bridge' ),
				'slug'     => 'app-bridge-vendor-app',
				'mount_id' => 'app-bridge-vendor-app',
			],
		];
	}

	public function event_catalogs(): array {
		return [
			'vendor' => VendorEventCatalog::categories(),
		];
	}

	public function event_option_keys(): array {
		return [
			'vendor' => 'app_bridge_vendor_settings',
		];
	}

	/**
	 * Whether the plugin license is currently valid.
	 */
	private function is_licensed(): bool {
		return $this->license_manager->get_license()->is_valid();
	}
}
