<?php

namespace Simplyin\Simplyin_W_Plugin\Payments\Gateway\Webhook;

use Simplyin\Simplyin_W_Plugin\Payments\Gateway\Model\Order_Data;
use Simplyin\Simplyin_W_Plugin\Payments\Gateway\Model\Payment_Type_Interface;

class Payment_Status {

	public const STATUS_PENDING = 'PENDING';

	public const STATUS_PAID = 'PAID';

	public const STATUS_CANCELED = 'CANCELED';

	public const STATUS_REJECTED = 'REJECTED';

	public const STATUS_REFUNDED = 'REFUNDED';


	private Order_Data $order_data;
	private Payment_Type_Interface $payment_type;

	/**
	 * @param Order_Data $order_data
	 */
	public function __construct( Order_Data $order_data ) {
		$this->order_data   = $order_data;
		$this->payment_type = $this->order_data->get_selected_payment_type();
	}

	private function refresh() {
		$this->payment_type = $this->order_data->get_selected_payment_type();

	}

	public function get_payment_status(): string {
		$paymentStatus = $this->payment_type->get_payment_status();

		return $paymentStatus ?? self::STATUS_PENDING;
	}

	public function update_payment_status( string $new_payment_status ) {

		if ( ! in_array( $new_payment_status,
			$this->get_simplyin_payment_status_allowable_values() ) ) {
			throw new \Exception( esc_html( "Unknown status: $new_payment_status" ) );
		}

		$this->refresh();

		$current_payment_status = $this->get_payment_status();

		if ( $current_payment_status === self::STATUS_PAID ) {
			throw new \Exception( esc_html( "Current status is: $current_payment_status. Can't change to: $new_payment_status" ) );
		}

		$this->payment_type->set_payment_status( $new_payment_status );
		$this->order_data->update_selected_payment_method_type( $this->payment_type );

		simplyin()->get_simplyin_logger()->log_if_wpdebug_on(
			sprintf( "[Payment_Status] [update_payment_status] %s",
				wp_json_encode( [
					'old' => $current_payment_status,
					'new' => $new_payment_status,

				] ),
			),
			'payments' );
	}


	public function map_wc_status( string $simplyin_status ): string {
		$map = [
			self::STATUS_PENDING  => 'wc-on-hold',
			self::STATUS_PAID     => 'wc-processing',
			self::STATUS_CANCELED => 'wc-failed',
			self::STATUS_REJECTED => 'wc-failed',
			self::STATUS_REFUNDED => 'wc-refunded',
		];

		if ( ! isset( $map[ $simplyin_status ] ) ) {
			throw new \Exception( esc_html( "Unknown status: $simplyin_status" ) );
		}

		return $map[ $simplyin_status ];
	}


	public function get_simplyin_payment_status_allowable_values() {
		return [
			self::STATUS_PENDING,
			self::STATUS_PAID,
			self::STATUS_CANCELED,
			self::STATUS_REJECTED,
			self::STATUS_REFUNDED,
		];
	}

}
