<?php


namespace Simplyin\Simplyin_W_Plugin\Payments\Ajax\Card;

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

class Card_Ajax_Handler {

	public function register_ajax_hooks() {

		add_action(
			'wp_ajax_simplyin_get_card_payment_status',
			[
				$this,
				'action_get_card_payment_status',
			]
		);
		add_action(
			'wp_ajax_nopriv_simplyin_get_card_payment_status',
			[
				$this,
				'action_get_card_payment_status',
			]
		);
	}


	public function action_get_card_payment_status(): void {
		if ( isset( $_POST['ajax_token'] ) && wp_verify_nonce(
				sanitize_text_field( wp_unslash( $_POST['ajax_token'] ) ),
				'simplyin_card_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 Card_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();

			// Debug log AJAX snapshot
			try {
				simplyin()->get_simplyin_logger()->log_if_wpdebug_on(
					sprintf(
						'[card_status_ajax] order_id=%s status=%s',
						esc_html( (string) $order_id ),
						esc_html( (string) $payment_status )
					),
					'payments'
				);
			} catch ( \Throwable $e ) {
				// noop
			}

			if ( $payment_status === Payment_Status::STATUS_PAID ) {
				$ajax_response->set_payment_status_success();
				$ajax_response->send_json_exit();
				// todo set flag to block query this order
			}

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

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