<?php

namespace SplitPay\Integrations\WooCommerce\Gateways;

use SplitPay\Contracts\GatewayAdapterInterface;
use SplitPay\Core\StripeService;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class WooStripePaymentGateway implements GatewayAdapterInterface {

	public function getId(): string {
		return 'wc_stripe_payment_plugins';
	}

	public function getName(): string {
		return 'Payment Plugins for Stripe WooCommerce';
	}

	public function isActive(): bool {
		return function_exists( 'stripe_wc' );
	}

	public function isTestMode(): bool {
		$settings = get_option( 'woocommerce_stripe_api_settings' );
		return isset( $settings['mode'] ) && $settings['mode'] === 'test';
	}

	public function getSecretKey(): string {
		$settings = get_option( 'woocommerce_stripe_api_settings' );
		if ( ! is_array( $settings ) ) {
			return '';
		}

		$key = $this->isTestMode() ? 'secret_key_test' : 'secret_key_live';
		return ! empty( $settings[ $key ] ) ? $settings[ $key ] : '';
	}

	public function getTransferSecretKey(): string {
		return $this->isTestMode()
			? get_option( 'spp_pp_stripe_test_secret_key', '' )
			: get_option( 'spp_pp_stripe_live_secret_key', '' );
	}

	public function getPublicKey(): string {
		$settings = get_option( 'woocommerce_stripe_api_settings' );
		if ( ! is_array( $settings ) ) {
			return '';
		}

		$key = $this->isTestMode() ? 'publishable_key_test' : 'publishable_key_live';
		return ! empty( $settings[ $key ] ) ? $settings[ $key ] : '';
	}

	public function getWebhookSecret(): string {
		$settings = get_option( 'woocommerce_stripe_api_settings' );
		if ( ! is_array( $settings ) ) {
			return '';
		}

		$key = $this->isTestMode() ? 'webhook_secret_test' : 'webhook_secret_live';
		return ! empty( $settings[ $key ] ) ? $settings[ $key ] : '';
	}

	public function resolveChargeId( $eventOrTransaction ): string {
		if ( $eventOrTransaction instanceof \WC_Order ) {
			$secretKey = $this->getSecretKey();
			if ( empty( $secretKey ) ) {
				return '';
			}

			$pi_id = $eventOrTransaction->get_meta( '_payment_intent_id', true );
			if ( empty( $pi_id ) ) {
				$pi_id = $eventOrTransaction->get_transaction_id();
			}

			if ( empty( $pi_id ) ) {
				return '';
			}

			try {
				$stripe = new StripeService( $secretKey );
				$pi     = $stripe->retrievePaymentIntent( $pi_id );
				return $pi->latest_charge ?? '';
			} catch ( \Exception $e ) {
				$this->log( 'resolveChargeId exception: ' . $e->getMessage() );
				return '';
			}
		}

		if ( is_object( $eventOrTransaction ) && ! empty( $eventOrTransaction->latest_charge ) ) {
			return $eventOrTransaction->latest_charge;
		}

		if ( is_array( $eventOrTransaction ) && ! empty( $eventOrTransaction['latest_charge'] ) ) {
			return $eventOrTransaction['latest_charge'];
		}

		return '';
	}

	public function getPlatformAccountId(): string {
		$secretKey = $this->getSecretKey();
		if ( empty( $secretKey ) ) {
			return '';
		}

		try {
			$stripe  = new StripeService( $secretKey );
			$account = $stripe->retrieveAccount( 'self' );
			return $account->id ?? '';
		} catch ( \Exception $e ) {
			$this->log( 'getPlatformAccountId exception: ' . $e->getMessage() );
			return '';
		}
	}

	public function supportsWebhookSync(): bool {
		return true;
	}

	public function getWebhookEndpointId(): string {
		return '';
	}

	public function getStatusDetails(): array {
		$active = $this->isActive();

		if ( ! $active ) {
			return [
				'label'        => 'Inactive',
				'description'  => 'Payment Plugins for Stripe WooCommerce is not active.',
				'action_url'   => admin_url( 'plugin-install.php?s=payment-plugins-for-stripe-woocommerce&tab=search&type=term' ),
				'action_label' => 'Install',
			];
		}

		$mode = $this->isTestMode() ? 'test' : 'live';

		return [
			'label'        => 'Active',
			'description'  => sprintf( 'Running in %s mode.', $mode ),
			'action_url'   => admin_url( 'admin.php?page=wc-settings&tab=checkout&section=stripe_api' ),
			'action_label' => 'Configure',
		];
	}

	private function log( string $message ): void {
		$prefix = '[Split Pay WooStripePaymentGateway] ';
		self::safe_wcs_log( $prefix . $message );
	}

	/**
	 * See WCStripeGateway::safe_wcs_log() for the full rationale. THIS is the
	 * class where the fix matters most: this gateway is active on
	 * Payment-Plugins-only sites (e.g. danahillsboosters.com / Sand Dragon
	 * Media) which is exactly the configuration where \WC_Stripe_Logger::log()
	 * was fataling pre-3.7.3.
	 *
	 * @since 3.7.3
	 */
	private static function safe_wcs_log( string $message ): void {
		if ( class_exists( '\WC_Stripe_Logger' ) ) {
			if ( method_exists( '\WC_Stripe_Logger', 'log' ) ) {
				\WC_Stripe_Logger::log( $message );
				return;
			}
			if ( method_exists( '\WC_Stripe_Logger', 'debug' ) ) {
				\WC_Stripe_Logger::debug( $message );
				return;
			}
		}
		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( $message ); } // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
	}
}
