<?php

namespace Simplyin\Simplyin_W_Plugin\Payments\Gateway\Model;

use Simplyin\Simplyin_W_Plugin\Payments\Mappers\Payment_Method_Mapper;
use WC_Order;

class Order_Data {

	private WC_Order $order;

	/**
	 * @param WC_Order $order
	 */
	public function __construct( WC_Order $order ) {
		$this->order = $order;
	}

	/**
	 * @throws \Exception
	 */
	public function get_selected_payment_method(): Payment_Method {
		$serialised = (string) $this->get_from_order_meta( '_simplyin_selected_payment_method' );

		return Payment_Method_Mapper::deserialize_single( $serialised );
	}

	/**
	 * @throws \Exception
	 */
	public function get_selected_payment_type(): Payment_Type_Interface {
		$selected_payment_method = $this->get_selected_payment_method();

		if ( $selected_payment_method instanceof Payment_Type_Interface ) {
			return $selected_payment_method;

		}
		$serialised = serialize( $selected_payment_method );
		throw new \Exception( esc_html( "Payment_Type_Interface not found: $serialised" ) );
	}


	public function get_from_order_meta( string $key ) {
		return $this->order->get_meta( $key );
	}

	public function update_order_meta( string $key, $value ) {
		$this->order->update_meta_data( $key, $value );
		$this->order->save_meta_data();
	}

	public function add_order_received_flag() {
		$this->update_order_meta( '_simplyin_order_received',
			'true' );
		$this->order->save_meta_data();
	}


	public function has_order_received_flag() {
		$flag = (string) $this->get_from_order_meta( '_simplyin_order_received' );

		return 'true' === $flag;
	}

	public function update_selected_payment_method(
		Payment_Method $payment_method_info
	) {
		$this->update_order_meta( '_simplyin_selected_payment_method',
			serialize( $payment_method_info ) );
		$this->order->save_meta_data();
	}

	public function update_selected_payment_method_type(
		Payment_Type_Interface $payment_method_type
	) {

		if ( false === $payment_method_type instanceof Payment_Method ) {
			$serialised = serialize( $payment_method_type );
			throw new \Exception( esc_html( "Payment_Method not found: $serialised" ) );
		}

		$this->update_selected_payment_method( $payment_method_type );
	}

	public function get_order(): WC_Order {
		return $this->order;
	}

	public function update_order_status(
		string $new_status,
		string $note = ''
	): bool {
		simplyin()->get_woocommerce_logger()->log_debug(
			sprintf( '[Order_Data] [update status to] [%s] [Order id: %s]',
				$new_status,
				$this->order->get_id()
			) );

		$result = $this->order->update_status( $new_status );
		$this->order->add_order_note( $note );

		simplyin()->get_woocommerce_logger()->log_debug(
			sprintf( '[update status result: %s] [Order id: %s] [Status: %s]',
				$result ? 'true' : 'false',
				$this->order->get_id(),
				$new_status
			) );

		return $result;
	}
}
