<?php

namespace PostenBringCheckout\admin\bring;

use Exception;
use PostenBringCheckout\admin\bring\models\Credentials;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Credentials
 *
 * Responsible for fetching and storing credentials
 *
 * @since 0.0.1
 */
class CredentialsService {

	/**
	 * Instance.
	 *
	 * @since 0.0.1
	 * @var CredentialsService $instance Instance
	 */
	private static $instance;

	/**
	 * Constructor
	 *
	 * @since 0.0.1
	 */
	private function __construct() {}

	/**
	 * Get instance.
	 *
	 * @return CredentialsService instance.
	 * @since 0.0.1
	 */
	public static function get_instance() {
		if ( ! isset( self::$instance ) ) {
			self::$instance = new CredentialsService();
		}
		return self::$instance;
	}

	/**
	 * Get credentials and webshopId.
	 *
	 * @return Credentials Stored credentials and webshopId.
	 * @since 0.0.1
	 */
	public function get_credentials_and_webshop_id(): Credentials {
		return new Credentials(
			get_option( 'posten-bring-checkout-apikey' ),
			get_option( 'posten-bring-checkout-webshopId' )
		);
	}

	/**
	 * Add or update credentials and webshopId.
	 *
	 * @param string $username API uid.
	 * @param string $api_key API key.
	 * @param string $webshop_id webshop id.
	 * @throws Exception If unable to store credentials.
	 * @since 0.0.1
	 */
	public function add_or_update_credentials_and_webshop_id( string $api_key, string $webshop_id ): void {
		update_option( 'posten-bring-checkout-apikey', $api_key );
		update_option( 'posten-bring-checkout-webshopId', $webshop_id );
	}

	/**
	 * Removes stored credentials and webshopId.
	 *
	 * @throws Exception If unable to remove credentials.
	 * @since 0.0.1
	 */
	public function remove_credentials(): void {
		delete_option( 'posten-bring-checkout-apikey' );
		delete_option( 'posten-bring-checkout-webshopId' );
	}
}
