<?php


namespace Simplyin\Simplyin_W_Plugin\Payments\Ajax\Blik;

use Simplyin\Simplyin_W_Plugin\Payments\Gateway\Model\Order_Data;
use Simplyin\Simplyin_W_Plugin\Payments\Gateway\Status\Payment_Status;

class Blik_Ajax_Handler {

	public function register_ajax_hooks() {

		add_action(
			'wp_ajax_simplyin_get_blik_payment_status',
			[
				$this,
				'action_get_blik_payment_status',
			]
		);
		add_action(
			'wp_ajax_nopriv_simplyin_get_blik_payment_status',
			[
				$this,
				'action_get_blik_payment_status',
			]
		);
	}


	public function action_get_blik_payment_status(): void {
		if ( isset( $_POST['ajax_token'] ) && wp_verify_nonce(
				sanitize_text_field( wp_unslash( $_POST['ajax_token'] ) ),
				'simplyin_blik_status'
			) ) {

			if ( isset( $_POST['order_id'] ) ) {
				$order_id = (int) sanitize_text_field( wp_unslash( $_POST['order_id'] ) );
			} else {
				$this->output_response_bad_request();
			}


			$ajax_response = new Blik_Get_Status_Ajax_Response();

			$order = wc_get_order( $order_id );
			$this->order_data = new Order_Data( $order );

			$payment = $this->order_data->get_selected_payment_type();
			if ( $error_message = $payment->get_customer_error_message() ) {
				$ajax_response->set_payment_status_failure();
				$ajax_response->set_customer_error_message( $error_message );
				$ajax_response->send_json_exit();
			}

			$payment_status_service = new Payment_Status( $this->order_data );
			$payment_status         = $payment_status_service->get_payment_status_remote();

			if ( $payment_status === Payment_Status::STATUS_PAID ) {
				$ajax_response->set_payment_status_success();
				$ajax_response->send_json_exit();
			}

			if ( $payment_status === Payment_Status::STATUS_PENDING ) {

				$ajax_response->set_payment_status_check_bank_app();
				$ajax_response->send_json_exit();
			}

			$ajax_response->set_payment_status_failure();
			$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;
	}
}
