<?php
/**
 * Class SessionStorage
 *
 * @package DhlPolska\Point
 */

namespace DhlPolska\Point;

use DhlPolska\Shipment\ShipmentData;

class SessionStorage {

	/**
	 * @return \WC_Session|\WC_Session_Handler
	 */
	private function get_session() {
		return WC()->session ?? new \WC_Session_Handler(); /** @phpstan-ignore-line */
	}

	/**
	 * @param string $key   .
	 * @param string $value .
	 *
	 * @return void
	 */
	private function set( string $key, string $value ): void {
		$this->get_session()->set( $key, $value );
	}

	/**
	 * @param string $key .
	 *
	 * @return string
	 */
	private function get( string $key ): string {
		return (string) $this->get_session()->get( $key );
	}

	/**
	 * @param array<string, string> $data .
	 *
	 * @return void
	 */
	public function set_parcelshop_data_from_fields( array $data ): void {
		foreach ( $this->get_fields_map() as $field ) {
			if ( isset( $data[ $field ] ) ) {
				$this->set( $field, (string) $data[ $field ] );
			}
		}
	}

	/**
	 * @return array<string, string>
	 */
	public function get_parcelshop_data(): array {
		return [
			'id'         => $this->get( CheckoutChoosePointField::FIELD_PARCELSHOP_ID ),
			'sap'        => $this->get( CheckoutChoosePointField::FIELD_PARCELSHOP_SAP ),
			'name'       => $this->get( CheckoutChoosePointField::FIELD_PARCELSHOP_NAME ),
			'zip'        => $this->get( CheckoutChoosePointField::FIELD_PARCELSHOP_ZIP ),
			'street'     => $this->get( CheckoutChoosePointField::FIELD_PARCELSHOP_STREET ),
			'city'       => $this->get( CheckoutChoosePointField::FIELD_PARCELSHOP_CITY ),
			'streetNo'   => $this->get( CheckoutChoosePointField::FIELD_PARCELSHOP_STREET_NO ),
			'houseNo'    => $this->get( CheckoutChoosePointField::FIELD_PARCELSHOP_HOUSE_NO ),
			'postnummer' => $this->get( CheckoutChoosePointField::FIELD_PARCELSHOP_POSTNUMMER ),
		];
	}

	/**
	 * @param string $value .
	 *
	 * @return void
	 */
	public function set_api_error( string $value ): void {
		$this->set( CheckoutChoosePointField::FIELD_API_ERROR, $value );
	}

	/**
	 * @return void
	 */
	public function clear_parcelshop_data(): void {
		foreach ( $this->get_fields_map() as $field ) {
			$this->set( $field, '' );
		}

		$this->set_api_error( 'no' );
	}

	/**
	 * @return string
	 */
	public function get_api_error(): string {
		return $this->get( CheckoutChoosePointField::FIELD_API_ERROR );
	}

	/**
	 * @return string[]
	 */
	private function get_fields_map(): array {
		return [
			ShipmentData::OPTION_PARCELSHOP_ID,
			ShipmentData::OPTION_PARCELSHOP_SAP,
			ShipmentData::OPTION_PARCELSHOP_NAME,
			ShipmentData::OPTION_PARCELSHOP_ZIP,
			ShipmentData::OPTION_PARCELSHOP_STREET,
			ShipmentData::OPTION_PARCELSHOP_CITY,
			ShipmentData::OPTION_PARCELSHOP_STREET_NO,
			ShipmentData::OPTION_PARCELSHOP_HOUSE_NO,
			ShipmentData::OPTION_PARCELSHOP_POSTNUMMER,
		];
	}
}
