<?php
/**
 * Admin User Handler for FunnelKit Square Payment Gateway
 *
 * Handles user profile integration for Square payment tokens
 *
 * @package FunnelKit_Square
 * @subpackage Admin
 */

namespace FKWCSQ\Admin;

use FKWCSQ\Includes\Traits\Instance;

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

/**
 * Admin User Handler Class
 */
class User_Handler {
	use Instance;

	/**
	 * Plugin instance
	 *
	 * @var \FKWCSQ\Square
	 */
	protected $plugin;

	/**
	 * Token editor instances
	 *
	 * @var array
	 */
	protected $token_editors = array();

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->plugin = \FKWCSQ\Square::instance();

		$this->init_hooks();
	}

	/**
	 * Initialize hooks
	 */
	private function init_hooks() {
		// Wait for WooCommerce to be fully loaded
		add_action( 'woocommerce_loaded', array( $this, 'init_after_wc_loaded' ) );

		// Fallback: also try on init with higher priority
		add_action( 'init', array( $this, 'init_after_wc_loaded' ), 20 );
	}

	/**
	 * Initialize after WooCommerce is loaded
	 */
	public function init_after_wc_loaded() {
		// Prevent duplicate hook registration
		static $hooks_initialized = false;
		if ( $hooks_initialized ) {
			return;
		}
		$hooks_initialized = true;

		// Add user profile section
		add_action( 'show_user_profile', array( $this, 'add_profile_section' ) );
		add_action( 'edit_user_profile', array( $this, 'add_profile_section' ) );

		// Save profile fields
		add_action( 'personal_options_update', array( $this, 'save_profile_fields' ) );
		add_action( 'edit_user_profile_update', array( $this, 'save_profile_fields' ) );

		// Initialize token editors
		add_action( 'admin_init', array( $this, 'init_token_editors' ) );

		// Display token editors in profile section
		add_action( 'fkwcsq_square_user_profile', array( $this, 'display_token_editors' ) );

		// Display customer ID fields
		add_action( 'fkwcsq_square_user_profile', array( $this, 'display_customer_id_fields' ) );
	}

	/**
	 * Initialize token editors for each gateway
	 */
	public function init_token_editors() {
		$gateways = $this->get_tokenized_gateways();

		foreach ( $gateways as $gateway ) {
			if ( ! $gateway->supports_token_editor() ) {
				continue;
			}

			$this->token_editors[ $gateway->get_id() ] = $gateway->get_payment_tokens_handler();
		}
	}

	/**
	 * Add profile section to user edit page
	 *
	 * @param \WP_User $user User object
	 */
	public function add_profile_section( $user ) {
		if ( ! $this->is_supported() ) {
			return;
		}

		if ( ! current_user_can( 'edit_users' ) ) {
			return;
		}

		$plugin_id           = 'fkwcsq_square';
		$section_title       = $this->get_title();
		$section_description = $this->get_description();

		include FKWCSQ_PLUGIN_DIR . 'includes/admin/views/html-user-profile-section.php';
	}

	/**
	 * Display token editors
	 *
	 * @param \WP_User $user User object
	 */
	public function display_token_editors( $user ) {
		$token_editors = $this->get_token_editors();

		foreach ( $token_editors as $gateway_id => $editor ) {
			$gateway = $this->get_gateway( $gateway_id );

			// Try to get or create customer ID if gateway supports it
			if ( $gateway && method_exists( $gateway, 'supports_customer_id' ) && $gateway->supports_customer_id() ) {
				$customer_id = '';
				if ( method_exists( $gateway, 'get_customer_id' ) ) {
					$customer_id = $gateway->get_customer_id( $user->ID, array( 'autocreate' => true ) );
				}

				if ( empty( $customer_id ) ) {
					continue;
				}
			}

			$editor->display( $user->ID );
		}
	}

	/**
	 * Display customer ID fields
	 *
	 * @param \WP_User $user User object
	 */
	public function display_customer_id_fields( $user ) {
		$customer_id_fields = $this->get_customer_id_fields( $user->ID );

		foreach ( $customer_id_fields as $field ) {
			$label = $field['label'];
			$name  = $field['name'];
			$value = $field['value'];

			include FKWCSQ_PLUGIN_DIR . 'includes/admin/views/html-user-profile-field-customer-id.php';
		}
	}

	/**
	 * Save profile fields
	 *
	 * @param int $user_id User ID
	 */
	public function save_profile_fields( $user_id ) {
		if ( ! $this->is_supported() || ! current_user_can( 'edit_users' ) ) {
			return;
		}

		// Check if this is a token save request
		if ( isset( $_POST['fkwcsq_save_tokens'] ) && isset( $_POST['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'update-user_' . $user_id ) ) {
			// Save token data
			$this->save_tokens( $user_id );
		}

		// Save customer IDs
		$this->save_customer_ids( $user_id );
	}

	/**
	 * Save tokens from token editors
	 *
	 * @param int $user_id User ID
	 */
	protected function save_tokens( $user_id ) {
		$token_editors = $this->get_token_editors();

		foreach ( $token_editors as $editor ) {
			$editor->save( $user_id );
		}
	}

	/**
	 * Save customer IDs
	 *
	 * @param int $user_id User ID
	 */
	protected function save_customer_ids( $user_id ) {
		// Verify nonce for security
		if ( ! isset( $_POST['_wpnonce'] ) || ! isset( $_POST['fkwcsq_save_customer_ids'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'update-user_' . $user_id ) ) {
			return;
		}

		foreach ( $this->get_tokenized_gateways() as $gateway ) {
			if ( ! $gateway->supports_customer_id() ) {
				continue;
			}

			$meta_name = $gateway->get_customer_id_user_meta_name();
			if ( isset( $_POST[ $meta_name ] ) ) {
				$customer_id = sanitize_text_field( wp_unslash( $_POST[ $meta_name ] ) );
				$gateway->update_customer_id( $user_id, trim( $customer_id ) );
			}
		}
	}

	/**
	 * Get token editors
	 *
	 * @return array
	 */
	protected function get_token_editors() {
		return $this->token_editors;
	}

	/**
	 * Get tokenized gateways
	 *
	 * @return array
	 */
	protected function get_tokenized_gateways() {
		$gateways = array();

		// Get Square gateway
		$gateway = $this->get_gateway( 'fkwcsq_square' );

		if ( $gateway ) {
			// Check if gateway is enabled by looking at settings
			$is_enabled = false;
			if ( method_exists( $gateway, 'is_enabled' ) ) {
				$is_enabled = $gateway->is_enabled();
			} else {
				// Fallback: check settings directly
				$settings   = get_option( 'woocommerce_fkwcsq_square_settings', array() );
				$is_enabled = isset( $settings['enabled'] ) && $settings['enabled'] === 'yes';
			}

			if ( $is_enabled &&
				method_exists( $gateway, 'supports_tokenization' ) && $gateway->supports_tokenization() &&
				( ( method_exists( $gateway, 'supports_token_editor' ) && $gateway->supports_token_editor() ) ||
					( method_exists( $gateway, 'supports_customer_id' ) && $gateway->supports_customer_id() ) ) ) {
				$gateways[] = $gateway;
			}
		}

		return $gateways;
	}

	/**
	 * Get gateway instance
	 *
	 * @param string $gateway_id Gateway ID
	 * @return \WC_Payment_Gateway|null
	 */
	protected function get_gateway( $gateway_id ) {
		if ( ! function_exists( 'WC' ) || ! WC() || ! WC()->payment_gateways() ) {
			return null;
		}

		$gateways = WC()->payment_gateways()->payment_gateways();
		return isset( $gateways[ $gateway_id ] ) ? $gateways[ $gateway_id ] : null;
	}

	/**
	 * Get customer ID fields
	 *
	 * @param int $user_id User ID
	 * @return array
	 */
	protected function get_customer_id_fields( $user_id ) {
		$fields = array();

		foreach ( $this->get_tokenized_gateways() as $gateway ) {
			if ( ! method_exists( $gateway, 'supports_customer_id' ) || ! $gateway->supports_customer_id() ) {
				continue;
			}

			$meta_key = method_exists( $gateway, 'get_customer_id_user_meta_name' ) ? $gateway->get_customer_id_user_meta_name() : '_square_customer_id';
			$label    = __( 'Customer ID', 'funnelkit-payment-gateway-square-for-woocommerce' );

			$customer_id = '';
			if ( method_exists( $gateway, 'get_customer_id' ) ) {
				$customer_id = $gateway->get_customer_id( $user_id, array( 'autocreate' => false ) );
			}

			$fields[] = array(
				'label' => $label,
				'name'  => $meta_key,
				'value' => $customer_id,
			);
		}

		return $fields;
	}

	/**
	 * Get section title
	 *
	 * @return string
	 */
	protected function get_title() {
		$title = __( 'Square Payment Tokens', 'funnelkit-payment-gateway-square-for-woocommerce' );

		return apply_filters( 'fkwcsq_admin_user_profile_title', $title, $this->plugin );
	}

	/**
	 * Get section description
	 *
	 * @return string
	 */
	protected function get_description() {
		return apply_filters( 'fkwcsq_admin_user_profile_description', '', $this->plugin );
	}

	/**
	 * Check if user profile section is supported
	 *
	 * @return bool
	 */
	protected function is_supported() {
		// Check if WooCommerce is loaded
		if ( ! function_exists( 'WC' ) || ! WC() ) {
			return false;
		}

		$gateways       = $this->get_tokenized_gateways();
		$should_display = ! empty( $gateways );

		return apply_filters( 'fkwcsq_display_user_profile', $should_display, $this->plugin );
	}
}
