<?php

declare( strict_types = 1 );

namespace FormConnector\Core\Admin;

use Kucrut\Vite;

/**
 * Admin bootstrapper
 *
 * @return void
 */
function bootstrap(): void {
	add_action( 'admin_menu', __NAMESPACE__ . '\\register_admin_menu' );
	add_action( 'admin_enqueue_scripts', __NAMESPACE__ . '\\enqueue_admin_scripts' );
	add_filter( 'admin_footer_text', __NAMESPACE__ . '\\remove_admin_footer_text' );
	add_filter( 'update_footer', '__return_empty_string', 11 );
}

/**
 * Remove admin footer text on our plugin pages
 *
 * @param string $text The default footer text.
 * @return string
 */
function remove_admin_footer_text( string $text ): string {
	$screen = get_current_screen();
	if ( $screen && $screen->id === 'toplevel_page_' . FC_SETTINGS_SLUG ) {
		return '';
	}

	return $text;
}

/**
 * Enqueue admin scripts
 *
 * @param string $hook_suffix The current admin page.
 * @return void
 */
function enqueue_admin_scripts( string $hook_suffix ): void {
	// Only load on our plugin's admin page
	if ( $hook_suffix !== 'toplevel_page_' . FC_SETTINGS_SLUG ) {
		return;
	}

	Vite\enqueue_asset(
		FC_PLUGIN_PATH . 'app/dist',
		'app/src/main.js',
		[
			'handle'    => 'fc-admin-svelte',
			'in-footer' => true,
		]
	);

	// Pass data to the Svelte app
	wp_localize_script( 'fc-admin-svelte', 'fcAdmin', [
		'ajaxUrl'   => admin_url( 'admin-ajax.php' ),
		'restUrl'   => rest_url( 'fc/v1/' ),
		'nonce'     => wp_create_nonce( 'fc_admin_nonce' ),
		'restNonce' => wp_create_nonce( 'wp_rest' ),
		'version'   => FC_VERSION,
		'page'      => isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '',
	] );
}

/**
 * Register admin menu
 *
 * @return void
 */
function register_admin_menu(): void {
	// Single menu page for Form Connector
	add_menu_page(
		__( 'CareHQ', 'form-connector' ),
		__( 'CareHQ', 'form-connector' ),
		'manage_options',
		FC_SETTINGS_SLUG,
		__NAMESPACE__ . '\\render_admin_page',
		get_menu_icon(),
		30
	);
}

/**
 * Get the menu icon
 *
 * @return string
 */
function get_menu_icon(): string {
	return 'dashicons-share-alt';
}

/**
 * Render admin page
 *
 * @return void
 */
function render_admin_page(): void {
	?>
	<div id="v4wp-app-svelte" class="v4wp-app-svelte"></div>
	<?php
}
