<?php
defined( 'ABSPATH' ) || exit;

/**
 * GET + POST /tukiflow/v1/settings — Read and update plugin settings.
 *
 * Both routes require the `manage_options` capability and a valid WP REST nonce.
 */
class TFDC_Endpoint_Settings extends TFDC_Endpoint_Base {

	/**
	 * Register routes.
	 */
	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/settings',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_settings' ),
					'permission_callback' => array( $this, 'check_permission' ),
				),
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'update_settings' ),
					'permission_callback' => array( $this, 'check_permission' ),
				),
			)
		);
	}

	/**
	 * Permission: manage_options + valid WP REST nonce.
	 *
	 * @param WP_REST_Request $request
	 * @return bool|WP_Error
	 */
	public function check_permission( WP_REST_Request $request ) {
		if ( ! current_user_can( 'manage_options' ) ) {
			return new WP_Error( 'rest_forbidden', __( 'Insufficient permissions.', 'tukiflow-direct-checkout-woocommerce' ), array( 'status' => 403 ) );
		}
		$nonce_check = $this->check_nonce( $request );
		if ( is_wp_error( $nonce_check ) ) {
			return $nonce_check;
		}
		return true;
	}

	/**
	 * GET /settings — Return current settings.
	 *
	 * @param WP_REST_Request $request
	 * @return WP_REST_Response
	 */
	public function get_settings( WP_REST_Request $request ) {
		return rest_ensure_response( TFDC_Admin::get_settings() );
	}

	/**
	 * POST /settings — Validate and save settings.
	 *
	 * Accepts all settings at once (React posts the full state object).
	 * Passes `_tab = 'all'` so sanitize_settings() processes every field.
	 *
	 * @param WP_REST_Request $request
	 * @return WP_REST_Response|WP_Error
	 */
	public function update_settings( WP_REST_Request $request ) {
		$body = $request->get_json_params();
		if ( ! is_array( $body ) ) {
			return $this->json_error( __( 'Invalid request body.', 'tukiflow-direct-checkout-woocommerce' ), 400 );
		}

		// Tell sanitize_settings() to process every tab at once.
		$body['_tab'] = 'all';

		$admin    = TFDC_Admin::get_instance();
		$sanitized = $admin->sanitize_settings( $body );

		update_option( 'tfdc_settings', $sanitized );

		return rest_ensure_response( TFDC_Admin::get_settings() );
	}
}
