<?php
/**
 * Affiliate Portal Integration
 *
 * @package     AffiliateWP Stripe Payouts
 * @subpackage  Integrations/Affiliate Portal
 * @copyright   Copyright (c) 2025, AffiliateWP, LLC
 * @license     GPL-2.0+
 * @since       2.29.0
 */

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

/**
 * AffiliateWP_Stripe_Payouts_Affiliate_Portal Class
 *
 * @since 2.29.0
 */
class AffiliateWP_Stripe_Payouts_Affiliate_Portal {

	/**
	 * Setup the affiliate portal integration
	 *
	 * @since 2.29.0
	 */
	public function __construct() {

		// Render the Stripe panel inside the Payout settings card's Alpine scope so it shows/hides reactively on the picker selection.
		add_action( 'affwp_portal_settings_payout_method_panel', [ $this, 'render_stripe_section' ] );

		// Handle Stripe Express Dashboard access.
		add_action( 'init', [ $this, 'process_stripe_dashboard_request' ] );

		// Handle Stripe account management link generation (for onboarding updates).
		add_action( 'init', [ $this, 'process_stripe_manage_request' ] );

		// Add notices to portal.
		add_action( 'affwp_portal_notices', [ $this, 'display_notices' ] );
	}

	/**
	 * Render the Stripe section in the Portal.
	 *
	 * @since 2.29.0
	 * @param int $affiliate_id The affiliate ID
	 * @return void
	 */
	public function render_stripe_section( $affiliate_id ) {
		// Show only when the affiliate is on Stripe, can switch to it, or has a connection to manage.
		if ( ! affwp_stripe_payouts_section_is_relevant_for_affiliate( $affiliate_id ) ) {
			return;
		}

		// Include the template.
		$template_path = dirname( __DIR__ ) . '/templates/portal-stripe-section.php';
		if ( file_exists( $template_path ) ) {
			include $template_path;
		}
	}

	/**
	 * Display notices in the affiliate portal
	 *
	 * @since 2.29.0
	 * @return void
	 */
	public function display_notices() {
		// Check for Stripe connection success/error.
		if ( isset( $_GET['stripe_connected'] ) && 'true' === $_GET['stripe_connected'] ) {
			?>
			<div class="bg-green-50 border-l-4 border-green-400 p-4 mb-4">
				<div class="flex">
					<div class="shrink-0">
						<?php \AffiliateWP\Utils\Icons::render( 'check-circle', '', [ 'class' => 'size-5 text-green-400' ] ); ?>
					</div>
					<div class="ml-3">
						<p class="text-sm text-green-700">
							<?php esc_html_e( 'Your Stripe account has been connected successfully!', 'affiliate-wp' ); ?>
						</p>
					</div>
				</div>
			</div>
			<?php
		}

		if ( isset( $_GET['stripe_manage_complete'] ) && 'true' === $_GET['stripe_manage_complete'] ) {
			?>
			<div class="bg-green-50 border-l-4 border-green-400 p-4 mb-4">
				<div class="flex">
					<div class="shrink-0">
						<?php \AffiliateWP\Utils\Icons::render( 'check-circle', '', [ 'class' => 'size-5 text-green-400' ] ); ?>
					</div>
					<div class="ml-3">
						<p class="text-sm text-green-700">
							<?php esc_html_e( 'Your Stripe account settings have been updated successfully!', 'affiliate-wp' ); ?>
						</p>
					</div>
				</div>
			</div>
			<?php
		}

		// One-time flash notices set server-side during the connect flow (never via the URL, so the
		// message can't be spoofed). Read-and-clear, then render styled by type.
		$flash = affwp_stripe_payouts_get_flash_notice();
		if ( $flash ) {
			$palette = array(
				'error'   => array( 'bg' => 'bg-red-50 border-red-400',     'icon' => 'text-red-400',   'text' => 'text-red-700',   'glyph' => 'x-circle' ),
				'success' => array( 'bg' => 'bg-green-50 border-green-400', 'icon' => 'text-green-400', 'text' => 'text-green-700', 'glyph' => 'check-circle' ),
				'info'    => array( 'bg' => 'bg-blue-50 border-blue-400',   'icon' => 'text-blue-400',  'text' => 'text-blue-700',  'glyph' => 'circle-info' ),
			);
			$tones = isset( $palette[ $flash['type'] ] ) ? $palette[ $flash['type'] ] : $palette['info'];
			?>
			<div class="border-l-4 p-4 mb-4 <?php echo esc_attr( $tones['bg'] ); ?>">
				<div class="flex">
					<div class="shrink-0">
						<?php \AffiliateWP\Utils\Icons::render( $tones['glyph'], '', [ 'class' => 'size-5 ' . $tones['icon'] ] ); ?>
					</div>
					<div class="ml-3">
						<p class="text-sm <?php echo esc_attr( $tones['text'] ); ?>"><?php echo esc_html( $flash['message'] ); ?></p>
					</div>
				</div>
			</div>
			<?php
		}
	}

	/**
	 * Handle Stripe Express Dashboard access request
	 *
	 * This method generates a direct login link to the Stripe Express Dashboard
	 * for affiliates to manage their daily operations like viewing balances and payouts.
	 *
	 * @since 2.29.0
	 * @return void
	 */
	public function process_stripe_dashboard_request() {
		if ( ! isset( $_GET['affwp_action'] ) || 'stripe_payouts_dashboard' !== $_GET['affwp_action'] ) {
			return;
		}

		if ( ! isset( $_GET['affiliate_id'] ) ) {
			return;
		}

		$affiliate_id = affwp_stripe_payouts_validate_affiliate_id( $_GET['affiliate_id'] );
		if ( is_wp_error( $affiliate_id ) ) {
			return;
		}

		// Verify nonce.
		if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( $_GET['_wpnonce'], 'affwp_stripe_payouts_dashboard_' . $affiliate_id ) ) {
			wp_die( esc_html__( 'Security check failed', 'affiliate-wp' ) );
		}

		// Generate and redirect to the Stripe Express Dashboard.
		$dashboard_link = affwp_stripe_payouts_generate_express_dashboard_link( $affiliate_id );

		$portal_url = function_exists( 'affwp_portal_get_page_url' )
			? \AffiliateWP_Affiliate_Portal\Core\Components\Portal::get_page_url( 'settings' )
			: home_url();

		if ( is_wp_error( $dashboard_link ) ) {
			affwp_stripe_payouts_set_flash_notice( $dashboard_link->get_error_message(), 'error' );
			wp_safe_redirect( $portal_url );
			exit;
		}

		// Redirect to Stripe Express Dashboard.
		wp_redirect( $dashboard_link );
		exit;
	}

	/**
	 * Handle Stripe account management link generation
	 *
	 * This method generates a Stripe Account Link for onboarding updates and compliance.
	 * Used when affiliates need to update verification info or fix account issues.
	 *
	 * @since 2.29.0
	 * @return void
	 */
	public function process_stripe_manage_request() {
		if ( ! isset( $_GET['affwp_action'] ) || 'stripe_payouts_manage' !== $_GET['affwp_action'] ) {
			return;
		}

		if ( ! isset( $_GET['affiliate_id'] ) ) {
			return;
		}

		$affiliate_id = affwp_stripe_payouts_validate_affiliate_id( $_GET['affiliate_id'] );
		if ( is_wp_error( $affiliate_id ) ) {
			return;
		}

		// Verify nonce.
		if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( $_GET['_wpnonce'], 'affwp_stripe_payouts_manage_' . $affiliate_id ) ) {
			wp_die( esc_html__( 'Security check failed', 'affiliate-wp' ) );
		}

		// Generate and redirect to the Stripe Account Link.
		$account_link = affwp_stripe_payouts_generate_account_link( $affiliate_id );

		$portal_url = function_exists( 'affwp_portal_get_page_url' )
			? \AffiliateWP_Affiliate_Portal\Core\Components\Portal::get_page_url( 'settings' )
			: home_url();

		if ( is_wp_error( $account_link ) ) {
			affwp_stripe_payouts_set_flash_notice( $account_link->get_error_message(), 'error' );
			wp_safe_redirect( $portal_url );
			exit;
		}

		wp_redirect( $account_link );
		exit;
	}
}
