<?php

namespace SplitPay\Integrations\WooCommerce\Gateways;

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

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

class WCStripeGateway implements GatewayAdapterInterface {

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

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

	public function isActive(): bool {
		return class_exists( 'WC_Stripe' ) || class_exists( 'WC_Stripe_Webhook_Handler' );
	}

	public function isTestMode(): bool {
		$settings = get_option( 'woocommerce_stripe_settings' );
		return isset( $settings['testmode'] ) && $settings['testmode'] === 'yes';
	}

	public function getSecretKey(): string {
		$settings = get_option( 'woocommerce_stripe_settings' );
		if ( ! is_array( $settings ) ) {
			return '';
		}
		$key = $this->isTestMode() ? ( $settings['test_secret_key'] ?? '' ) : ( $settings['secret_key'] ?? '' );
		return (string) $key;
	}

	public function getTransferSecretKey(): string {
		$key = $this->isTestMode()
			? get_option( 'spp_wc_stripe_test_secret_key', '' )
			: get_option( 'spp_wc_stripe_live_secret_key', '' );
		if ( empty( $key ) ) {
			$key = $this->isTestMode()
				? get_option( 'stripe_test_api_secret_key', '' )
				: get_option( 'stripe_api_secret_key', '' );
		}
		return (string) $key;
	}

	public function getPublicKey(): string {
		if ( $this->isTestMode() ) {
			return (string) get_option( 'stripe_test_api_public_key', '' );
		}
		return (string) get_option( 'stripe_api_public_key', '' );
	}

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

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

	public function resolveChargeId( $eventOrTransaction ): string {
		if ( is_string( $eventOrTransaction ) ) {
			$decoded = json_decode( $eventOrTransaction );
			if ( ! $decoded || empty( $decoded->data->object->id ) ) {
				return '';
			}

			$pi_id     = $decoded->data->object->id;
			$secretKey = $this->getSecretKey();
			if ( empty( $secretKey ) ) {
				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'  => 'WooCommerce Stripe Gateway plugin is not active.',
				'action_url'   => admin_url( 'plugin-install.php?s=woocommerce-gateway-stripe&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' ),
			'action_label' => 'Configure',
		];
	}

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

	/**
	 * Mirror of BSD_SCSP_Main_Plugin::safe_wcs_log() from the legacy main class
	 * (class-bsd-split-pay-stripe-connect-woo.php:41-54), inlined per namespaced
	 * class so the new architecture doesn't depend on the legacy class load
	 * order. Guards \WC_Stripe_Logger::log() against sites running Payment
	 * Plugins' woo-stripe-payment, which declares \WC_Stripe_Logger WITHOUT a
	 * static ::log() method — calling the static there fatals.
	 *
	 * Falls back to ::debug() (which Payment Plugins does ship and which is
	 * also the deprecated-since-9.7.0 replacement on the official gateway),
	 * then to PHP error_log() so we never lose the message.
	 *
	 * @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
	}
}
