<?php
/**
 * Stripe SDK wrapper / factory.
 *
 * @package Donatico\Stripe
 */

declare(strict_types=1);

namespace Donatico\Stripe;

use Donatico\Exceptions\StripeException;

/**
 * Reads API keys and mode from WordPress options, validates them, and
 * exposes a ready-to-use \Stripe\StripeClient instance.
 *
 * Throw StripeException on configuration problems (missing key) so callers
 * can distinguish plugin config errors from Stripe API errors.
 */
class StripeClient {

	/** @var \Stripe\StripeClient */
	private \Stripe\StripeClient $client;

	/** @var string 'test' or 'live'. */
	private string $mode;

	/**
	 * Read settings, validate the secret key, and initialise the SDK client.
	 *
	 * @throws StripeException When the required secret key is not set.
	 */
	public function __construct() {
		$is_test    = (bool) get_option( 'donatico_stripe_test_mode', true );
		$this->mode = $is_test ? 'test' : 'live';

		$secret_key = $is_test
			? (string) get_option( 'donatico_stripe_test_secret_key', '' )
			: (string) get_option( 'donatico_stripe_live_secret_key', '' );

		if ( empty( $secret_key ) ) {
			throw new StripeException(
				$is_test
					/* translators: shown to the admin when the Stripe test key is missing */
					? esc_html__( 'Stripe test secret key is not configured. Please add it in Donatico → Settings → Stripe.', 'donatico' )
					/* translators: shown to the admin when the Stripe live key is missing */
					: esc_html__( 'Stripe live secret key is not configured. Please add it in Donatico → Settings → Stripe.', 'donatico' )
			);
		}

		$this->client = new \Stripe\StripeClient( $secret_key );
	}

	/**
	 * The underlying Stripe SDK client.
	 *
	 * @return \Stripe\StripeClient
	 */
	public function getClient(): \Stripe\StripeClient {
		return $this->client;
	}

	/**
	 * Current operating mode.
	 *
	 * @return string 'test' or 'live'.
	 */
	public function getMode(): string {
		return $this->mode;
	}

	/**
	 * @return bool
	 */
	public function isTestMode(): bool {
		return $this->mode === 'test';
	}

	/**
	 * The webhook signing secret for the current mode.
	 * A single secret is stored because each Stripe webhook endpoint (test or
	 * live) has its own signing secret — the admin stores whichever one
	 * corresponds to the active mode.
	 *
	 * @return string
	 */
	public function getWebhookSecret(): string {
		return (string) get_option( 'donatico_stripe_webhook_secret', '' );
	}

	/**
	 * The publishable key for the current mode (used in frontend JS).
	 *
	 * @return string
	 */
	public function getPublishableKey(): string {
		return $this->isTestMode()
			? (string) get_option( 'donatico_stripe_test_publishable_key', '' )
			: (string) get_option( 'donatico_stripe_live_publishable_key', '' );
	}
}
