<?php

namespace Simplyin\Simplyin_W_Plugin\Payments\Gateway\Model;

use Exception;
use Simplyin\Simplyin_W_Plugin\Lib\Session\Simplyin_Session;
use Simplyin\Simplyin_W_Plugin\Payments\Mappers\Payment_Method_Mapper;
use Simplyin\Simplyin_W_Plugin\Payments\Mappers\Payment_Provider_Mapper;
use Simplyin\Simplyin_W_Plugin\Payments\View_Model\Classic_Checkout\Payment_Method_Item_Provider;
use WC_Order;

class Session_Data {

	private Simplyin_Session $session_adapter;


	public function __construct() {
		$this->session_adapter = new Simplyin_Session();
	}

	/**
	 * @param Payment_Method[] $payment_methods_info_arr
	 *
	 * @return void
	 */
	public function update_payment_methods(
		array $payment_methods_info_arr
	) {
		$serialized = serialize( $payment_methods_info_arr );
		$this->session_adapter->set( 'payment_methods_in_checkout',
			$serialized );
	}

	public function get_payment_provider(): ?Payment_Method_Item_Provider {

		$serialised = (string) $this->session_adapter->get( 'payment_provider' );
		if ( $serialised !== '' ) {
			return Payment_Provider_Mapper::deserialize( $serialised );
		}

		return null;
	}

	public function update_payment_provider(
		Payment_Method_Item_Provider $payment_provider
	) {
		$serialized = Payment_Provider_Mapper::serialize( $payment_provider );
		$this->session_adapter->set( 'payment_provider',
			$serialized );
	}

	/**
	 * @return Payment_Method[]
	 */
	public function get_payment_methods(): array {

		$serialised = (string) $this->session_adapter->get( 'payment_methods_in_checkout' );
		if ( $serialised !== '' ) {
			return Payment_Method_Mapper::deserialize( $serialised );
		}

		return [];
	}

	/**
	 * @param string $method_id
	 *
	 * @return Payment_Method
	 * @throws Exception
	 */
	public function get_payment_method_info_by_id( string $method_id
	): Payment_Method {

		$methods = $this->get_payment_methods();

		foreach ( $methods as $method_model ) {
			if ( $method_id === $method_model->get_id() ) {
				return $method_model;
			}
		}


		throw new Exception( esc_html( "Method: $method_id not found in session cache" ) );
	}
}
