<?php
/**
 * Admin-menu controller.
 *
 * @package Fast-Events/Mainmenu
 * @since 1.0
 */

declare(strict_types=1);
namespace FeData\FastEvents\Admin;

use FeData\FastEvents\Storage\Encryption;
use FeData\FastEvents\Storage\Options;
use FeData\FastEvents\Storage\PluginSettings;
use FeData\FastEvents\Utilities\PluginUtil;

defined( 'ABSPATH' ) || exit;

/**
 * AdminMenu class.
 */
class AdminMenu {

	/**
	 * AdminMenu constructor.
	 *
	 * @since 3.0
	 *
	 * @param Options        $options         Options class.
	 * @param PluginSettings $plugin_settings Settings class.
	 * @param Encryption     $encryption      Encryption class.
	 */
	public function __construct(
		private readonly Options $options,
		private readonly PluginSettings $plugin_settings,
		private readonly Encryption $encryption
	) {
		require_once ABSPATH . 'wp-admin/includes/file.php';
		WP_Filesystem();
	}


	/**
	 * Load JS or CSS.
	 *
	 * @since 1.0
	 * @since 2.3.0 Bootstrap 5.3.3
	 * @since 2.4.0 Bootstrap 5.3.8
	 * @since 2.5.0 Load qrcode
	 *
	 * @param string $id   The JS or CSS identifier.
	 * @param int    $type 0=JS and 1=CSS.
	 *
	 * @return void
	 */
	private function load_from_local( string $id, int $type = 0 ): void {
		static $assets = array(
			'Bootstrap-style' => array(
				'/assets/css/bootstrap.min.css',
				null,
				'5.3.8',
			),
			'Bootstrap-js'    => array(
				'/assets/js/bootstrap.bundle.min.js',
				array( 'jquery' ),
				'5.3.8',
			),
			'Qrcode-js'       => array(
				'/assets/js/qrcode.min.js',
				null,
				'1.0.0',
			),
		);

		// Set an asset path.
		$asset_path = PluginUtil::plugin_url() . $assets[ $id ][0];

		// Load JS or CSS.
		if ( 1 === $type ) {
			wp_enqueue_style( $id, $asset_path, $assets[ $id ][1], $assets[ $id ][2] );
		} else {
			wp_register_script( $id, $asset_path, $assets[ $id ][1], $assets[ $id ][2], true );
			wp_enqueue_script( $id );
		}
	}


	/**
	 * Load additional styles and scripts from CDN.
	 * Also include the localized strings for the JavaScript files
	 *
	 * @since 1.0
	 * @since 2.5.0 Load qrcode.
	 *
	 * @param string $hook Page name.
	 *
	 * @return void
	 */
	public function load_styles_scripts( string $hook ): void {
		// Only load CSS/JS for the Fast Event pages.
		if ( 'toplevel_page_fast_events' !== $hook ) {
			return;
		}

		// Load stylesheets.
		$this->load_from_local( 'Bootstrap-style', 1 );
		wp_enqueue_style( 'FE-Events-styles', PluginUtil::plugin_url() . '/assets/css/fast-events.min.css', null, fast_events_func()::FAST_EVENTS_VERSION );

		// Load scripts.
		$this->load_from_local( 'Qrcode-js' );
		$this->load_from_local( 'Bootstrap-js' );

		wp_localize_script(
			'Bootstrap-js',
			'feWpOrders',
			array(
				'home'            => esc_url_raw( home_url() ),
				'root'            => esc_url_raw( rest_url( '/fast-events/v1/' ) ),
				'plugin'          => esc_url_raw( PluginUtil::plugin_url() ),
				'nonce'           => wp_create_nonce( 'wp_rest' ),
				'currency'        => $this->plugin_settings->currency(),
				'currency_symbol' => $this->plugin_settings->currency_symbol(),
				'custom_status'   => $this->plugin_settings->misc_custom_order_status(),
				'admin_api_key'   => $this->plugin_settings->admin_api_key(),
				'timeout'         => esc_html__( 'The server did not respond within the given timeframe (5 seconds)', 'fast-events' ),
				'no_route'        => esc_html__( 'The server does not support this request; please ask the site administrator for help', 'fast-events' ),
				'fetch_failed'    => esc_html__( 'Could not connect to the server; please ask the site administrator for help', 'fast-events' ),
				'forbidden'       => esc_html__( 'You do not have permission on the server to execute this request; please ask the site administrator for help', 'fast-events' ),
				'invalid_json'    => esc_html__( 'The server did not return valid JSON: ', 'fast-events' ),
			)
		);
	}


	/**
	 * Create the Fast Events main menu
	 *
	 * @since 1.0
	 */
	public function add_admin_menu(): void {
		$mgt     = $this->options->get_management_settings();
		$display = ! empty( $mgt['new_version'] ) && ! empty( $mgt['new_changes'] )
			? '<span style="color:red"> &#9679;</span>'
			: '';
		add_menu_page(
			'Fast Events',
			'Fast Events' . $display,
			'manage_options',
			'fast_events',
			array( $this, 'fast_events_options_page' ),
			'dashicons-tickets-alt',
			81
		);
		add_submenu_page(
			'fast_events',
			esc_html__( 'Settings', 'fast-events' ),
			esc_html__( 'Settings', 'fast-events' ) . $display,
			'manage_options',
			'fast_events',
			array( $this, 'fast_events_options_page' )
		);
		add_submenu_page(
			'fast_events',
			esc_html__( 'Administration', 'fast-events' ),
			esc_html__( 'Administration', 'fast-events' ),
			'manage_options',
			'fast_events_admin',
			array( $this, 'fast_events_admin_page' )
		);
	}


	/**
	 * Render the settings page
	 *
	 * @since 1.0
	 * @since 1.4 Check for SaaS mode
	 * @since 2.5.0 - Simplified capability checking by using 'current_user_can'.
	 *              - Pass 'home', 'key' and 'nonce' via data attributes, so they won't show up in the webserver logging files.
	 */
	public function fast_events_options_page(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'No authorization to change settings', 'fast-events' ) );
		}

		echo '<h2>' . esc_html__( 'Settings', 'fast-events' ) . '</h2>';

		wp_register_script( 'FE-settings-js', PluginUtil::plugin_url() . '/assets/js/fe-settings.min.js', null, fast_events_func()::FAST_EVENTS_VERSION, true );
		wp_enqueue_script( 'FE-settings-js' );
		include_once PluginUtil::plugin_path() . '/templates/settings.php';
	}


	/**
	 * Render the admin page
	 *
	 * @since 2.0
	 * @since 2.1 Check if dir exists and if index.html exists.
	 * @since 2.5.0 Simplified capabilities check.
	 */
	public function fast_events_admin_page(): void {
		global $wp_filesystem;

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'No authorization to manage this plugin', 'fast-events' ) );
		}

		// Is this a multisite environment and not the main site?
		if ( ! is_main_site() ) {
			switch_to_blog( get_main_network_id() );
			$upload_dir = wp_upload_dir();
			$admin      = $upload_dir['basedir'] . '/fast-events/admin';
			restore_current_blog();
			if ( ! $wp_filesystem->exists( $admin ) || ! $wp_filesystem->exists( $admin . '/index.html' ) ) {
				echo '<h2>' . esc_html__( 'Administration', 'fast-events' ) . '</h2><p>';
				esc_html_e( 'The fast-events plugin management interface is not installed.', 'fast-events' );
				echo '</p><p>';
				esc_html_e( 'Ask your site administrator to install the management interface.', 'fast-events' );
				echo '</p>';
				return;
			}
		} else {
			$upload_dir = wp_upload_dir();
			$admin      = $upload_dir['basedir'] . '/fast-events/admin';
			if ( empty( $this->options->get_management_settings() ) || ! $wp_filesystem->exists( $admin ) || ! $wp_filesystem->exists( $admin . '/index.html' ) ) {
				$this->options->delete_management_settings();
				echo '<h2>' . esc_html__( 'Administration', 'fast-events' ) . '</h2><p>';
				esc_html_e( 'The fast-events plugin management interface can be installed in 2 ways.', 'fast-events' );
				echo '</p><ol><li>';
				esc_html_e( 'Install the management interface in the plugin\'s management panel in WordPress.The interface is then available under this menu choice. This is the easiest way and the interface will update automatically if chosen. For this choice, go to the plugin\'s settings and choose \'Management interface\' and click the button to install this interface.', 'fast-events' );
				echo '</li><li>';
				esc_html_e( 'Install the FE Admin App (Android or IOS) on a phone or tablet. How to install this App can be found at: ', 'fast-events' );
				echo '<a href="https://docs.fast-events.eu/en/latest/apps/admin.html" target="_blank" rel="noreferrer noopener">https://docs.fast-events.eu/en/latest/apps/admin.html</a>';
				echo '</li></ol><p>';
				esc_html_e( 'Of course it is possible to do both installations. Both interfaces offer exactly the same functionality.', 'fast-events' );
				echo '</p>';
				return;
			}
		}

		echo '<div style="margin:15px 25px 0 0;">';
		echo '<iframe id="fe_flutter_app" allow="web-share" style="height:85vh" ' .
		     'data-home="' . home_url() . '" data-key="' . ( $this->plugin_settings->admin_api_key() ?? 'NOT_FOUND' ) . '" data-nonce="' . wp_create_nonce( 'wp_rest' ) . '" ' . // phpcs:ignore
		     'src="' . $upload_dir['baseurl'] . '/fast-events/admin/" width="100%"> </iframe>'; // phpcs:ignore
		echo '</div>';
	}
}
