<?php
/**
 * AJAX handler for rendering template previews.
 *
 * @package MailDoctor
 */

use MailDoctor\WPMD_Email_Templates;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * AJAX handler for rendering template previews.
 *
 * @return void
 */
function mail_doctor_ajax_preview(): void {
	if ( ! current_user_can( 'manage_woocommerce' ) && ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error(
			array(
				'message' => esc_html__( 'You do not have permission to preview templates.', 'mail-doctor' ),
			),
			403
		);
	}

	check_ajax_referer( 'mail_doctor_preview_template', 'nonce' );

	$email_type = isset( $_POST['email_type'] ) ? sanitize_key( wp_unslash( $_POST['email_type'] ) ) : '';
	$order_id   = isset( $_POST['order_id'] ) ? absint( wp_unslash( $_POST['order_id'] ) ) : 0;
	if ( ! $order_id ) {
		$order_id = mail_doctor_find_sample_order_id();
	}

	if ( '' === $email_type ) {
		wp_send_json_error(
			array(
				'message' => esc_html__( 'Email type is required.', 'mail-doctor' ),
			),
			400
		);
	}

	// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Elements sanitized below.
	$template_input = isset( $_POST['template'] ) && is_array( $_POST['template'] ) ? wp_unslash( $_POST['template'] ) : array();

	$template = array(
		'subject' => WPMD_Email_Templates::sanitize_line_field( isset( $template_input['subject'] ) ? (string) $template_input['subject'] : '' ),
		'heading' => WPMD_Email_Templates::sanitize_line_field( isset( $template_input['heading'] ) ? (string) $template_input['heading'] : '' ),
		'html'    => WPMD_Email_Templates::sanitize_html_field( isset( $template_input['html'] ) ? (string) $template_input['html'] : '' ),
		'css'     => WPMD_Email_Templates::sanitize_css_field( isset( $template_input['css'] ) ? (string) $template_input['css'] : '' ),
	);

	$prepared = mail_doctor_prepare_email_template(
		$email_type,
		$order_id,
		array(
			'template' => $template,
			'preview'  => true,
		)
	);

	if ( empty( $prepared['html'] ) ) {
		wp_send_json_error(
			array(
				'message' => esc_html__( 'Unable to render preview for this template.', 'mail-doctor' ),
			),
			500
		);
	}

	wp_send_json_success(
		array(
			'html'     => $prepared['html'],
			'subject'  => $prepared['subject'],
			'heading'  => $prepared['heading'],
			'order_id' => $prepared['order_id'],
		)
	);
}
