<?php
/**
 * Dashboard screen class.
 *
 * @since 5.0.0
 * @package elasticprobe
 */

namespace ElasticProbe\Screen;

use ElasticProbe\Features as FeaturesStore;
use ElasticProbe\REST;
use ElasticProbe\Screen;
use ElasticProbe\Utils;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Dashboard screen.
 *
 * @since 5.0.0
 * @package ElasticProbe
 */
class Features {
	/**
	 * Initialize class
	 */
	public function setup() {
		add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] );
		add_action( 'rest_api_init', [ $this, 'register_rest_routes' ] );
	}

	/**
	 * Enqueue script.
	 *
	 * @since 3.6.0
	 * @return void
	 */
	public function admin_enqueue_scripts() {
		if ( 'dashboard' !== Screen::factory()->get_current_screen() ) {
			return;
		}

		wp_enqueue_script(
			'eprobe_features_script',
			EPROBE_URL . 'dist/js/features-script.js',
			Utils\get_asset_info( 'features-script', 'dependencies' ),
			Utils\get_asset_info( 'features-script', 'version' ),
			true
		);

		wp_set_script_translations( 'eprobe_features_script', 'elasticprobe' );

		wp_enqueue_style(
			'eprobe_features_script',
			EPROBE_URL . 'dist/css/features-script.css',
			[ 'wp-components', 'wp-edit-post' ],
			Utils\get_asset_info( 'features-script', 'version' )
		);

		$store = FeaturesStore::factory();

		$features = $store->registered_features;
		$features = array_map( fn( $f ) => $f->get_json(), $features );
		$features = array_values( $features );

		$sync_url = ( defined( 'EPROBE_IS_NETWORK' ) && EPROBE_IS_NETWORK ) ?
				network_admin_url( 'admin.php?page=elasticprobe-sync' ) :
				admin_url( 'admin.php?page=elasticprobe-sync' );

		$data = [
			'apiUrl'        => rest_url( 'elasticprobe/v1/features' ),
			'epioLogoUrl'   => esc_url( plugins_url( '/images/logo-eprobe-com.svg', EPROBE_FILE ) ),
			'features'      => $features,
			'indexMeta'     => Utils\get_indexing_status(),
			'settings'      => $store->get_feature_settings(),
			'settingsDraft' => $store->get_feature_settings_draft(),
			'syncUrl'       => $sync_url,
			'syncNonce'     => wp_create_nonce( 'ep_sync_nonce' ),
		];

		wp_localize_script( 'eprobe_features_script', 'epDashboard', $data );
	}

	/**
	 * Register REST API routes.
	 *
	 * @return void
	 */
	public function register_rest_routes() {
		$controller = new REST\Features();
		$controller->register_routes();
	}
}
