<?php
/**
 * PSP Settings Tab
 *
 * @package AmbassadorHub\Admin\Settings\Tabs
 */

namespace AmbassadorHub\Admin\Settings\Tabs;

use AmbassadorHub\Admin\InlineAssets;
use AmbassadorHub\Admin\Settings\AbstractTab;
use AmbassadorHub\Connectors\ConnectorRegistry;

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

/**
 * PSP (Payment Service Provider) settings tab.
 *
 * Shows every installed PSP connector as a row with logo, name, optional
 * description, an enable/disable button, and a Configure button that expands
 * the connector's settings panel inline.
 *
 * Connector plugins register their section via `ambh_psp_settings_sections`.
 */
final class PaymentsTab extends AbstractTab {

	public function __construct() {
		$this->id       = 'payments';
		$this->label    = __( 'Payments', 'ambassadorhub' );
		$this->priority = 20;

		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
	}

	/**
	 * Enqueue this tab's inline CSS/JS.
	 *
	 * Hooked to admin_enqueue_scripts (from the constructor, which runs early
	 * enough via Registry::get_tabs()) so wp_add_inline_style()/
	 * wp_add_inline_script() are attached before admin_print_styles fires —
	 * by the time render() runs later, that hook has already passed.
	 *
	 * @return void
	 */
	public function enqueue_assets(): void {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only page/tab check.
		$page = isset( $_GET['page'] ) ? sanitize_key( $_GET['page'] ) : '';
		if ( 'ambassadorhub-settings' !== $page ) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only tab-selection check.
		$tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : '';
		if ( $this->id !== $tab ) {
			return;
		}

		InlineAssets::style(
			'.ambh-psp-list {
				margin: -28px -32px 0;
			}

			@media screen and (max-width: 782px) {
				.ambh-psp-list {
					margin: -16px -18px 0;
				}
			}

			.ambh-conn-status {
				display: flex;
				align-items: center;
				gap: 8px;
				margin-top: 16px;
				padding: 10px 14px;
				border-radius: 4px;
				font-size: 13px;
				line-height: 1.4;
			}
			.ambh-conn-status--ok    { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
			.ambh-conn-status--error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
			.ambh-conn-status__icon  { font-size: 15px; flex-shrink: 0; }
			.ambh-conn-status__sub   { opacity: .75; }

			.ambh-psp-row {
				border-bottom: 1px solid #dcdcde;
			}
			.ambh-psp-row:last-child { border-bottom: none; }

			.ambh-psp-row__inner {
				display: flex;
				align-items: center;
				gap: 16px;
				padding: 14px 18px;
				background: #fff;
			}

			.ambh-psp-row__logo {
				flex: 0 0 52px;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.ambh-psp-logo {
				display: block;
				width: 48px;
				height: 40px;
				object-fit: contain;
				object-position: center;
			}

			.ambh-psp-logo-avatar {
				display: flex; align-items: center; justify-content: center;
				width: 40px; height: 40px; border-radius: 8px;
				background: #0073aa; color: #fff;
				font-family: Arial, sans-serif; font-size: 18px; font-weight: 700;
				line-height: 1; user-select: none;
			}
			.ambh-psp-logo-avatar[data-letter="A"],.ambh-psp-logo-avatar[data-letter="N"] { background: #e74c3c; }
			.ambh-psp-logo-avatar[data-letter="B"],.ambh-psp-logo-avatar[data-letter="O"] { background: #e67e22; }
			.ambh-psp-logo-avatar[data-letter="C"],.ambh-psp-logo-avatar[data-letter="P"] { background: #0073aa; }
			.ambh-psp-logo-avatar[data-letter="D"],.ambh-psp-logo-avatar[data-letter="Q"] { background: #8e44ad; }
			.ambh-psp-logo-avatar[data-letter="E"],.ambh-psp-logo-avatar[data-letter="R"] { background: #27ae60; }
			.ambh-psp-logo-avatar[data-letter="F"],.ambh-psp-logo-avatar[data-letter="S"] { background: #2980b9; }
			.ambh-psp-logo-avatar[data-letter="G"],.ambh-psp-logo-avatar[data-letter="T"] { background: #16a085; }
			.ambh-psp-logo-avatar[data-letter="H"],.ambh-psp-logo-avatar[data-letter="U"] { background: #c0392b; }
			.ambh-psp-logo-avatar[data-letter="I"],.ambh-psp-logo-avatar[data-letter="V"] { background: #d35400; }
			.ambh-psp-logo-avatar[data-letter="J"],.ambh-psp-logo-avatar[data-letter="W"] { background: #7f8c8d; }
			.ambh-psp-logo-avatar[data-letter="K"],.ambh-psp-logo-avatar[data-letter="X"] { background: #1abc9c; }
			.ambh-psp-logo-avatar[data-letter="L"],.ambh-psp-logo-avatar[data-letter="Y"] { background: #6c3483; }
			.ambh-psp-logo-avatar[data-letter="M"],.ambh-psp-logo-avatar[data-letter="Z"] { background: #1e8449; }

			.ambh-psp-row__info {
				flex: 1 1 auto;
				min-width: 0;
			}
			.ambh-psp-row__name { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
			.ambh-psp-row__description {
				margin: 3px 0 0;
				font-size: 12px;
				color: #646970;
				line-height: 1.4;
			}

			.ambh-psp-badge {
				display: inline-block;
				padding: 2px 8px; border-radius: 3px;
				font-size: 11px; font-weight: 500;
				white-space: nowrap;
			}
			.ambh-psp-badge--active       { background: #d4edda; color: #155724; }
			.ambh-psp-badge--configured   { background: #cce5ff; color: #004085; }
			.ambh-psp-badge--unconfigured { background: #f0f0f1; color: #646970; }
			.ambh-psp-badge--error        { background: #f8d7da; color: #721c24; }

			.ambh-psp-row__actions {
				flex: 0 0 auto;
				display: flex;
				align-items: center;
				gap: 8px;
			}

			.ambh-psp-inline-note {
				display: inline-block;
				max-width: 220px;
				font-size: 12px;
				line-height: 1.4;
				color: #646970;
			}

			.ambh-psp-btn-configure .ambh-psp-chevron {
				display: inline-block;
				margin-left: 4px;
				transition: transform .2s ease;
			}
			.ambh-psp-btn-configure[aria-expanded="true"] .ambh-psp-chevron { transform: rotate(180deg); }

			.ambh-psp-settings-panel {
				background: #f9f9f9;
				border-top: 1px solid #dcdcde;
				padding: 20px 24px;
			}'
		);

		InlineAssets::script(
			"(function () {
				document.querySelectorAll( '.ambh-psp-btn-configure' ).forEach( function ( btn ) {
					btn.addEventListener( 'click', function () {
						var panelId  = btn.getAttribute( 'data-target' );
						var panel    = document.getElementById( panelId );
						var expanded = btn.getAttribute( 'aria-expanded' ) === 'true';

						panel.hidden = expanded;
						btn.setAttribute( 'aria-expanded', expanded ? 'false' : 'true' );
					} );
				} );
			} )();"
		);
	}

	/**
	 * Handle enable / disable form submissions.
	 *
	 * @return void
	 */
	public function handle_submission(): void {
		if ( ! isset( $_POST['ambh_psp_action'] ) ) {
			return;
		}

		if (
			! isset( $_POST['ambh_psp_nonce'] ) ||
			! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['ambh_psp_nonce'] ) ), 'ambh_psp_enable' )
		) {
			wp_die( esc_html__( 'Security check failed.', 'ambassadorhub' ) );
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to perform this action.', 'ambassadorhub' ) );
		}

		$action       = sanitize_key( wp_unslash( $_POST['ambh_psp_action'] ) );
		$connector_id = sanitize_key( wp_unslash( $_POST['ambh_psp_connector_id'] ?? '' ) );

		if ( 'enable' === $action && $connector_id ) {
			update_option( 'ambh_active_connector_psp', $connector_id );
		} elseif ( 'disable' === $action && 'free' !== $connector_id ) {
			update_option( 'ambh_active_connector_psp', '' );
		}

		wp_safe_redirect(
			add_query_arg(
				array(
					'page'    => 'ambassadorhub-settings',
					'tab'     => 'payments',
					'updated' => '1',
				),
				admin_url( 'admin.php' )
			)
		);
		exit;
	}

	/**
	 * Render the PSP tab.
	 *
	 * Collects sections from `ambh_psp_settings_sections` and renders each
	 * connector as a table row. The settings panel is hidden by default and
	 * toggled open by the Configure button.
	 *
	 * @return void
	 */
	public function render(): void {
		/**
		 * Filter the list of PSP settings sections.
		 *
		 * Each item must be an associative array with these keys:
		 *
		 * - 'connector_id'  (string)   Connector ID (from ConnectorInterface::get_id()).
		 * - 'label'         (string)   Human-readable connector name.
		 * - 'description'   (string)   Optional. Short description shown below the name.
		 * - 'render'        (callable) Outputs the settings form for this connector.
		 *
		 * The logo is sourced from ConnectorInterface::get_logo().
		 *
		 * @param array<int, array{connector_id: string, label: string, description?: string, render: callable}> $sections
		 */
		$sections      = $this->get_psp_sections();
		$active_psp_id = (string) get_option( 'ambh_active_connector_psp', '' );
		$page_url      = admin_url( 'admin.php?page=ambassadorhub-settings&tab=payments' );

		if ( empty( $sections ) ) {
			?>
			<p class="description">
				<?php esc_html_e( 'No PSP connectors are installed. Install a payment provider connector plugin to get started.', 'ambassadorhub' ); ?>
			</p>
			<?php
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only display flag set by our own redirect.
		if ( isset( $_GET['updated'] ) && '1' === $_GET['updated'] ) {
			?>
			<div class="notice notice-success is-dismissible inline">
				<p><?php esc_html_e( 'Payment method settings saved.', 'ambassadorhub' ); ?></p>
			</div>
			<?php
		}
		?>
		<div class="ambh-psp-list">
		<?php
		foreach ( $sections as $section ) :
			$connector_id = (string) ( $section['connector_id'] ?? '' );
			$connector    = $connector_id ? ( ConnectorRegistry::get_all()[ $connector_id ] ?? null ) : null;
			$label        = $connector ? $connector::get_label() : (string) ( $section['label'] ?? $connector_id );
			$description  = $connector ? $connector::get_description() : (string) ( $section['description'] ?? '' );
			$render       = $section['render'] ?? null;
			$row_id       = 'ambh-psp-' . sanitize_html_class( $connector_id );
			$panel_id     = $row_id . '-settings';
			$is_test_psp  = 'free' === $connector_id;
			$is_available = $connector && $connector::is_available();
			$is_active_db = '' !== $active_psp_id && $active_psp_id === $connector_id;
			$is_active    = $is_active_db && $is_available;
			$logo_url     = $connector ? $connector::get_logo() : '';
			?>
		<div class="ambh-psp-row" id="<?php echo esc_attr( $row_id ); ?>">
			<div class="ambh-psp-row__inner">

				<!-- Logo -->
				<div class="ambh-psp-row__logo">
					<?php if ( $logo_url ) : ?>
						<img
							src="<?php echo esc_url( $logo_url ); ?>"
							alt="<?php echo esc_attr( $label ); ?>"
							class="ambh-psp-logo"
						/>
					<?php else : ?>
						<?php $first_letter = mb_strtoupper( mb_substr( $label, 0, 1 ) ); ?>
						<span
							class="ambh-psp-logo-avatar"
							data-letter="<?php echo esc_attr( $first_letter ); ?>"
							aria-hidden="true"
						><?php echo esc_html( $first_letter ); ?></span>
					<?php endif; ?>
				</div>

				<!-- Name, description + status badge -->
				<div class="ambh-psp-row__info">
					<div class="ambh-psp-row__name">
						<strong><?php echo esc_html( $label ); ?></strong>
						<?php if ( $is_active ) : ?>
							<span class="ambh-psp-badge ambh-psp-badge--active"><?php esc_html_e( 'Active', 'ambassadorhub' ); ?></span>
						<?php elseif ( $is_active_db && ! $is_available ) : ?>
							<span class="ambh-psp-badge ambh-psp-badge--error"><?php esc_html_e( 'Active · Connection error', 'ambassadorhub' ); ?></span>
						<?php elseif ( $is_available ) : ?>
							<span class="ambh-psp-badge ambh-psp-badge--configured"><?php esc_html_e( 'Configured', 'ambassadorhub' ); ?></span>
						<?php else : ?>
							<span class="ambh-psp-badge ambh-psp-badge--unconfigured"><?php esc_html_e( 'Not configured', 'ambassadorhub' ); ?></span>
						<?php endif; ?>
					</div>
					<?php if ( $description ) : ?>
						<p class="ambh-psp-row__description"><?php echo esc_html( $description ); ?></p>
					<?php endif; ?>
				</div>

				<!-- Actions -->
				<div class="ambh-psp-row__actions">
					<?php if ( is_callable( $render ) ) : ?>
						<button
							type="button"
							class="button ambh-psp-btn-configure"
							aria-expanded="false"
							aria-controls="<?php echo esc_attr( $panel_id ); ?>"
							data-target="<?php echo esc_attr( $panel_id ); ?>"
						>
							<?php esc_html_e( 'Configure', 'ambassadorhub' ); ?>
							<span class="ambh-psp-chevron" aria-hidden="true">&#9660;</span>
						</button>
					<?php endif; ?>

					<form method="post" action="<?php echo esc_url( $page_url ); ?>">
						<?php wp_nonce_field( 'ambh_psp_enable', 'ambh_psp_nonce' ); ?>
						<input type="hidden" name="ambh_psp_connector_id" value="<?php echo esc_attr( $connector_id ); ?>">
						<?php if ( $is_active_db && ! $is_test_psp ) : ?>
							<input type="hidden" name="ambh_psp_action" value="disable">
							<button type="submit" class="button ambh-psp-btn-disable">
								<?php esc_html_e( 'Disable', 'ambassadorhub' ); ?>
							</button>
						<?php elseif ( ! $is_active_db ) : ?>
							<input type="hidden" name="ambh_psp_action" value="enable">
							<button
								type="submit"
								class="button button-primary ambh-psp-btn-enable"
								<?php disabled( ! $is_available ); ?>
								<?php if ( ! $is_available ) : ?>
									title="<?php esc_attr_e( 'Configure this payment method before enabling it.', 'ambassadorhub' ); ?>"
								<?php endif; ?>
							>
								<?php esc_html_e( 'Enable', 'ambassadorhub' ); ?>
							</button>
						<?php else : ?>
							<span class="ambh-psp-inline-note">
								<?php esc_html_e( 'Enable another provider to switch away from test mode.', 'ambassadorhub' ); ?>
							</span>
						<?php endif; ?>
					</form>
				</div>
			</div><!-- .ambh-psp-row__inner -->

			<!-- Expandable settings panel -->
			<?php if ( is_callable( $render ) ) : ?>
			<div class="ambh-psp-settings-panel" id="<?php echo esc_attr( $panel_id ); ?>" hidden>
				<?php call_user_func( $render ); ?>
			</div>
			<?php endif; ?>
		</div><!-- .ambh-psp-row -->
		<?php endforeach; ?>
		</div><!-- .ambh-psp-list -->
		<?php
	}

	/**
	 * Build the list of PSP rows for the settings tab.
	 *
	 * Connectors that register settings sections keep their existing order and
	 * inline settings panels. PSP connectors without a settings section, such as
	 * the built-in test connector, are appended as simple enable/disable rows.
	 *
	 * @return array<int, array{connector_id: string, label?: string, description?: string, render?: callable}>
	 */
	private function get_psp_sections(): array {
		$sections       = apply_filters( 'ambh_psp_settings_sections', array() );
		$sections_by_id = array();

		foreach ( $sections as $section ) {
			$connector_id = (string) ( $section['connector_id'] ?? '' );

			if ( '' === $connector_id ) {
				continue;
			}

			$sections_by_id[ $connector_id ] = $section;
		}

		foreach ( ConnectorRegistry::get_by_type( 'psp' ) as $connector_id => $connector ) {
			if ( isset( $sections_by_id[ $connector_id ] ) ) {
				continue;
			}

			$sections_by_id[ $connector_id ] = array(
				'connector_id' => $connector_id,
				'label'        => $connector::get_label(),
				'description'  => $connector::get_description(),
			);
		}

		return array_values( $sections_by_id );
	}
}
