<?php

namespace Simplyin\Simplyin_W_Plugin\Payments\Ajax\Payment_Methods;

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

use Simplyin\Simplyin_W_Plugin\Payments\Gateway\Woocommerce_Blocks\Payment_Blocks_Support;

class Payment_Methods_Ajax_Handler {

	public function register_ajax_hooks() {
		add_action(
			'wp_ajax_simplyin_get_blocks_payment_methods',
			[
				$this,
				'action_get_payment_methods',
			]
		);
		add_action(
			'wp_ajax_nopriv_simplyin_get_blocks_payment_methods',
			[
				$this,
				'action_get_payment_methods',
			]
		);
	}


	public function action_get_payment_methods(): void {
		if ( isset( $_POST['ajax_token'] ) && wp_verify_nonce(
			sanitize_text_field( wp_unslash( $_POST['ajax_token'] ) ),
			'simplyin_block_payment'
		) ) {
			$ajax_response = new Payment_Methods_Ajax_Response();

			try {
				$channels = Payment_Blocks_Support::get_channels_for_blocks();
			} catch ( \Exception $e ) {
				$ajax_response->set_is_error( true );
				$ajax_response->send_json_exit();

				return;
			}

			$ajax_response->set_payment_methods( $channels );
			$ajax_response->send_json_exit();

		}

		$this->output_response_unauthorized();
	}


	private function output_response_bad_request() {
		header( 'HTTP/1.1 400 BAD REQUEST' );
		exit;
	}

	private function output_response_unauthorized() {
		header( 'HTTP/1.1 401 Unauthorized' );
		exit;
	}
}
