<?php
/**
 * Admin AJAX for RSM Buttons.
 *
 * @package Rsmspark_Content_Widgets
 */

defined( 'ABSPATH' ) || exit;

/**
 * Rsmspark_Buttons_Ajax
 */
class Rsmspark_Buttons_Ajax {

	/**
	 * @return void
	 */
	public static function init() {
		add_action( 'wp_ajax_rsmspark_search_posts_for_button', array( __CLASS__, 'search_posts' ) );
		add_action( 'wp_ajax_rsmspark_buttons_preview', array( __CLASS__, 'preview_button' ) );
	}

	/**
	 * Live preview HTML for the button builder.
	 *
	 * @return void
	 */
	public static function preview_button() {
		check_ajax_referer( 'rsmspark_buttons_admin', 'nonce' );

		if ( ! current_user_can( 'manage_rsm_buttons' ) && ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'rsm-content-widgets' ) ), 403 );
		}

		$raw = isset( $_POST['config'] ) && is_array( $_POST['config'] ) ? wp_unslash( $_POST['config'] ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Validated immediately by Rsmspark_Buttons_Config::sanitize().
		$config = Rsmspark_Buttons_Config::sanitize( $raw );

		wp_send_json_success(
			array(
				'html' => Rsmspark_Buttons_Render::render( $config, 0, true ),
			)
		);
	}

	/**
	 * @return void
	 */
	public static function search_posts() {
		check_ajax_referer( 'rsmspark_buttons_admin', 'nonce' );

		if ( ! current_user_can( 'manage_rsm_buttons' ) && ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'rsm-content-widgets' ) ), 403 );
		}

		$search = sanitize_text_field( wp_unslash( (string) ( $_POST['search'] ?? '' ) ) );
		$posts  = get_posts(
			array(
				's'              => $search,
				'post_type'      => array( 'page', 'post' ),
				'post_status'    => 'publish',
				'posts_per_page' => 20,
				'orderby'        => 'relevance',
			)
		);

		$results = array();
		foreach ( $posts as $post ) {
			$results[] = array(
				'id'        => $post->ID,
				'title'     => get_the_title( $post ),
				'type'      => $post->post_type,
				'permalink' => get_permalink( $post ),
			);
		}

		wp_send_json_success( array( 'results' => $results ) );
	}
}
