<?php

declare(strict_types=1);

namespace AllCoach\Admin;

defined( 'ABSPATH' ) || exit;

use AllCoach\Core\Constants;
use AllCoach\Core\Container;
use AllCoach\Core\ServiceProvider;
use AllCoach\Infrastructure\Google\GoogleOAuthClient;
use AllCoach\Infrastructure\Google\GoogleTokenManager;
use AllCoach\Support\AssetManager;
use AllCoach\Traits\Hooks;
use DI\ContainerBuilder;

use function AllCoach\Support\currencies;
use function AllCoach\Support\timezones;

class AdminServiceProvider implements ServiceProvider {

	use Hooks;

	public function __construct(
		private readonly Container $container,
		private readonly AssetManager $assetManager,
		private readonly GoogleOAuthClient $googleOAuthClient,
		private readonly GoogleTokenManager $googleTokenManager,
	) {}

	public function register( ContainerBuilder $builder ): void {}

	public function boot(): void {
		$this->addAction( 'admin_menu', [ $this, 'registerMenus' ] );
		$this->addAction( 'allcoach:enqueue-assets:admin', [ $this, 'enqueueAssets' ] );
		$this->addAction( 'admin_footer', [ $this, 'inlineMenuHighlight' ] );
	}

	public function registerMenus(): void {
		$dashicon = 'data:image/svg+xml;base64,' . base64_encode( (string) file_get_contents( Constants::path( 'assets/images/dashicon-allcoach.svg' ) ) );

		add_menu_page(
			__( 'AllCoach', 'allcoach' ),
			__( 'AllCoach', 'allcoach' ),
			'manage_options',
			'allcoach',
			function () {
				echo '<div id="AllCoach-Admin-Root"></div>';
			},
			$dashicon,
			30
		);

		add_submenu_page(
			parent_slug: 'allcoach',
			page_title: __( 'Programs', 'allcoach' ),
			menu_title: __( 'Programs', 'allcoach' ),
			capability: 'manage_options',
			menu_slug: 'allcoach#/programs',
			callback: function () {
				echo '<div id="AllCoach-Admin-Root"></div>';
			},
		);

		add_submenu_page(
			parent_slug: 'allcoach',
			page_title: __( 'Clients', 'allcoach' ),
			menu_title: __( 'Clients', 'allcoach' ),
			capability: 'manage_options',
			menu_slug: 'allcoach#/clients',
			callback: function () {
				echo '<div id="AllCoach-Admin-Root"></div>';
			},
		);

		add_submenu_page(
			parent_slug: 'allcoach',
			page_title: __( 'Appointments', 'allcoach' ),
			menu_title: __( 'Appointments', 'allcoach' ),
			capability: 'manage_options',
			menu_slug: 'allcoach#/appointments',
			callback: function () {
				echo '<div id="AllCoach-Admin-Root"></div>';
			},
		);

		add_submenu_page(
			parent_slug: 'allcoach',
			page_title: __( 'Orders', 'allcoach' ),
			menu_title: __( 'Orders', 'allcoach' ),
			capability: 'manage_options',
			menu_slug: 'allcoach#/orders',
			callback: function () {
				echo '<div id="AllCoach-Admin-Root"></div>';
			},
		);

		add_submenu_page(
			parent_slug: 'allcoach',
			page_title: __( 'Settings', 'allcoach' ),
			menu_title: __( 'Settings', 'allcoach' ),
			capability: 'manage_options',
			menu_slug: 'allcoach#/settings',
			callback: function () {
				echo '<div id="AllCoach-Admin-Root"></div>';
			},
		);

		remove_submenu_page( 'allcoach', 'allcoach' );
	}

	public function inlineMenuHighlight(): void {
		$screen = get_current_screen();
		if ( ! $screen || ! str_contains( $screen->id, 'allcoach' ) ) {
			return;
		}
		$script = <<<'JS'
(function () {
	function syncHighlight() {
		const rawHash = window.location.hash || '#/programs';
		// Strip search params from hash (e.g. #/bookings/?page=1 → #/bookings/)
		const hashPath = rawHash.split('?')[0];
		// Normalise trailing slash (e.g. #/bookings/ → #/bookings)
		const normalised = hashPath.replace(/\/$/, '');
		const submenu = document.querySelector(
			'#toplevel_page_allcoach .wp-submenu',
		);
		if (!submenu) return;
		submenu.querySelectorAll('li').forEach(function (li) {
			const a = li.querySelector('a');
			if (!a) return;
			const href = a.getAttribute('href') || '';
			// Normalise the link's hash the same way
			const linkHash = href.includes('#') ? '#' + href.split('#')[1] : '';
			const linkNormalised = linkHash.replace(/\/$/, '');

			if (linkNormalised && normalised.startsWith(linkNormalised)) {
				li.classList.add('current');
			} else {
				li.classList.remove('current');
			}
		});
	}
	syncHighlight();
	window.addEventListener('allcoach:navigate', syncHighlight);
})();
JS;
		wp_print_inline_script_tag(
			$script,
			[
				'type' => 'text/javascript',
				'id'   => 'AllCoach-Menu-Highlight',
			]
		);
	}

	public function enqueueAssets( string $hook ): void {
		if ( ! str_contains( $hook, 'allcoach' ) ) {
			return;
		}

		$adminData = $this->applyFilters(
			'allcoach:admin:script_data',
			[
				'adminUrl'          => admin_url( 'admin.php' ),
				'pluginUrl'         => Constants::url(),
				'currentUserId'     => get_current_user_id(),
				'isAdmin'           => current_user_can( 'manage_options' ),
				'nonce'             => wp_create_nonce( 'wp_rest' ),
				'version'           => Constants::VERSION,
				'currencies'        => currencies()->getAll(),
				'timezones'         => timezones()->getAll(),
				'googleCallbackUrl' => rest_url( 'allcoach/v1/google/callback' ),
				'homeUrl'           => home_url( '/' ),
				'googleIntegration' => [
					'isConfigured' => $this->googleOAuthClient->isConfigured(),
					'isConnected'  => $this->googleTokenManager->isConnected( get_current_user_id() ),
				],
			]
		);

		wp_enqueue_media();

		$this->assetManager->enqueueScript(
			handle: 'admin',
			src: 'admin.js',
			localize:[
				'object_name' => '__ALLCOACH_ADMIN__',
				'data'        => $adminData,
			]
		);
		$this->assetManager->enqueueStyle(
			handle: 'admin',
			src: 'admin.css'
		);
		if ( is_rtl() ) {
			$this->assetManager->enqueueStyle(
				handle: 'admin-rtl',
				src: 'admin.rtl.css'
			);
		}

		$this->doAction( 'allcoach:admin:enqueue_assets', $hook );
	}
}
