<?php
/**
 * ThemePreview AJAX handler
 *
 * Returns rendered HTML for a theme preview in the settings page.
 *
 * @package Relatedly\Admin\Ajax
 * @since   2.0.0
 */

namespace Relatedly\Admin\Ajax;

use Relatedly\Core\Options;
use Relatedly\Theming\ThemeRegistry;

defined( 'ABSPATH' ) || exit;

/**
 * Renders theme previews over AJAX.
 *
 * @since 2.0.0
 */
class ThemePreview {

	/**
	 * Plugin settings repository.
	 *
	 * @since 2.0.0
	 * @var Options
	 */
	private Options $options;

	/**
	 * Theme renderer registry.
	 *
	 * @since 2.0.0
	 * @var ThemeRegistry
	 */
	private ThemeRegistry $themes;

	/**
	 * Create the theme preview handler.
	 *
	 * @since 2.0.0
	 * @param Options       $options Plugin settings repository.
	 * @param ThemeRegistry $themes  Theme renderer registry.
	 */
	public function __construct( Options $options, ThemeRegistry $themes ) {
		$this->options = $options;
		$this->themes  = $themes;
	}

	/**
	 * Register the preview AJAX action.
	 *
	 * @since 2.0.0
	 */
	public function init_hooks(): void {
		add_action( 'wp_ajax_relatedly_theme_preview', [ $this, 'handle' ] );
	}

	/**
	 * Return rendered preview HTML for the requested theme.
	 *
	 * @since 2.0.0
	 */
	public function handle(): void {
		check_ajax_referer( 'relatedly_settings', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'relatedly' ) ] );
		}

		$context   = sanitize_key( $_POST['context'] ?? 'inline' );
		$theme_key = sanitize_key( $_POST['theme_key'] ?? 'theme1' );

		// Fetch a real post for the preview.
		$posts = get_posts(
			[
				'posts_per_page'      => 1,
				'orderby'             => 'date',
				'order'               => 'DESC',
				'ignore_sticky_posts' => true,
				'no_found_rows'       => true,
			]
		);

		if ( empty( $posts ) ) {
			wp_send_json_error( [ 'message' => __( 'No posts found for preview.', 'relatedly' ) ] );
		}

		$html = $this->themes->render( $context, $theme_key, $posts, null );
		wp_send_json_success( [ 'html' => $html ] );
	}
}
