<?php
/**
 * AJAX controller for Schema V2 settings saves.
 *
 * @package SEOvaultSEO\Admin
 */

namespace SEOvaultSEO\Admin;

use SEOvaultSEO\Schema\SchemaArchitectureSettings;
use SEOvaultSEO\Schema\SchemaSettingsSanitizer;
use SEOvaultSEO\Utils\Logger;

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

/**
 * Handles V2 Schema-tab settings saves (non-legacy catalogue).
 */
class SchemaSettingsAdmin {

	/**
	 * Register AJAX hooks.
	 *
	 * @return void
	 */
	public static function init() {
		add_action( 'wp_ajax_seovaultseo_save_schema_v2_settings', array( __CLASS__, 'ajax_save_v2_settings' ) );
	}

	/**
	 * AJAX: save V2 schema settings only.
	 *
	 * @return void
	 */
	public static function ajax_save_v2_settings() {
		if ( ! check_ajax_referer( 'seovaultseo_admin', 'nonce', false ) ) {
			wp_send_json_error(
				array(
					'code'    => 'invalid_nonce',
					'message' => __( 'Security check failed. Reload the page and try again.', 'seovault-ai' ),
				),
				403
			);
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			Logger::error( 'SchemaSettingsAdmin::ajax_save_v2_settings: capability check failed' );
			wp_send_json_error(
				array(
					'code'    => 'unauthorized',
					'message' => __( 'Unauthorized.', 'seovault-ai' ),
				),
				403
			);
		}

		$raw_settings  = isset( $_POST['settings'] )
			? ( is_array( $_POST['settings'] )
				? map_deep( wp_unslash( $_POST['settings'] ), 'sanitize_text_field' )
				: wp_strip_all_tags( wp_unslash( (string) $_POST['settings'] ), true ) )
			: '';
		$payload_bytes = is_string( $raw_settings ) ? strlen( $raw_settings ) : 0;

		if ( is_string( $raw_settings ) && '' !== $raw_settings ) {
			$decoded = json_decode( $raw_settings, true );
		} elseif ( is_array( $raw_settings ) ) {
			$decoded       = $raw_settings;
			$payload_bytes = strlen( (string) wp_json_encode( $raw_settings ) );
		} else {
			$decoded = null;
		}

		$result = SchemaSettingsSanitizer::sanitize(
			$decoded,
			array(
				'payload_bytes' => $payload_bytes,
			)
		);

		if ( empty( $result['ok'] ) ) {
			$message = __( 'Invalid schema settings.', 'seovault-ai' );
			if ( in_array( 'rejected_legacy_or_specialized_fields', $result['errors'], true )
				|| in_array( 'rejected_specialized_enable', $result['errors'], true ) ) {
				$message = __( 'Specialized schema cannot be enabled for all posts from Schema settings. Add it on a post, block, or targeted template instead.', 'seovault-ai' );
			} elseif ( in_array( 'payload_too_large', $result['errors'], true ) ) {
				$message = __( 'Schema settings payload is too large.', 'seovault-ai' );
			} elseif ( in_array( 'absent_payload', $result['errors'], true ) || in_array( 'malformed_payload', $result['errors'], true ) || in_array( 'malformed_json', $result['errors'], true ) ) {
				$message = __( 'Schema settings payload was missing or malformed.', 'seovault-ai' );
			}

			wp_send_json_error(
				array(
					'code'     => 'invalid_settings',
					'message'  => $message,
					'errors'   => $result['errors'],
					'rejected' => $result['rejected'],
					'ignored'  => $result['ignored'],
				),
				400
			);
		}

		$expected_revision = isset( $result['settings']['settings_revision'] )
			? (int) $result['settings']['settings_revision']
			: ( isset( $_POST['settings_revision'] ) ? (int) $_POST['settings_revision'] : -1 );

		if ( $expected_revision < 0 ) {
			wp_send_json_error(
				array(
					'code'    => 'missing_settings_revision',
					'message' => __( 'Missing settings revision. Reload the page and try again.', 'seovault-ai' ),
				),
				400
			);
		}

		$saved = SchemaArchitectureSettings::save_v2_settings( $result['settings'], $expected_revision );
		if ( is_wp_error( $saved ) ) {
			$data = $saved->get_error_data();
			if ( ! is_array( $data ) ) {
				$data = array();
			}
			$data['code']    = $saved->get_error_code();
			$data['message'] = $saved->get_error_message();
			$status          = isset( $data['status'] ) ? (int) $data['status'] : 409;
			wp_send_json_error( $data, $status );
		}

		$saved['ignored'] = $result['ignored'];
		wp_send_json_success( $saved );
	}
}
