<?php
/**
 * Footer widget JSON import/export (SiteOrigin admin AJAX).
 *
 * @package Rsmspark_Content_Widgets
 */

defined( 'ABSPATH' ) || exit;

require_once RSMSPARK_CONTENT_WIDGETS_PATH . 'includes/class-rsmspark-content-widgets-widget-json-config.php';

/**
 * Rsmspark_Content_Widgets_Footer_Json
 */
class Rsmspark_Content_Widgets_Footer_Json {

	/**
	 * @return void
	 */
	public static function init() {
		add_action( 'wp_ajax_rsmspark_cw_footer_widget_json', array( __CLASS__, 'handle' ) );
	}

	/**
	 * @return void
	 */
	public static function handle() {
		if ( ! current_user_can( 'edit_posts' ) && ! current_user_can( 'edit_theme_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'rsm-content-widgets' ) ), 403 );
		}

		check_ajax_referer( 'rsmspark_cw_footer_admin', 'nonce' );

		$mode = sanitize_key( (string) ( $_POST['mode'] ?? '' ) );

		if ( 'export' === $mode ) {
			self::ajax_export();
		}

		if ( 'import' === $mode ) {
			self::ajax_import();
		}

		wp_send_json_error( array( 'message' => __( 'Invalid request.', 'rsm-content-widgets' ) ), 400 );
	}

	/**
	 * @return void
	 */
	private static function ajax_export() {
		// phpcs:disable WordPress.Security.NonceVerification.Missing -- Verified in ::handle() via check_ajax_referer().
		$raw      = Rsmspark_Content_Widgets_Widget_Json_Config::read_post_string( 'instance' );
		$instance = json_decode( $raw, true );
		$instance = is_array( $instance ) ? $instance : array();
		$label    = isset( $_POST['label'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['label'] ) ) : '';
		// phpcs:enable WordPress.Security.NonceVerification.Missing

		wp_send_json_success(
			Rsmspark_Content_Widgets_Footer_Config::build_export_payload( $instance, $label )
		);
	}

	/**
	 * @return void
	 */
	private static function ajax_import() {
		// phpcs:disable WordPress.Security.NonceVerification.Missing -- Verified in ::handle() via check_ajax_referer().
		$raw     = Rsmspark_Content_Widgets_Widget_Json_Config::read_post_string( 'payload' );
		$current = Rsmspark_Content_Widgets_Widget_Json_Config::read_post_string( 'instance' );
		// phpcs:enable WordPress.Security.NonceVerification.Missing
		$parsed  = Rsmspark_Content_Widgets_Footer_Config::parse_import_payload( $raw );

		if ( null === $parsed ) {
			wp_send_json_error(
				array(
					'message' => __( 'Paste valid RSM Footer JSON export data.', 'rsm-content-widgets' ),
				),
				400
			);
		}

		$instance = json_decode( $current, true );
		$instance = is_array( $instance ) ? $instance : array();

		wp_send_json_success(
			array(
				'config'   => $parsed['config'],
				'label'    => $parsed['label'],
				'instance' => Rsmspark_Content_Widgets_Footer_Config::merge_siteorigin_instance(
					$instance,
					$parsed['config']
				),
			)
		);
	}
}
