<?php
/**
 * Widget settings AJAX handlers for SiteStaffr admin.
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/admin/traits
 * @since      0.14.261
 */

if ( ! defined( 'WPINC' ) ) {
	die;
}

/**
 * Encapsulates widget-settings AJAX actions.
 */
// phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Raw request values are immediately unslashed and sanitized by sanitize_widget_settings().
trait SiteStaffr_Admin_Widget_Settings_Ajax_Trait {

	/**
	 * AJAX handler for per-section widget settings save.
	 *
	 * Collects form fields from the specified section and merges them into
	 * the sitestaffr_widget_settings option without a page reload.
	 *
	 * @since 0.14.167
	 * @return void
	 */
	public function ajax_save_widget_section() {
		check_ajax_referer( 'sitestaffr_save_widget_settings', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'sitestaffr' ) ), 403 );
			return;
		}

		$section = isset( $_POST['section'] ) ? sanitize_key( wp_unslash( $_POST['section'] ) ) : '';
		if ( ! in_array( $section, array( 'fixed', 'button' ), true ) ) {
			wp_send_json_error( array( 'message' => __( 'Invalid section.', 'sitestaffr' ) ), 400 );
			return;
		}

		// Get incoming field data (already namespaced under sitestaffr_widget_settings[]).
		$raw = isset( $_POST['settings'] ) && is_array( $_POST['settings'] ) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized by sanitize_widget_settings().
			? wp_unslash( $_POST['settings'] )
			: array();

		// Sanitize through the existing sanitize callback.
		$sanitized = $this->sanitize_widget_settings( $raw );

		// Merge with existing settings so the other section is preserved.
		$existing = get_option( 'sitestaffr_widget_settings', array() );
		$merged   = array_merge( $existing, $sanitized );
		update_option( 'sitestaffr_widget_settings', $merged );

		wp_send_json_success( array( 'message' => __( 'Settings saved.', 'sitestaffr' ) ) );
	}
}
// phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
