<?php
/**
 * Class ShipmentsSubmenu
 *
 * @package DhlPolska\Admin\Menu
 */

namespace DhlPolska\Admin\Menu;

use DhlPolska\Admin\DhlPolskaMenu;
use DhlPolska\Admin\Shipments\ShipmentsListTable;
use DhlPolskaVendor\Octolize\DhlPolska\API\WebAPI;
use DhlPolska\WooCommerceSettings\WooCommerceDHLPolskaSettings;
use DhlPolskaVendor\Psr\Log\LoggerInterface;
use DhlPolskaVendor\WPDesk\PluginBuilder\Plugin\Hookable;

/**
 * Register DHL Polska shipments submenu.
 */
class ShipmentsSubmenu implements Hookable {

	private const SCRIPT_HANDLE = 'dhl_polska_shipments_page';

	private WooCommerceDHLPolskaSettings $settings;

	private LoggerInterface $logger;

	private WebAPI $webapi;

	private string $assets_url;

	private string $scripts_version;

	public function __construct( WooCommerceDHLPolskaSettings $settings, LoggerInterface $logger, WebAPI $webapi, string $assets_url, string $scripts_version ) {
		$this->settings        = $settings;
		$this->logger          = $logger;
		$this->webapi          = $webapi;
		$this->assets_url      = $assets_url;
		$this->scripts_version = $scripts_version;
	}

	/**
	 * Hooks.
	 */
	public function hooks() {
		add_action( 'admin_menu', [ $this, 'register_submenu' ] );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );
	}

	/**
	 * @return void
	 */
	public function register_submenu() {
		add_submenu_page(
			DhlPolskaMenu::MENU_SLUG,
			__( 'Przesyłki', 'dhl-polska' ),
			__( 'Przesyłki', 'dhl-polska' ),
			'manage_woocommerce',
			DhlPolskaMenu::MENU_SLUG,
			[ $this, 'render_page' ],
			1
		);
	}

	/**
	 * @return void
	 */
	public function enqueue_assets() {
		if ( ! $this->is_shipments_page() ) {
			return;
		}

		$suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';

		wp_register_script(
			self::SCRIPT_HANDLE,
			$this->assets_url . 'js/admin-shipments-page' . $suffix . '.js',
			[],
			$this->scripts_version,
			true
		);
		wp_enqueue_script( self::SCRIPT_HANDLE );
	}

	/**
	 * @return void
	 */
	public function render_page() {
		$table = new ShipmentsListTable( $this->settings, $this->logger, $this->webapi );
		$table->handle_bulk_actions();
		$table->prepare_items();
		$notice    = $table->get_notice();
		$menu_slug = DhlPolskaMenu::MENU_SLUG;

		include __DIR__ . '/../views/html-shipments-page.php';
	}

	private function is_shipments_page(): bool {
		if ( ! function_exists( 'get_current_screen' ) ) {
			return false;
		}

		$screen = get_current_screen();
		if ( ! $screen instanceof \WP_Screen ) {
			return false;
		}

		$screen_id = $screen->id;

		return in_array(
			$screen_id,
			[
				'toplevel_page_' . DhlPolskaMenu::MENU_SLUG,
				DhlPolskaMenu::MENU_SLUG . '_page_' . DhlPolskaMenu::MENU_SLUG,
			],
			true
		);
	}
}
