<?php

class Facet_Wp_Remote_Data_Rest_Api {

	public function register_rest_api_routes() {
		register_rest_route(
			'sw-facetwp/v1',
			'/sync-settings',
			[
				'methods'  => 'GET',
				'callback' => [$this, 'handle_facetwp_sync_request'],
				'permission_callback' => [$this, 'validate_request_origin'],
			]
		);
	}

	public function validate_request_origin( WP_REST_Request $request ) {
		$allowed_origin = get_option( 'facetwp_remote_data_remote_site_url' );

		if ( empty( $allowed_origin ) ) {
			return new WP_Error( 'invalid_origin', 'No valid origin set in plugin settings.', ['status' => 403] );
		}

		$request_origin = $request->get_header( 'Main-Site-Url' );

		if ( empty( $request_origin ) ) {
			return new WP_Error( 'unauthorized', 'Access denied. Invalid request origin.', ['status' => 403] );
		}

		$allowed_origin = untrailingslashit( $allowed_origin );
		$request_origin = untrailingslashit( $request_origin );

		if ( false === strpos( $request_origin, $allowed_origin ) ) {
			return new WP_Error( 'unauthorized', 'Access denied. Invalid request origin.', ['status' => 403] );
		}

		return true;
	}

	public function handle_facetwp_sync_request( WP_REST_Request $request ) {
		$auto_sync_enabled = get_option( 'facetwp_remote_data_enable_auto_sync', false );

		if ( ! $auto_sync_enabled ) {
			return new WP_Error( 'auto_sync_disabled', 'Automatic syncing is disabled.', ['status' => 403] );
		}

		$sync_facetwp_settings_result = Facet_Wp_Remote_Data_Admin::sync_facetwp_settings();

		if ( is_wp_error( $sync_facetwp_settings_result ) ) {
			return rest_ensure_response( $sync_facetwp_settings_result );
		}

		if ( ! wp_next_scheduled( 'facetwp_remote_data_sync_index_batch_event' ) ) {
			wp_schedule_single_event( time() + 5, 'facetwp_remote_data_sync_index_batch_event', [ 1 ] );
		}

		return rest_ensure_response( ['success' => true, 'message' => 'FacetWP settings synced successfully.'] );
	}

}