<?php
/**
 * Nonce-protected AJAX handlers: save the wizard model, render a live preview,
 * and publish/update the statement page.
 */

defined( 'ABSPATH' ) || exit;

class TSFFE_Ajax {

	public static function init(): void {
		add_action( 'wp_ajax_tsffe_save', array( __CLASS__, 'save' ) );
		add_action( 'wp_ajax_tsffe_preview', array( __CLASS__, 'preview' ) );
		add_action( 'wp_ajax_tsffe_publish', array( __CLASS__, 'publish' ) );
	}

	private static function guard(): void {
		check_ajax_referer( 'tsffe_admin' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => 'forbidden' ), 403 );
		}
	}

	/**
	 * Pull the raw statement model from $_POST['statement'] and sanitize it.
	 *
	 * @return array<string, mixed>
	 */
	private static function read_input(): array {
		// Sanitization is delegated to TSFFE_Data::sanitize(), which sanitizes
		// every field individually. We unslash first.
		$raw = isset( $_POST['statement'] ) ? wp_unslash( $_POST['statement'] ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput

		if ( ! is_array( $raw ) ) {
			$raw = array();
		}

		return TSFFE_Data::sanitize( $raw );
	}

	public static function save(): void {
		self::guard();

		$data = self::read_input();
		update_option( TSFFE_Page::OPTION_STATEMENT, $data );

		$footer = ! empty( $_POST['footer_link'] ) && '1' === sanitize_text_field( wp_unslash( $_POST['footer_link'] ) );
		update_option( TSFFE_Page::OPTION_FOOTER_LINK, $footer ? 1 : 0 );

		wp_send_json_success(
			array(
				'errors'      => TSFFE_Data::validate( $data ),
				'conformance' => $data['conformance'],
			)
		);
	}

	public static function preview(): void {
		self::guard();

		$data = self::read_input();

		wp_send_json_success( array( 'html' => TSFFE_Render::html( $data ) ) );
	}

	public static function publish(): void {
		self::guard();

		$data   = self::read_input();
		$errors = TSFFE_Data::validate( $data );

		if ( $errors ) {
			wp_send_json_error( array( 'errors' => $errors ) );
		}

		update_option( TSFFE_Page::OPTION_STATEMENT, $data );

		$footer = ! empty( $_POST['footer_link'] ) && '1' === sanitize_text_field( wp_unslash( $_POST['footer_link'] ) );
		update_option( TSFFE_Page::OPTION_FOOTER_LINK, $footer ? 1 : 0 );

		$page_id = TSFFE_Page::publish( $data );

		if ( ! $page_id ) {
			wp_send_json_error( array( 'message' => __( 'The statement page could not be saved.', 'tendforge-statement-forge-for-eaa' ) ) );
		}

		wp_send_json_success(
			array(
				'page_id'   => $page_id,
				'page_url'  => get_permalink( $page_id ),
				'edit_url'  => get_edit_post_link( $page_id, 'raw' ),
			)
		);
	}
}
