<?php
/**
 * REST endpoint for onboarding status.
 *
 * @since 1.0.0
 */

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

class ZINV_REST_Onboarding {

	private string $namespace;

	public function __construct( string $namespace ) {
		$this->namespace = $namespace;
	}

	public function register(): void {
		register_rest_route( $this->namespace, '/onboarding/status', [
			'methods'             => WP_REST_Server::READABLE,
			'callback'            => [ $this, 'get_status' ],
			'permission_callback' => function () {
				return current_user_can( 'zinv_manage_settings' );
			},
		] );

		register_rest_route( $this->namespace, '/onboarding/complete', [
			'methods'             => WP_REST_Server::CREATABLE,
			'callback'            => [ $this, 'complete' ],
			'permission_callback' => function () {
				return current_user_can( 'zinv_manage_settings' );
			},
		] );
	}

	public function get_status( WP_REST_Request $request ): WP_REST_Response {
		$completed = get_option( 'zinv_onboarding_complete', false );

		$settings = [];
		$general  = get_option( 'zinv_onboarding_general', [] );
		if ( is_array( $general ) && ! empty( $general ) ) {
			$settings['general'] = $general;
		}

		return new WP_REST_Response( [
			'completed' => (bool) $completed,
			'step'      => (int) get_option( 'zinv_onboarding_step', 0 ),
			'settings'  => $settings,
		], 200 );
	}

	public function complete( WP_REST_Request $request ): WP_REST_Response {
		$step   = min( 4, absint( $request->get_param( 'step' ) ?? 4 ) );
		$save   = $request->get_param( 'save_settings' ) ?? true;

		update_option( 'zinv_onboarding_step', $step );

		if ( $step >= 4 || $save ) {
			update_option( 'zinv_onboarding_complete', true );
		}

		$general = $request->get_param( 'general' );
		if ( is_array( $general ) ) {
			$clean = [];
			foreach ( $general as $key => $value ) {
				$key = sanitize_key( $key );
				if ( '' === $key ) {
					continue;
				}
				if ( is_array( $value ) ) {
					$clean[ $key ] = array_map( 'sanitize_text_field', array_filter( $value, 'is_scalar' ) );
				} elseif ( is_scalar( $value ) ) {
					$clean[ $key ] = 'address' === $key
						? sanitize_textarea_field( (string) $value )
						: sanitize_text_field( (string) $value );
				}
			}

			update_option( 'zinv_onboarding_general', $clean );

			if ( $save ) {
				$settings_rest = new ZINV_REST_Settings( $this->namespace );
				$settings_req  = new WP_REST_Request( 'PUT' );
				$settings_req->set_body( wp_json_encode( [ 'general' => $clean ] ) );
				$settings_req->set_header( 'Content-Type', 'application/json' );
				$settings_rest->update_settings( $settings_req );
			}
		}

		$gateway = $request->get_param( 'gateway' );
		if ( is_string( $gateway ) && '' !== $gateway ) {
			$allowed_gateways = [ 'stripe', 'bank', 'paypal' ];
			if ( in_array( $gateway, $allowed_gateways, true ) ) {
				update_option( 'zinv_preferred_gateway', sanitize_text_field( $gateway ) );
			}
		}

		$payments = $request->get_param( 'payments' );
		if ( is_array( $payments ) ) {
			$allowed_payment_keys = [ 'stripe_mode', 'stripe_test_key', 'stripe_live_key', 'stripe_webhook_secret' ];
			$clean_payments = [];
			foreach ( $allowed_payment_keys as $k ) {
				if ( isset( $payments[ $k ] ) && is_string( $payments[ $k ] ) ) {
					$clean_payments[ $k ] = sanitize_text_field( $payments[ $k ] );
				}
			}
			if ( ! empty( $clean_payments ) ) {
				$settings_rest = new ZINV_REST_Settings( $this->namespace );
				$settings_req  = new WP_REST_Request( 'PUT' );
				$settings_req->set_body( wp_json_encode( [ 'payments' => $clean_payments ] ) );
				$settings_req->set_header( 'Content-Type', 'application/json' );
				$settings_rest->update_settings( $settings_req );
			}
		}

		return new WP_REST_Response( [
			'completed' => (bool) get_option( 'zinv_onboarding_complete', false ),
			'step'      => $step,
		], 200 );
	}
}
