<?php
/**
 * Sync (Dashboard Index) functionality
 *
 * @since  3.6.0
 * @package elasticprobe
 */

namespace ElasticProbe\Screen;

use ElasticProbe\Elasticsearch;
use ElasticProbe\Indexables;
use ElasticProbe\IndexHelper;
use ElasticProbe\REST;
use ElasticProbe\Screen;
use ElasticProbe\Stats;
use ElasticProbe\Utils;

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

/**
 * Class Sync
 *
 * @since  3.6.0
 * @package ElasticProbe
 */
class Sync {
	/**
	 * 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 ( 'sync' !== Screen::factory()->get_current_screen() ) {
			return;
		}

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

		wp_set_script_translations( 'eprobe_sync_scripts', 'elasticprobe' );

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

		$indexables = Indexables::factory()->get_all();

		$indices_comparison = Elasticsearch::factory()->get_indices_comparison();
		$indices_missing    = count( $indices_comparison['missing_indices'] ) > 0;

		$post_types = Indexables::factory()->get( 'post' )->get_indexable_post_types();
		$post_types = array_values( $post_types );

		$sync_history = ! $indices_missing ? IndexHelper::factory()->get_sync_history() : [];

		$data = [
			'apiUrl'      => rest_url( 'elasticprobe/v1/sync' ),
			'autoIndex'   => Utils\isset_do_sync_parameter() && ( ! defined( 'EPROBE_DASHBOARD_SYNC' ) || EPROBE_DASHBOARD_SYNC ),
			'indexMeta'   => Utils\get_indexing_status(),
			'indexables'  => array_map( fn( $indexable ) => [ $indexable->slug, $indexable->labels['plural'] ], $indexables ),
			'isEpio'      => Utils\is_epio(),
			'nonce'       => wp_create_nonce( 'wp_rest' ),
			'postTypes'   => array_map( fn( $post_type ) => [ $post_type, get_post_type_object( $post_type )->labels->name ], $post_types ),
			'syncHistory' => $sync_history,
			'syncTrigger' => Utils\isset_do_sync_parameter() ? sanitize_text_field( wp_unslash( $_GET['do_sync'] ) ) : null, // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		];

		wp_localize_script( 'eprobe_sync_scripts', 'epDash', $data );
	}

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