<?php

namespace SugarCalendarBookings\Support\Ajax;

use SugarCalendarBookings\Support\DataProcessing\InputProcessor;

/**
 * Abstract controller.
 *
 * @since 1.0.0
 */
abstract class AbstractController {

	/**
	 * Get sanitized and validated data from POST request.
	 *
	 * IMPORTANT: The sanitizer never returns the raw value.
	 *  - If the value cannot be sanitized, an empty value is returned.
	 *  - If no sanitization rule is defined for some of the input fields,
	 *    those fields will be excluded from the sanitized result.
	 *  - If the rules are set, but not include sanitization rule,
	 *    those fields will be excluded from the sanitized result.
	 *
	 * @since 1.0.0
	 *
	 * @param array $rules Rules to sanitize and validate the data.
	 *
	 * @return array
	 */
	public function get_input_data( $rules ) {

		$data = [];

		// phpcs:disable
		if ( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] === 'POST' ) {
			$json = file_get_contents( 'php://input' );

			if ( $json !== false ) {
				$data = json_decode( $json, true ) ?? [];
			}
		} else {
			$data = $_GET['data'] ?? [];
		}
		// phpcs:enable

		$data = wp_unslash( $data );

		$sanitized_data = InputProcessor::process( $data, $rules );

		if ( is_wp_error( $sanitized_data ) ) {
			wp_send_json_error( $sanitized_data->get_error_message() );
		}

		return $sanitized_data;
	}
}
